Tag Archives: const
C++ || Char Array – Convert Text Contained In A Character Array From Lower To UPPERCASE
This program demonstrates how to switch text which is contained in a char array from lower to UPPERCASE. This program also demonstrates how to convert all of the text contained in a char array to lower/UPPERCASE.
REQUIRED KNOWLEDGE FOR THIS PROGRAM
Character Arrays
Cin.getline
Islower
Isupper
Tolower
Toupper
Strlen
While Loops
For Loops
Constant Variables
Setw
Using a constant integer value, this program first asks the user to enter in 3 lines of text they wish to convert from lower to UPPERCASE. Upon obtaining the information from the user, the program then converts all the text which was placed into the character array from lower to uppercase in the following order:
(1) Switches the text from lower to UPPERCASE
(2) Converts all the text to UPPERCASE
(3) Converts all the text to lowercase
After each conversion is complete, the program displays the updated information to the screen via cout.
NOTE: On some compilers, you may have to add #include < cstdlib>, #include < cctype>, and #include < cstring> in order for the code to compile.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 |
#include <iostream> #include <iomanip> using namespace std; // constant value const int NUM_NAMES = 3; // function prototype void ConvertLowerToUpper(char names[][30]); void ConvertAllToUpper(char names[][30]); void ConvertAllToLower(char names[][30]); int main() { // declare variable // this is a 2-D char array, which by default, has // the ability to hold 3 names, each 30 characters long char names[NUM_NAMES][30]; // get data from user cout << "Please enter "<<NUM_NAMES<<" line(s) of text you wish to convert from lower to UPPERCASE:nt"; for(int index=0; index < NUM_NAMES; ++index) { cout<<"#"<< index+1 <<": "; cin.getline(names[index],30); cout<< "t"; } // create a line seperator cout<<endl; cout.fill('-'); cout<<left<<setw(30)<<""<<right<<setw(30)<<""<<endl; // re-display the input to the screen cout << "nThis is what you entered into the system:nt"; for(int index=0; index < NUM_NAMES; ++index) { cout<<"Text #"<< index+1 <<": "<<names[index]<<endl; cout<< "t"; } // create a line seperator cout<<endl; cout.fill('-'); cout<<left<<setw(30)<<""<<right<<setw(30)<<""<<endl; // display the switched lower to UPPERCASE text to the user cout << "nThis is the information switched from lower to UPPERCASE:nt"; // function declaration ConvertLowerToUpper(names); for(int index=0; index < NUM_NAMES; ++index) { cout<<"Text #"<< index+1 <<": "<<names[index]<<endl; cout<< "t"; } // create a line seperator cout<<endl; cout.fill('-'); cout<<left<<setw(30)<<""<<right<<setw(30)<<""<<endl; // display the 'all UPPERCASE' converted text to the user cout << "nThis is the information converted to all UPPERCASE:nt"; // function declaration ConvertAllToUpper(names); for(int index=0; index < NUM_NAMES; ++index) { cout<<"Text #"<< index+1 <<": "<<names[index]<<endl; cout<< "t"; } // create a line seperator cout<<endl; cout.fill('-'); cout<<left<<setw(30)<<""<<right<<setw(30)<<""<<endl; // display the 'all lowercase' converted text to the user cout << "nThis is the information converted to all lowercase:nt"; // function declaration ConvertAllToLower(names); for(int index=0; index < NUM_NAMES; ++index) { cout<<"Text #"<< index+1 <<": "<<names[index]<<endl; cout<< "t"; } return 0; }// end of main void ConvertLowerToUpper(char names[][30]) { int index=0; // increment thru the current char array index while(index < NUM_NAMES) { // increment thru each letter within the current char array index for(int currentChar=0; currentChar < strlen(names[index]); ++currentChar) { // checks each letter in the current array index // to see if its lower or UPPERCASE // if its lowercase, change to UPPERCASE if (islower(names[index][currentChar])) { names[index][currentChar] = toupper(names[index][currentChar]); } else // if its UPPERCASE, change to lowercase { names[index][currentChar] = tolower(names[index][currentChar]); } } ++index; } }// end of ConvertLowerToUpper void ConvertAllToUpper(char names[][30]) { int index=0; // increment thru the current char array index while(index < NUM_NAMES) { // increment thru each letter within the current char array index for(int currentChar=0; currentChar < strlen(names[index]); ++currentChar) { // checks each letter in the current array index // to see if its lower or UPPERCASE // if its lowercase, change to UPPERCASE if (islower(names[index][currentChar])) { names[index][currentChar] = toupper(names[index][currentChar]); } } ++index; } }// end of ConvertAllToUpper void ConvertAllToLower(char names[][30]) { int index=0; // increment thru the current char array index while(index < NUM_NAMES) { // increment thru each letter within the current char array index for(int currentChar=0; currentChar < strlen(names[index]); ++currentChar) { // checks each letter in the current array index // to see if its lower or UPPERCASE // if its UPPERCASE, change to lowercase if (isupper(names[index][currentChar])) { names[index][currentChar] = tolower(names[index][currentChar]); } } ++index; } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
Click here to see how cin.getline works.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output
Please enter 3 line(s) of text you wish to convert from lower to UPPERCASE:
#1: I StriKe hiM a heAVy bloW.
#2: When cAn the neRve ShinE?
#3: My Programming Notes.------------------------------------------------------------
This is what you entered into the system:
Text #1: I StriKe hiM a heAVy bloW.
Text #2: When cAn the neRve ShinE?
Text #3: My Programming Notes.------------------------------------------------------------
This is the information switched from lower to UPPERCASE:
Text #1: i sTRIkE HIm A HEavY BLOw.
Text #2: wHEN CaN THE NErVE sHINe?
Text #3: mY pROGRAMMING nOTES.------------------------------------------------------------
This is the information converted to all UPPERCASE:
Text #1: I STRIKE HIM A HEAVY BLOW.
Text #2: WHEN CAN THE NERVE SHINE?
Text #3: MY PROGRAMMING NOTES.------------------------------------------------------------
This is the information converted to all lowercase:
Text #1: i strike him a heavy blow.
Text #2: when can the nerve shine?
Text #3: my programming notes.
C++ || Class – A Simple Calculator Implementation Using A Class, Enum List, Typedef & Header Files
The following is another homework assignment which was presented in a programming class, that was used to introduce the concept of the class data structure, which is very similar to the struct data structure.
REQUIRED KNOWLEDGE FOR THIS PROGRAM
Header Files - How To Use Them
Class - Data Structure
Enumerated List
Typedef
Do/While Loop
Passing a Value By Reference
Constant Variables
Atoi - Convert String To Int Value
This is an interactive program which simulates a basic arithmetic calculator, where the user has the option of selecting from 9 modes of operation. Of those modes, the user has the option of adding, subtracting, multiplying, and dividing two numbers together. Also included in the calculator is a mode which deducts percentages from any given variable the user desires, so for example, if the user wanted to deduct 23% from the number 87, the program would display the reduced value of 66.99.
A sample of the menu is as followed:
(Where the user would enter numbers 1-9 to select a choice)
1 2 3 4 5 6 7 8 9 10 11 12 |
Calculator Options: 1) Clear Calculator 2) Set Initial Calculator Value 3) Display The Current Value 4) Add 5) Subtract 6) Divide 7) Multiply 8) Percentage Calculator 9) Quit Please enter a selection: |
This program was implemented into 3 different files (two .cpp files, and one header file .h). So the code for this program will be broken up into 3 sections, the main file (.cpp), the header file (.h), and the implementation of the functions within the header file (.cpp).
NOTE: On some compilers, you may have to add #include < cstdlib> in order for the code to compile.
======== File #1 Main.cpp ========
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 |
// ============================================================================ // This program tests the CCalc class. A loop is entered where the user is // prompted for a simple mathematical operation to be performed by the CCalc // class. The user is allowed to manipulate the calculator until they // indicate they wish to quit. // ============================================================================ #include <iostream> #include <iomanip> #include "CCalc.h" using namespace std; // defined constants const int LENGTH = 81; // function prototypes void DisplayMenu(); void HandleMenuSelection(CCalc &calcObject, int menuItem); // enumerated list enum MenuChoice { ITEM_CLEAR = 1 , ITEM_SET_VALUE = 2 , ITEM_DISPLAY_VALUE = 3 , ITEM_ADD = 4 , ITEM_SUBTRACT = 5 , ITEM_DIVIDE = 6 , ITEM_MULTIPLY = 7 , ITEM_PERCENT = 8 , ITEM_QUIT = 9}; // ==== main ================================================================== // // ============================================================================ int main() { // variable declarations CCalc calculator; // 'calculator' is an accessor to the 'CCalc' class char myString[LENGTH]; int menuItem=0; // initialize the calculator calculator.SetCurrentValue(0); // loop and let the user manipulate the calculator do{ // display the menu and get the user selection DisplayMenu(); cout << "nPlease enter a selection: "; cin.getline(myString, LENGTH); // convert the ascii string into an integer menuItem = atoi(myString); // creates a line seperator after each task is executed cout<<setfill('-'); cout<<left<<setw(30)<<""<<right<<setw(30)<<""<<endl; // handle the menu selection HandleMenuSelection(calculator, menuItem); cout <<endl; // creates a line seperator after each task is executed cout<<setfill('-'); cout<<left<<setw(30)<<""<<right<<setw(30)<<""<<endl; // ensures the menu isnt displayed twice on the screen if(menuItem!=1 && menuItem!=3 && menuItem!=9) { cin.ignore(); } }while(menuItem!=ITEM_QUIT); cout << "nBye....n"; return 0; } // end of "main" // ==== DisplayMenu =========================================================== // // This function displays the menu of options to stdout. // // Input: nothing // // Output: nothing // // ============================================================================ void DisplayMenu() { cout << "Calculator Options:" << endl; cout << " 1) Clear Calculator" << endl; cout << " 2) Set Initial Calculator Value" << endl; cout << " 3) Display The Current Value" << endl; cout << " 4) Add" << endl; cout << " 5) Subtract" << endl; cout << " 6) Divide" << endl; cout << " 7) Multiply" << endl; cout << " 8) Percentage Calculator" << endl; cout << " 9) Quit" << endl; } // end of "DisplayMenu" // ==== HandleMenuSelection =================================================== // // This function handles the menu selection by examining the input integer // value and calling the appropriate function. // // Input: // calculator -- a reference to the CCalc class // // menuItem -- an integer representing the current menu selection // // Output: // The desired user selection // // ============================================================================ void HandleMenuSelection(CCalc &calculator, int menuItem) { double currentValue = 0; double prevNum = calculator.GetPreviousValue(); // checks to see which user defined selection the calculator will execute // as defined in the enum list located above the main function. // A switch would be more practical to be used here, but i wasnt // comfortable yet using switches when this program was initially made if (menuItem == ITEM_CLEAR) { cout << "nThe current value is " << calculator.Clear() << endl; } // set a initial value else if (menuItem == ITEM_SET_VALUE) { cout << "nPlease enter a new value to assign: "; cin >> currentValue; calculator.SetCurrentValue(currentValue); } // display current value else if (menuItem == ITEM_DISPLAY_VALUE) { cout << "nThe current value is: "<< calculator.DisplayCurrentValue() <<endl; } // add current number by another number else if (menuItem == ITEM_ADD) { cout << "nThe current value is: "<< prevNum <<endl; cout << "nPlease enter a number to be added to "<<prevNum<<": "; cin >> currentValue; calculator.Add(currentValue); cout << "n"<<prevNum<<" + "<<currentValue<<" = "<< calculator.DisplayCurrentValue() <<endl; } // subtract current number by another number else if (menuItem == ITEM_SUBTRACT) { cout << "nThe current value is: "<< prevNum <<endl; cout << "nPlease enter a number to be subtracted from "<<prevNum<<": "; cin >> currentValue; calculator.Subtract(currentValue); cout << "n"<<prevNum<<" - "<<currentValue<<" = " << calculator.DisplayCurrentValue() <<endl; } // divide current value by another number else if (menuItem == ITEM_DIVIDE) { cout << "nThe current value is: "<< prevNum <<endl; cout << "nPlease enter a divisor to be divided by "<<prevNum<<": "; cin >> currentValue; if (currentValue == 0) { cout << "nSorry, division by zero is not allowed...nPlease press ENTER to continue..."; cin.get(); } else { calculator.Divide(currentValue); cout << "n"<<prevNum<<" "<<char(246)<<" "<<currentValue<<" = " << calculator.DisplayCurrentValue() <<endl; } } // multiply current value by another number else if (menuItem == ITEM_MULTIPLY) { cout << "nThe current value is: "<< prevNum <<endl; cout << "nPlease enter a number to be multiplied by "<<prevNum<<": "; cin >> currentValue; calculator.Multiply(currentValue); cout << "n"<<prevNum<<" x "<<currentValue<<" = " << calculator.DisplayCurrentValue() <<endl; } // convert value to decimal percent else if (menuItem == ITEM_PERCENT) { cout << "nThe current value is: "<< prevNum <<endl; cout << "nPlease enter a percentage to be deducted from "<<prevNum<<": "; cin >> currentValue; cout << "n"<<currentValue<<"% off of "<<prevNum<<" is " << calculator.GetPercentage(currentValue) <<endl; } // quit program else if (menuItem == ITEM_QUIT) { cout << "nCalculator will now quit"; } // user entered an invalid choice else { cout << "nYou have entered an invalid command...nPlease press ENTER to try again."; } } // http://programmingnotes.org/ |
======== File #2 CCalc.h. ========
Remember, you need to name the header file the same as the #include from the main.cpp file. This file contains the function declarations, but no implementation of those functions takes place here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
// ============================================================================ // File: CCalc.h // ============================================================================ // This is the header file for the CCalc class. // ============================================================================ #ifndef CCALC_HEADER #define CCALC_HEADER // a typedef statement to create a synonym for // the 'double' data type named "CCalcType" typedef double CCalcType; class CCalc // this is the 'CCalc' class declaration { public: // constructor CCalc(); // initializes variables // member functions void Add(CCalcType value); // adds numbers together CCalcType Clear(); // clears the current number in the calculator void Divide(CCalcType value); // divides numbers together CCalcType DisplayCurrentValue(); // displays the current value in the calculator CCalcType GetPreviousValue(); // returns the previous value in the calculator CCalcType GetPercentage(CCalcType value); // deducts a user specified percentage of a given value void Multiply(CCalcType value); // multiplies numbers together void SetCurrentValue(CCalcType value); // set a current value in the calculator void Subtract(CCalcType value); // subtracts two numbers together // destructor ~CCalc(); // deletes any variables contained in the class private: CCalcType m_total; // private variable used within the program }; #endif // CCALC_HEADER -- http://programmingnotes.org/ |
======== File #3 CCalc.cpp. ========
This is the function implementation file for the CCalc.h class. This file can be named anything you wish as long as you #include “CCalc.h”
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
// ============================================================================ // File: CCalc.cpp // ============================================================================ // This is the function implementation file for the CCalc.h class. // ============================================================================ #include <iostream> #include "CCalc.h" using namespace std; CCalc::CCalc() // this is the constructor { m_total = 0; }// end of CCalc void CCalc::Add(CCalcType value) { m_total += value; }// end of Add CCalcType CCalc::Clear() { m_total = 0; return m_total; }// end of Clear void CCalc::Divide(CCalcType value) { m_total /= value; }// end of Divide CCalcType CCalc::DisplayCurrentValue() { return m_total; }// end of DisplayCurrentValue CCalcType CCalc::GetPreviousValue() { return m_total; }// end of GetPreviousValue void CCalc::Multiply(CCalcType value) { m_total *= value; }// end if Multiply void CCalc::SetCurrentValue(CCalcType value) { m_total = value; }// end of SetValue void CCalc::Subtract(CCalcType value) { m_total -= value; }// end of Subtract CCalcType CCalc::GetPercentage(CCalcType value) { CCalcType percent= value/100; CCalcType tempTotal = m_total; tempTotal *= percent; m_total -= tempTotal; return m_total; }// end of GetPercentage CCalc::~CCalc() // this is the destructor { m_total = 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output
Calculator Options:
1) Clear Calculator
2) Set Initial Calculator Value
3) Display The Current Value
4) Add
5) Subtract
6) Divide
7) Multiply
8.) Percentage Calculator
9) QuitPlease enter a selection: 0
------------------------------------------------------------You have entered an invalid command...
Please ENTER to try again.
------------------------------------------------------------Calculator Options:
1) Clear Calculator
2) Set Initial Calculator Value
3) Display The Current Value
4) Add
5) Subtract
6) Divide
7) Multiply
8.) Percentage Calculator
9) QuitPlease enter a selection: 2
------------------------------------------------------------Please enter a new value to assign: 2
------------------------------------------------------------
Calculator Options:
1) Clear Calculator
2) Set Initial Calculator Value
3) Display The Current Value
4) Add
5) Subtract
6) Divide
7) Multiply
8.) Percentage Calculator
9) QuitPlease enter a selection: 3
------------------------------------------------------------The current value is: 2
------------------------------------------------------------
Calculator Options:
1) Clear Calculator
2) Set Initial Calculator Value
3) Display The Current Value
4) Add
5) Subtract
6) Divide
7) Multiply
8.) Percentage Calculator
9) QuitPlease enter a selection: 4
------------------------------------------------------------The current value is: 2
Please enter a number to be added to 2: 2
2 + 2 = 4
------------------------------------------------------------
Calculator Options:
1) Clear Calculator
2) Set Initial Calculator Value
3) Display The Current Value
4) Add
5) Subtract
6) Divide
7) Multiply
8.) Percentage Calculator
9) QuitPlease enter a selection: 5
------------------------------------------------------------The current value is: 4
Please enter a number to be subtracted from 4: 6
4 - 6 = -2
------------------------------------------------------------
Calculator Options:
1) Clear Calculator
2) Set Initial Calculator Value
3) Display The Current Value
4) Add
5) Subtract
6) Divide
7) Multiply
8.) Percentage Calculator
9) QuitPlease enter a selection: 6
------------------------------------------------------------The current value is: -2
Please enter a divisor to be divided by -2: -2
-2 ÷ -2 = 1
------------------------------------------------------------
Calculator Options:
1) Clear Calculator
2) Set Initial Calculator Value
3) Display The Current Value
4) Add
5) Subtract
6) Divide
7) Multiply
8.) Percentage Calculator
9) QuitPlease enter a selection: 7
------------------------------------------------------------The current value is: 1
Please enter a number to be multiplied by 1: 87
1 x 87 = 87
------------------------------------------------------------
Calculator Options:
1) Clear Calculator
2) Set Initial Calculator Value
3) Display The Current Value
4) Add
5) Subtract
6) Divide
7) Multiply
8.) Percentage Calculator
9) QuitPlease enter a selection: 8
------------------------------------------------------------The current value is: 87
Please enter a percentage to be deducted from 87: 23
23% off of 87 is 66.99
------------------------------------------------------------
Calculator Options:
1) Clear Calculator
2) Set Initial Calculator Value
3) Display The Current Value
4) Add
5) Subtract
6) Divide
7) Multiply
8.) Percentage Calculator
9) QuitPlease enter a selection: 9
------------------------------------------------------------Calculator will now quit
------------------------------------------------------------Bye....
C++ || Struct – Add One Day To Today’s Date Using A Struct
This program displays more practice using the structure data type, and is very similar to another program which was previously discussed here.
REQUIRED KNOWLEDGE FOR THIS PROGRAM
Functions
Passing a Value By Reference
Integer Arrays
Structures
Constant Variables
Boolean Expressions
This program utilizes a struct, which is very similar to the class concept. This program first prompts the user to enter the current date in mm/dd/yyyy format. Upon obtaining the date from the user, the program then uses a struct implementation to simply add one day to the date which was entered by the user. If the day that was entered into the program by the user falls on the end of the month, the program will”roll over” the incremented date into the next month. If the user enters 12/31/2012, the program will “roll over” the incremented date into the next calendar year.
NOTE: On some compilers, you may have to add #include < cstdlib> in order for the code to compile.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 |
#include <iostream> using namespace std; // struct declaration struct Date { int month; int day; int year; }; // constants which do not change // specifies the max values for each variable const int MAX_DAYS = 31; const int MAX_MONTHS = 12; // function prototypes bool IsDateValid(Date dateVal); void CalcNextDay(Date &dateVal); int main() { // initialize the structure: month, day, year Date dateVal = {1,18,2012}; char backSlash = '/'; // this is a 'placeholder' variable // obtain information from user cout << "Please enter today's date in mm/dd/yyyy format: "; cin >> dateVal.month >> backSlash >> dateVal.day >> backSlash >> dateVal.year; // Checks to see if user entered valid data if (IsDateValid(dateVal) == false) { cout << "Invalid input...nProgram exiting...." << endl; exit(EXIT_FAILURE); } // function declaration which calculates the next day CalcNextDay(dateVal); // display updated data to user cout << "The next day is " << dateVal.month << "/" << dateVal.day << "/" << dateVal.year <<endl; return 0; }// end of main // this function checks to see if the user inputted valid data bool IsDateValid(Date dateVal) { // checks to see if user inputted data falls between the specified // const variables as declared above if ((dateVal.day >= 1 && dateVal.day <= MAX_DAYS) &&(dateVal.month >= 1 && dateVal.month <= MAX_MONTHS)) { return true; } else { return false; } }// end of IsDateValid // this calculates the next day & updates values via reference void CalcNextDay(Date &dateVal) { // int array which holds the max date each month has // from January to December int maxDays[12]={31,28,31,30,31,30,31,31,30,31,30,31}; // bool which lets the program know if the month the // user entered is a max month for the specific month // the user inputted bool maxDay = false; // checks to see if user inputted day is a max date from the // above array for the currently selected month which // was entered by the user if(dateVal.day == maxDays[dateVal.month-1]) { dateVal.day = 1; ++dateVal.month; maxDay = true; } // checks to see if user inputted a valid date // for the currently selected month else if (dateVal.day > maxDays[dateVal.month-1]) { cout << "Invalid day input - There is no such date for the selected month.nProgram exiting...." << endl; exit(EXIT_FAILURE); } // if user didnt enter a max date, and the date is valid, increment the day else { ++dateVal.day; } // if the date is 12/31/yyyy // increment to the next year if ((dateVal.month > 12) && maxDay == true) { dateVal.month = 1; ++dateVal.year; } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output:
Note: The code was compiled 6 separate times to display the different outputs its able to produce
Please enter today's date in mm/dd/yyyy format: 1/18/2012
The next day is 1/19/2012
-------------------------------------------------------------------Please enter today's date in mm/dd/yyyy format: 7/31/2012
The next day is 8/1/2012
-------------------------------------------------------------------Please enter today's date in mm/dd/yyyy format: 2/28/2012
The next day is 3/1/2012
-------------------------------------------------------------------Please enter today's date in mm/dd/yyyy format: 13/5/2012
Invalid input...
Program exiting....
-------------------------------------------------------------------Please enter today's date in mm/dd/yyyy format: 2/31/2012
Invalid day input - There is no such date for the selected month.
Program exiting....
-------------------------------------------------------------------Please enter today's date in mm/dd/yyyy format: 12/31/2012
The next day is 1/1/2013
C++ || Find The Average Using an Array – Omit Highest And Lowest Scores
This page will consist of two programs which calculates the average of a specific amount of numbers using an array.
REQUIRED KNOWLEDGE FOR BOTH PROGRAMS
Float Data Type
Constant Values
Arrays
For Loops
Assignment Operators
Basic Math
====== FIND THE AVERAGE USING AN ARRAY ======
The first program is fairly simple, and it was used to introduce the array concept. The program prompts the user to enter the total amount of numbers they want to find the average for, then the program displays the answer to them via cout.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
#include <iostream> using namespace std; int main() { // declare variables float total = 0; int numElems = 0; float average[100]; // declare array which has the ability to hold 100 elements cout << "How many numbers do you want to find the average for?: "; cin >> numElems; // user enters data into array using a for loop // you can also use a while loop, but for loops are more common // when dealing with arrays for(int index=0; index < numElems; ++index) { cout << "nEnter #" << index +1<< " : "; cin >> average[index]; total += average[index]; } // find the average. Note: // the expression below literally // means: total = total / numElems; total /= numElems; cout << "nThe average of the " << numElems << " numbers is " << total <<endl; return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
ARRAY
Notice the array declaration on line #9. The type of array being used in this program is a static array, which has the ability to store up to 100 integer elements in the array. You can change the number of elements its able to store to a higher or lower number if you wish.
FOR LOOP
Notice line 17-22 contains a for loop, which is used to actually store the data inside of the array. Without some type of loop, it is virtually impossible for the user to input data into the array; that is, unless you want to add 100 different cout statements into your code asking the user to input data. Line 21 uses the assignment operator “+=” which gives us a running total of the data that is being inputted into the array. Note the loop only stores as many elements as the user so desires, so if the user only wants to input 3 numbers into the array, the for loop will only execute 3 times.
Once compiled, you should get this as your output:
How many numbers do you want to find the average for?: 5
Enter #1 : 23
Enter #2 : 17
Enter #3 : 29
Enter #4 : 14
Enter #5 : 16
The average of the 5 numbers is 19.8
====== FIND THE AVERAGE – OMIT HIGHEST AND LOWEST SCORES ======
The second program is really practical in a real world setting, specifically when a teacher records test scores into the computer. We were asked to create a program for a fictional competition which had 6 judges. The 6 judges each gave a score of the performance for a competitor in a competition, (i.e a score of 1-10), and we were asked to find the average of those scores, omitting the highest/lowest results. The program was to store the scores into an array, display the scores back to the user via cout, display the highest and lowest scores among the 6 obtained, display the average of the 6 scores, and finally display the average adjusted scores omitting the highest and lowest result.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
#include <iostream> using namespace std; const int NUM_JUDGES = 6; int main() { int scores[NUM_JUDGES]; // array is initialized using a const variable int highestScore = -999999; int lowestScore = 999999; float sumOfScores = 0; float avgScores = 0; // use a for loop to obtain data from user using the const variable cout<< "Judges, enter one score each for the current competitor: "; for(int counter=0; counter < NUM_JUDGES; ++counter) { cin >> scores[counter]; } // use another for loop to redisplay the data back to the user via cout cout<<"nThese are the scores from the " << NUM_JUDGES << " judges: "; for(int index=0; index < NUM_JUDGES; ++index) { cout<<"nThe score for judge #"<<(index+1)<<" is: "<<scores[index]; } // use a for loop to go thru the array checking to see the highes/lowest element cout<<"nnThese are the highest and lowest scores: "; for(int index=0; index < NUM_JUDGES; ++index) { // if current score in the array is bigger than the current 'highestScore' // element, then set 'highestScore' equal to the current array element if(scores[index] > highestScore) { highestScore = scores[index]; } // if current 'lowestScore' element is bigger than the current array element, // then set 'lowestScore' equal to the current array element if(lowestScore > scores[index]) { lowestScore = scores[index]; } } cout << "ntHighest: "<< highestScore; cout << "ntLowest: "<< lowestScore; cout << "nThe average score is: "; // this calculates a running total, adding each element in the array together for(int counter=0; counter < NUM_JUDGES; ++counter) { sumOfScores += scores[counter]; } avgScores = sumOfScores/NUM_JUDGES; cout<< avgScores; // reset data back to 0 so we dont get wrong answers sumOfScores = 0; avgScores = 0; cout<<"nThe average adjusted score omitting the highest and lowest result is: "; // final loop, which calculates a running total, adding each element // in the array together, this time omitting the highest/lowest elements for(int counter=0; counter < NUM_JUDGES; ++counter) { // IF(current score isnt equal to the highest elem) AND (current score isnt equal lowest elem) // THEN create a running total if ((scores[counter] != highestScore) && (scores[counter] != lowestScore)) { sumOfScores += scores[counter]; } } avgScores = sumOfScores/(NUM_JUDGES-2); cout<< avgScores <<endl; return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
CONST
A constant variable was declared and used to initialize the array (line 8). Note, when using static arrays, the program has to know how many elements to initialize the program with before the program starts, so creating a constant variable to do that for us is convenient.
FOR LOOPS
Once again loops were used to traverse the array, as noted on lines 16, 23, 30, 53, and 70. The const variable was also used within the for loops, making it easier to modify the code if its necessary to reduce or increase the number of available judges.
HIGHEST/LOWEST SCORES
This is noted on lines 34-44, and it is really simple to understand the process once you see the code.
OMITTING HIGHEST/LOWEST SCORE
Lines 70-78 highlight this process, and the loop basically traverses the array, skipping over the highest/lowest elements
Once compiled, you should get this as your output:
Judges, enter one score each for
the current competitor: 123 453 -789 2 23345 987These are the scores from the 6 judges:
The score for judge #1 is: 123
The score for judge #2 is: 453
The score for judge #3 is: -789
The score for judge #4 is: 2
The score for judge #5 is: 23345
The score for judge #6 is: 987These are the highest and lowest scores:
Highest: 23345
Lowest: -789
The average score is: 4020.17
The average adjusted score omitting the highest and lowest result is: 391.25