Tag Archives: switch
Java || Display Today’s Date Using a Switch Statement
If statements, char’s and strings have been previously discussed, and this page will be more of the same. This program will demonstrate how to use a switch statement to display today’s date, converting from mm/dd/yyyy format (i.e 6/17/12) to formal format (i.e June 17th, 2012).
This same program can easily be done using if statements, but sometimes that is not always the fastest programming method. Switch statements are like literal light switches because the code “goes down a line” to check to see which case is valid or not, just like if statements. You will see why switches are very effective when used right by examining this program.
====== TODAY’S DATE USING A SWITCH ======
So to start our program out, lets define the variables.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.util.Scanner; public class TodaysDate { // global variable declaration static Scanner cin = new Scanner(System.in); public static void main(String[] args) { // declare variables int month = 6; int day = 17; int year = 2012; }// end of main }// http://programmingnotes.org/ |
Notice on line 6 there is a variable named “cin.” This program uses the scanner class to obtain data from the user. Click here for various examples demonstrating how to obtain data from the user using the scanner class.
We also declared three other variables, named “month, day, and year.” You should always name your variables something descriptive, as well as initializing them to a starting value.
Next we get data from the user for the month, day, and year variables. This process is demonstrated below:
1 2 3 4 5 6 7 8 9 10 11 |
// get month from user System.out.print("Please enter the current month: "); month = cin.nextInt(); // get day from user System.out.print("Please enter the current day: "); day = cin.nextInt(); // get year from user System.out.print("Please enter the current year: "); year = cin.nextInt(); |
Notice the format that the user will input the data in. They will input data in mm/dd/yyyy format, and using the “cin” variable will make that possible.
So after obtaining data from the user, how will the program convert numbers into actual text? Next comes the switch statements.
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 |
// determine which month to display switch(month) { case 1: System.out.print("tJanuary "); break; case 2: System.out.print("tFebruary "); break; case 3: System.out.print("tMarch "); break; case 4: System.out.print("tApril "); break; case 5: System.out.print("tMay "); break; case 6: System.out.print("tJune "); break; case 7: System.out.print("tJuly "); break; case 8: System.out.print("tAugust "); break; case 9: System.out.print("tSeptember "); break; case 10: System.out.print("tOctober "); break; case 11: System.out.print("tNovember "); break; case 12: System.out.print("tDecember "); break; default: System.out.print("t" + month +" is not a valid monthn"); System.exit(1); break; }// http://programmingnotes.org/ |
Line 2 contains the switch declaration, and its comparing the variable of “month” to the 12 different cases that is defined within the switch statement. So this piece of code will “go down the line” comparing to see if the user obtained data is any of the numbers from 1 to 12, as defined in the switch statement. If the user chooses a number which does not fall between 1 thru 12, the “default” case will be executed, prompting the user that the data they entered was invalid, which can be seen in line 40. Notice line 42 has an exit code. This program will force an exit whenever the user enters invalid data.
Line 6 is also very important, because that forces the computer to “break” away from the selected case whenever it is done examining that specific piece of code. It is important to add the break statement in there to avoid errors, which may result if the program does not break away from the current statement in which it is examining. Try compiling this code removing the “break” statements and see what happens!
Next we will add another switch statement in order to convert the day of the month to have a number suffix (i.e displaying the number in 1st, 2nd, 3rd format). This is very similar to the previous switch statement
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// determine which suffix to display switch(day) { case 1: case 21: case 31: System.out.print(day + "st, "); break; case 2: case 22: System.out.print(day + "nd, "); break; case 3: case 23: System.out.print(day + "rd, "); break; default: System.out.print(day + "th, "); break; } |
This block of code is very similar to the previous one. Line 2 is declaring the variable ‘day’ to be compared with the base cases; line 6 and so forth has the break lines, but line 4, 7 and 10 are different. If you notice, line 4, 7 and 10 are comparing multiple cases in one line. Yes, with switch statements, you can do that. Just like you can compare multiple values in if statements, the same can be done here. So this switch is comparing the number the user entered into the program, with the base cases, adding a suffix to the end of the number.
So far we have obtained data from the user, compared the month and day using switch statements and displayed that to the screen. Now all we have to do is output the year to the user. This is fairly simple, because the year is not being compared, you are just simply using a system print to display data to the user.
1 2 |
// display the current year System.out.println(year); |
So finally, adding all the above snippets together should give us the following code:
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 |
import java.util.Scanner; public class TodaysDate { // global variable declaration static Scanner cin = new Scanner(System.in); public static void main(String[] args) { // declare variables int month = 6; int day = 17; int year = 2012; // display message to screen System.out.println("nWelcome to My Programming Notes' Java Program."); // get month from user System.out.print("nPlease enter the current month: "); month = cin.nextInt(); // get day from user System.out.print("Please enter the current day: "); day = cin.nextInt(); // get year from user System.out.print("Please enter the current year: "); year = cin.nextInt(); System.out.println("nTodays date is: "); // use this switch statement to display the current month // using the information obtained from above switch(month) { case 1: System.out.print("tJanuary "); break; case 2: System.out.print("tFebruary "); break; case 3: System.out.print("tMarch "); break; case 4: System.out.print("tApril "); break; case 5: System.out.print("tMay "); break; case 6: System.out.print("tJune "); break; case 7: System.out.print("tJuly "); break; case 8: System.out.print("tAugust "); break; case 9: System.out.print("tSeptember "); break; case 10: System.out.print("tOctober "); break; case 11: System.out.print("tNovember "); break; case 12: System.out.print("tDecember "); break; default: System.out.print("t" + month +" is not a valid monthn"); System.exit(1); break; } // use this switch statement to display the current day // using the information obtained from above switch(day) { case 1: case 21: case 31: System.out.print(day + "st, "); break; case 2: case 22: System.out.print(day + "nd, "); break; case 3: case 23: System.out.print(day + "rd, "); break; default: System.out.print(day + "th, "); break; } // display the current year System.out.println(year); }// end of main }// http://programmingnotes.org/ |
Once compiled, you should get this as your output:
Welcome to My Programming Notes' Java Program.
Please enter the current month: 7
Please enter the current day: 28
Please enter the current year: 2012Todays date is:
July 28th, 2012
Java || Whats My Name? – Practice Using Strings, Methods & Switch Statemens
Here is another actual homework assignment which was presented in an intro to programming class. This program highlights more use using strings, modules, and switch statements.
REQUIRED KNOWLEDGE FOR THIS PROGRAM
How To Get String Input
If/Else Statements
Methods (A.K.A "Functions") - What Are They?
Switch Statements - How To Use Them
Equal - String Comparison
This program first prompts the user to enter their name. Upon receiving that information, the program saves input into a string called “firstName.” The program then asks if the user has a middle name. If they do, the user will enter a middle name. If they dont, the program proceeds to ask for a last name. Upon receiving the first, [middle], and last names, the program will append the first, [middle], and last names into a completely new string titled “fullName.” Lastly, if the users’ first, [middle], or last names are the same, the program will display that data to the screen via stdout. The program will also display to the user the number of characters their full name contains using the built in function “length.”
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 |
import java.util.Scanner; public class NameString { // global variable declaration static Scanner cin = new Scanner(System.in); public static void main(String[] args) { // declare variables char response = ' '; String firstName= ""; String fullName=""; // display message to screen System.out.println("nWelcome to My Programming Notes' Java Program."); // get first name from user System.out.print("Please enter your first name: "); firstName = cin.next(); System.out.print("nDo you have a middle name?(Y/N): "); String choice = cin.next(); choice = choice.toUpperCase(); response = choice.charAt(0); // use a switch statement to detrmine which function will be called switch(response) { case 'Y': fullName = FirstMiddleLast(firstName); // method declaration break; case 'N': fullName = FirstLast(firstName); // method declaration break; default: System.out.print("nPlease press either 'Y' or 'N'n" + "Program exiting...n"); System.exit(1); break; } System.out.println("And your full name is "+fullName); }// end of main // ==== FirstMiddleLast ==================================================== // // This module will take as input the first name, and prompt the user for // their middle and last name. Then it will display the total number of // characters in their name. It returns the full name back to main // // ========================================================================= private static String FirstMiddleLast(String firstName) { String middleName=""; String lastName=""; String fullName=""; System.out.print("nPlease enter your middle name: "); middleName = cin.next(); System.out.print("Please enter your last name: "); lastName = cin.next(); // copy the contents from the 3 strings into the 'fullName' string fullName = firstName+" "+middleName+" "+lastName; System.out.println(""); // check to see if the first, middle or last names are the same // if they are, display a message to the user if(firstName.equals(middleName)) { System.out.print("tYour first and middle name are the samen"); } if(middleName.equals(lastName)) { System.out.print("tYour middle and last name are the samen"); } if(firstName.equals(lastName)) { System.out.print("tYour first and last name are the samen"); } // display the total length of the string, minus the 2 white spaces System.out.println("nThe total number of characters in your " +"name is: "+(fullName.length()-2)); // return the full name string to main return fullName; }// end of FirstMiddleLast // ==== FirstLast ========================================================== // // This module will take as input the first name, and prompt the user for // their last name. Then it will display the total number of characters in // their name. It returns the full name back to main // // ============================================================================ private static String FirstLast(String firstName) { String lastName=""; String fullName=""; System.out.print("nPlease enter your last name: "); lastName = cin.next(); // copy the contents from the 3 strings into the 'fullName' string fullName = firstName+" "+lastName; System.out.println(""); // check to see if the first or last names are the same // if they are, display a message to the user if(firstName.equals(lastName)) { System.out.print("tYour first and last name are the samen"); } // display the total length of the string, minus the white space System.out.println("nThe total number of characters in your " +"name is: "+(fullName.length()-1)); // return the full name string to main return fullName; }// end of FirstLast }// 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 five separate times to display the different outputs its able to produce
====== RUN 1 ======
Welcome to My Programming Notes' Java Program.
Please enter your first name: My
Do you have a middle name?(Y/N): y
Please enter your middle name: Programming
Please enter your last name: NotesThe total number of characters in your name is: 18
And your full name is My Programming Notes====== RUN 2 ======
Welcome to My Programming Notes' Java Program.
Please enter your first name: Programming
Do you have a middle name?(Y/N): n
Please enter your last name: NotesThe total number of characters in your name is: 16
And your full name is Programming Notes====== RUN 3 ======
Welcome to My Programming Notes' Java Program.
Please enter your first name: Notes
Do you have a middle name?(Y/N): y
Please enter your middle name: Notes
Please enter your last name: NotesYour first and middle name are the same
Your middle and last name are the same
Your first and last name are the sameThe total number of characters in your name is: 15
And your full name is Notes Notes Notes====== RUN 4 ======
Welcome to My Programming Notes' Java Program.
Please enter your first name: My
Do you have a middle name?(Y/N): n
Please enter your last name: MyYour first and last name are the same
The total number of characters in your name is: 4
And your full name is My My====== RUN 5 ======
Welcome to My Programming Notes' Java Program.
Please enter your first name: My
Do you have a middle name?(Y/N): zPlease press either 'Y' or 'N'
Program exiting...
C++ || Class – Roman Numeral To Integer & Integer To Roman Numeral Conversion
The following is another homework assignment which was presented in a C++ Data Structures course. This program was assigned in order to practice the use 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 - What Is It?
Do/While Loop
Passing a Value By Reference
Roman Numerals - How Do You Convert To Decimal?
Online Roman Numeral Converter - Check For Correct Results
This is an interactive program in which the user has the option of selecting from 7 modes of operation. Of those modes, the user has the option of entering in roman numerals for conversion, entering in decimal numbers for conversion, displaying the recently entered number, and finally converting between roman or decimal values.
A sample of the menu is as followed:
(Where the user would enter numbers 1-7 to select a choice)
1 2 3 4 5 6 7 8 9 10 11 |
From the following menu: 1. Enter a Decimal number 2. Enter a Roman Numeral 3. Convert from Decimal to Roman 4. Convert from Roman to Decimal 5. Print the current Decimal number 6. Print the current Roman Numeral 7. 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).
======== FILE #1 – Menu.cpp ========
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 |
// ============================================================================ // File: Menu.cpp // Purpose: Converts a number enetered in Decimal to Roman Numeral and a // Roman Numeral to a Decimal Number // ============================================================================ #include <iostream> #include <iomanip> #include <string> #include "ClassRomanType.h" using namespace std; // function prototypes void DisplayMenu(); int GetCommand(int command); void RunChoice(int command, ClassRomanType& romanObject); int main() { int command=7; // Holds which action the user chooses to make ClassRomanType romanObject; // Gives access to the class do{ DisplayMenu(); command = GetCommand(command); RunChoice(command, romanObject); cout<<"n--------------------------------------------------------------------n"; }while(command!=7); cout<<"nBye!n"; return 0; }// End of main void RunChoice(int command, ClassRomanType& romanObject) {// Function: Execute the choice selected from the menu // declare private variables int decimalNumber=0; // Holds decimal value char romanNumeral[150]; //Holds value of roman numeral // execute the desired choice cout <<"ntYou selected choice #"<<command<<" which will: "; switch(command) { case 1: cout << "Get Decimal Numbernn"; cout <<"Enter a Decimal Number: "; cin >> decimalNumber; romanObject.GetDecimalNumber(decimalNumber); break; case 2: cout << "Get Roman Numeralnn"; cout <<"nEnter a Roman Numeral: "; cin >> romanNumeral; romanObject.GetRomanNumeral(romanNumeral); break; case 3: cout << "Convert from Decimal to Romannn"; romanObject.ConvertDecimalToRoman(); cout<<"Running....nComplete!n"; break; case 4: cout << "Convert from Roman to Decimalnn"; romanObject.ConvertRomanToDecimal(); cout<<"Running....nComplete!n"; break; case 5: cout << "Print the current Decimal numbernn"; cout<<"n The current Roman to Decimal Value is: "; cout << romanObject.ReturnDecimalNumber()<<endl; break; case 6: cout << "Print the current Roman Numeralnn"; cout<<"n The current Decimal to Roman Value is: "; cout << romanObject.ReturnRomanNumber()<<endl; break; case 7: cout << "Quitnn"; break; default: cout << "nError, you entered an invalid command!nPlease try again..."; break; } }//End of RunChoice int GetCommand(int command) {// Function: Gets choice from menu cout <<"nPlease enter a selection: "; cin>> command; return command; }// End of GetCommand void DisplayMenu() {// Function: Displays menu cout <<"From the following menu:n"<<endl; cout <<left<<setw(2)<<"1."<<left<<setw(15)<<" Enter a Decimal number"<<endl; cout <<left<<setw(2)<<"2."<<left<<setw(15)<<" Enter a Roman Numeral"<<endl; cout <<left<<setw(2)<<"3."<<left<<setw(15)<<" Convert from Decimal to Roman"<<endl; cout <<left<<setw(2)<<"4."<<left<<setw(15)<<" Convert from Roman to Decimal"<<endl; cout <<left<<setw(2)<<"5."<<left<<setw(15)<<" Print the current Decimal number"<<endl; cout <<left<<setw(2)<<"6."<<left<<setw(15)<<" Print the current Roman Numeral"<<endl; cout <<left<<setw(2)<<"7."<<left<<setw(15)<<" Quit"<<endl; }// http://programmingnotes.org/ |
======== FILE #2 – ClassRomanType.h ========
Remember, you need to name the header file the same as the #include from the Menu.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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
// ============================================================================ // File: ClassRomanType.h // Purpose: Header file for Roman Numeral conversion. It contains all // declarations and prototypes for the class members to carry out the // conversion // ============================================================================ #include <string> using namespace std; class ClassRomanType { public: ClassRomanType(); /* Function: constructor initializes class variables to "0" Precondition: none Postcondition: defines private variables */ // member functions void GetDecimalNumber(int decimalNumber); /* Function: gets decimal number Precondition: none Postcondition: Gets arabic number from user */ void GetRomanNumeral(char romanNumeral[]); /* Function: gets roman numeral Precondition: none Postcondition: Gets roman numeral from user */ void ConvertDecimalToRoman(); /* Function: converts decimal number to ronman numeral Precondition: arabic and roman numeral characters should be known Postcondition: Gets roman numeral from user */ void ConvertRomanToDecimal(); /* Function: converts roman numeral to arabic number Precondition: arabic and roman numeral characters should be known Postcondition: Gets decimal number from user */ int ReturnDecimalNumber(); /* Function: displays converted decimal number Precondition: the converted roman numeral to decimal number Postcondition: displays decimal number to user */ string ReturnRomanNumber(); /* Function: displays converted roman numeral Precondition: the converted decimal number to roman numeral Postcondition: displays roman numeral to user */ ~ClassRomanType(); /* Function: destructor used to return memory to the system Precondition: the converted decimal number to roman numeral Postcondition: none */ private: char m_romanValue[150]; // An array holding the roman value within the class int m_decimalValue; // Holds the final output answer of the roman to decimal conversion }; // http://programmingnotes.org/ |
======== FILE #3 – RomanType.cpp ========
This is the function implementation file for the ClassRomanType.h class. This file can be named anything you wish as long as you #include “ClassRomanType.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 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 |
// ============================================================================ // File: RomanType.cpp // Purpose: Contains the implementation of the class members for the // roman numeral conversion // // *NOTE*: Uncomment cout statements to visualize whats happening // ============================================================================ #include <iostream> #include <string> #include <cstring> #include "ClassRomanType.h" using namespace std; ClassRomanType::ClassRomanType() { m_decimalValue=0; strcpy(m_romanValue,"Currently Undefined"); }// end of ClassRomanType void ClassRomanType:: GetDecimalNumber(int decimalNumber) { m_decimalValue = decimalNumber; }// end of GetDecimalNumber void ClassRomanType:: GetRomanNumeral(char romanNumeral[]) { strcpy(m_romanValue,romanNumeral); }// end of GetRomanNumeral void ClassRomanType:: ConvertDecimalToRoman() { strcpy(m_romanValue,""); // erases any previous data int numericValue[]={1000,900,500,400,100,90,50,40,10,9,5,4,1,0}; char *romanNumeral[]={"M","CM","D","CD","C","XC","L" ,"XL","X","IX","V","IV","I",0}; for (int x=0; numericValue[x] > 0; ++x) { //cout<<endl<<numericValue[x]<<endl; while (m_decimalValue >= numericValue[x]) { //cout<<"current m_decimalValue = " <<m_decimalValue<<endl; //cout<<"current numericValue = "<<numericValue[x]<<endl<<endl; if(strlen(m_romanValue)==0) { strcpy(m_romanValue,romanNumeral[x]); } else { strcat(m_romanValue,romanNumeral[x]); } m_decimalValue -= numericValue[x]; } } }// end of ConvertDecimalToRoman void ClassRomanType:: ConvertRomanToDecimal() { int currentNumber = 0; // Holds value of each letter numerical value int previousNumber = 0; // Holds the numerical value being compared m_decimalValue=0; // Resets the current 'romanToDecimalValue' to zero if(strcmp(m_romanValue,"Currently Undefined")!=0) { for (int counter = strlen(m_romanValue)-1; counter >= 0; counter--) { if ((m_romanValue[counter] == 'M') || (m_romanValue[counter] == 'm')) { currentNumber = 1000; } else if ((m_romanValue[counter] == 'D') || (m_romanValue[counter] == 'd')) { currentNumber = 500; } else if ((m_romanValue[counter] == 'C') || (m_romanValue[counter] == 'c')) { currentNumber = 100; } else if ((m_romanValue[counter] == 'L') || (m_romanValue[counter] == 'l')) { currentNumber = 50; } else if ((m_romanValue[counter] == 'X') || (m_romanValue[counter] == 'x')) { currentNumber = 10; } else if ((m_romanValue[counter] == 'V') || (m_romanValue[counter] == 'v')) { currentNumber = 5; } else if ((m_romanValue[counter] == 'I') || (m_romanValue[counter] == 'i')) { currentNumber = 1; } else { currentNumber = 0; } //cout<<"previousNumber = " <<previousNumber<<endl; //cout<<"currentNumber = " <<currentNumber<<endl; if (previousNumber > currentNumber) { m_decimalValue -= currentNumber; previousNumber = currentNumber; } else { m_decimalValue += currentNumber; previousNumber = currentNumber; } //cout<<"current m_decimalValue = " <<m_decimalValue<<endl<<endl; } } }// end of ConvertRomanToDecimal int ClassRomanType::ReturnDecimalNumber() { return m_decimalValue; }// end of ReturnDecimalNumber string ClassRomanType::ReturnRomanNumber() { return m_romanValue; }// end of ReturnRomanNumber ClassRomanType::~ClassRomanType() { m_decimalValue=0; strcpy(m_romanValue,"Currently Undefined"); }// 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
From the following menu:
1. Enter a Decimal number
2. Enter a Roman Numeral
3. Convert from Decimal to Roman
4. Convert from Roman to Decimal
5. Print the current Decimal number
6. Print the current Roman Numeral
7. QuitPlease enter a selection: 9
You selected choice #9 which will:
Error, you entered an invalid command!
Please try again...
--------------------------------------------------------------------
From the following menu:1. Enter a Decimal number
2. Enter a Roman Numeral
3. Convert from Decimal to Roman
4. Convert from Roman to Decimal
5. Print the current Decimal number
6. Print the current Roman Numeral
7. QuitPlease enter a selection: 5
You selected choice #5 which will: Print the current Decimal number
The current Roman to Decimal Value is: 0
--------------------------------------------------------------------
From the following menu:1. Enter a Decimal number
2. Enter a Roman Numeral
3. Convert from Decimal to Roman
4. Convert from Roman to Decimal
5. Print the current Decimal number
6. Print the current Roman Numeral
7. QuitPlease enter a selection: 6
You selected choice #6 which will: Print the current Roman Numeral
The current Decimal to Roman Value is: Currently Undefined
--------------------------------------------------------------------
From the following menu:1. Enter a Decimal number
2. Enter a Roman Numeral
3. Convert from Decimal to Roman
4. Convert from Roman to Decimal
5. Print the current Decimal number
6. Print the current Roman Numeral
7. QuitPlease enter a selection: 1
You selected choice #1 which will: Get Decimal Number
Enter a Decimal Number: 1987
--------------------------------------------------------------------
From the following menu:1. Enter a Decimal number
2. Enter a Roman Numeral
3. Convert from Decimal to Roman
4. Convert from Roman to Decimal
5. Print the current Decimal number
6. Print the current Roman Numeral
7. QuitPlease enter a selection: 5
You selected choice #5 which will: Print the current Decimal number
The current Roman to Decimal Value is: 1987
--------------------------------------------------------------------
From the following menu:1. Enter a Decimal number
2. Enter a Roman Numeral
3. Convert from Decimal to Roman
4. Convert from Roman to Decimal
5. Print the current Decimal number
6. Print the current Roman Numeral
7. QuitPlease enter a selection: 3
You selected choice #3 which will: Convert from Decimal to Roman
Running....
Complete!
--------------------------------------------------------------------
From the following menu:1. Enter a Decimal number
2. Enter a Roman Numeral
3. Convert from Decimal to Roman
4. Convert from Roman to Decimal
5. Print the current Decimal number
6. Print the current Roman Numeral
7. QuitPlease enter a selection: 6
You selected choice #6 which will: Print the current Roman Numeral
The current Decimal to Roman Value is: MCMLXXXVII
--------------------------------------------------------------------
From the following menu:1. Enter a Decimal number
2. Enter a Roman Numeral
3. Convert from Decimal to Roman
4. Convert from Roman to Decimal
5. Print the current Decimal number
6. Print the current Roman Numeral
7. QuitPlease enter a selection: 2
You selected choice #2 which will: Get Roman Numeral
Enter a Roman Numeral: mMxiI
--------------------------------------------------------------------
From the following menu:1. Enter a Decimal number
2. Enter a Roman Numeral
3. Convert from Decimal to Roman
4. Convert from Roman to Decimal
5. Print the current Decimal number
6. Print the current Roman Numeral
7. QuitPlease enter a selection: 6
You selected choice #6 which will: Print the current Roman Numeral
The current Decimal to Roman Value is: mMxiI
--------------------------------------------------------------------
From the following menu:1. Enter a Decimal number
2. Enter a Roman Numeral
3. Convert from Decimal to Roman
4. Convert from Roman to Decimal
5. Print the current Decimal number
6. Print the current Roman Numeral
7. QuitPlease enter a selection: 4
You selected choice #4 which will: Convert from Roman to Decimal
Running....
Complete!
--------------------------------------------------------------------
From the following menu:1. Enter a Decimal number
2. Enter a Roman Numeral
3. Convert from Decimal to Roman
4. Convert from Roman to Decimal
5. Print the current Decimal number
6. Print the current Roman Numeral
7. QuitPlease enter a selection: 5
You selected choice #5 which will: Print the current Decimal number
The current Roman to Decimal Value is: 2012
--------------------------------------------------------------------
From the following menu:1. Enter a Decimal number
2. Enter a Roman Numeral
3. Convert from Decimal to Roman
4. Convert from Roman to Decimal
5. Print the current Decimal number
6. Print the current Roman Numeral
7. QuitPlease enter a selection: 7
You selected choice #7 which will: Quit
--------------------------------------------------------------------
Bye!
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++ || Input/Output – Using An Array, Sort Names From a Text File & Save The Sorted Names To A New Text File
Since we previously discussed how to sort numbers which is contained in an integer array, it is only fitting that we display a program which sorts characters that are stored in a character array.
This is an interactive program which first displays a menu to the user, allowing them to choose from 6 different modes of operation. The 6 options are described as followed:
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit
From the available choices, the user has the option of reading in names from a file, manually entering in names themselves, displaying the current names in the array, sorting the current names in the array, clearing the current names in the array, and finally quitting the program. When the user chooses to quit the program, whatever data which is currently stored within the array will automatically be saved to the output text file.
REQUIRED KNOWLEDGE FOR THIS PROGRAM
Fstream
Ifstream
Ofstream
Character Arrays
2D Arrays
Working With Files
Pass By Reference
While Loops
For Loops
Bubble Sort
Functions
Switch Statements
Boolean Expressions
Toupper
Strcpy
Strcmp
The data file that is used in this example can be downloaded here.
Note: In order to read in the data .txt file, you need to save the .txt file in the same directory (or folder) as your .cpp file is saved in. If you are using Visual C++, this directory will be located in
Documents > Visual Studio 2010 > Projects > [Your project name] > [Your project name]
NOTE: On some compilers, you may have to add #include < cstdlib> 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 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 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 |
#include <iostream> #include <fstream> #include <iomanip> using namespace std; // const variable indicating how many names the array can hold const int TOTALNAMES = 100; // function prototypes void DisplayMenu(); int ReadInData(char names[][50], ifstream &infile); void GetUserData(char names[][50], int numberOfNames); void ClearArray(char names[][50], int numberOfNames); void SortArray(char names[][50], int numNames); void DisplayArray(char names[][50], int numNames); void SaveArrayToFile(char names[][50], int numberOfNames, ofstream &outfile); int main() { // declare variables ifstream infile; ofstream outfile; char names[TOTALNAMES][50]; char userResponse = 'Q'; int numberOfNames = 0; // display menu to user DisplayMenu(); cin >> userResponse; // keep looping thru the menu until the user // selects Q (Quit) while(toupper(userResponse)!='Q') { // switch statement indicating the available choices // the user has to make switch(toupper(userResponse)) { case 'R': numberOfNames = ReadInData(names, infile); break; case 'E': cout << "nPlease enter the number of names you want to sort: "; cin >> numberOfNames; GetUserData(names,numberOfNames); break; case 'D': DisplayArray(names, numberOfNames); break; case 'C': ClearArray(names,numberOfNames); numberOfNames=0; break; case 'S': SortArray(names, numberOfNames); break; case 'Q': break; default: cout << "nThe selected option is not apart of the list!nPlease try again.."; break; } // creates a line seperator after each task is executed cout<<endl; cout.fill('-'); cout<<left<<setw(30)<<""<<right<<setw(30)<<""<<endl; // re-display's the menu to the user DisplayMenu(); cin >> userResponse; } // after the user is finished manipulating the // data, save the names to the output file SaveArrayToFile(names, numberOfNames, outfile); return 0; }// end of main // ============================================================================ // displays options to user void DisplayMenu() { cout<<" Welcome to the name sorting program..."; cout<<"nFrom the following menu, select an option"; cout<<"nR - Read in names from a file for sorting"; cout<<"nE - Enter in names manually for sorting"; cout<<"nD - Display the current names in the array"; cout<<"nS - Sort the current names in the array"; cout<<"nC - Clear the current names in the array"; cout<<"nQ - Quitn"; cout<<"n>> "; }// end of DisplayMenu // ============================================================================ // reads in data from a file int ReadInData(char names[][50], ifstream &infile) { int numberOfNames=0; // open input file infile.open("INPUT_UNSORTED_NAMES_programmingnotes_freeweq_com.txt"); if(infile.fail()) { cout<<"Input file could not be found!n" <<"Please place the input file in the correct directory.."; return 0; } else { cout << "nReading in data from the file..."; while(infile.good()) { infile >> names[numberOfNames]; ++numberOfNames; } cout << "nSuccess!"; } infile.close(); // close the infile once we are done using it return numberOfNames; }// end of ReadInData // ============================================================================ // gets data from user (names) for direct input void GetUserData(char names[][50], int numberOfNames) { cout << "nPlease enter "<<numberOfNames<<" names" << endl; for(int index=0; index < numberOfNames; ++index) { cout<<"nName #"<<index+1<<": "; cin >> names[index]; } }// end of GetUserData // ============================================================================ // clears the data contained in the array void ClearArray(char names[][50], int numNames) { if(numNames==0) { cout<<"nThe array is currently empty!n"; } else { cout<<"nDeleting the data contained in the array..."; for(int index=0; index < numNames; ++index) { strcpy(names[index],""); } cout << "nClearing Complete!"; } }// end of ClearArray // ============================================================================ // sorts the array via 'bubble sort' void SortArray(char names[][50],int numNames) { bool sorted = false; char temp[50]; if(numNames==0) { cout<<"nThe array is currently empty!n"; } else { cout << "nSorting the names contained in the array..."; // this is the 'bubble sort' and will execute only // if there is more than 1 name contained within the array // If there is only one name contained in the array, // there is no need to sort anything while((sorted == false) && (numNames > 1)) { sorted = true; for (int index=0; index < numNames-1; ++index) { if (strcmp(names[index], names[index+1]) > 0) { strcpy(temp,names[index]); strcpy(names[index], names[index+1]); strcpy(names[index+1], temp); sorted = false; } } } cout << "nSuccess!"; } }// end of SortArray // ============================================================================ // saves the current data which is in the arrya to the output file void SaveArrayToFile(char names[][50], int numberOfNames, ofstream &outfile) { // open output file outfile.open("OUTPUT_SORTED_NAMES_programmingnotes_freeweq_com.txt"); if(outfile.fail()) { cout<<"Error creating output file!"; return; } else { if(numberOfNames==0) { cout<<"nThe array contained no names.nThere was no data to save to the output file...n"; outfile<<"The array contained no names.nThere was no data to save to the output file...n"; } else { cout<<"nSaving the current contents of the array to the ouptut file.."; outfile<<"Sorted items which were contained within the array..n"; for(int index=0; index < numberOfNames; ++index) { outfile <<"Name #"<<index+1<<": " << names[index]<<endl; } cout << "nSuccess!n"; } } outfile.close(); }// end of SaveArrayToFile // ============================================================================ // displays the current contents of the array to the user // via cout void DisplayArray(char names[][50], int numNames) { if(numNames==0) { cout<<"nThe array is currently empty!n"; } else { cout << "nThe values in the array are:n"; for (int index=0; index < numNames; ++index) { cout << names[index] << endl; } cout<<"nThere is currently "<<numNames<<" names in the array!n"; } }// 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
(Remember to include the input file)
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> d
The array is currently empty!
------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> q
The array contained no names.
There was no data to save to the output file...------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> e
Please enter the number of names you want to sort: 3
Please enter 3 names
Name #1: My
Name #2: Programming
Name #3: Notes------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> d
The values in the array are:
My
Programming
NotesThere is currently 3 names in the array!
------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> s
Sorting the names contained in the array...
Success!
------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> d
The values in the array are:
My
Notes
ProgrammingThere is currently 3 names in the array!
------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> c
Deleting the data contained in the array...
Clearing Complete!
------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> r
Reading in data from the file...
Success!
------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> d
The values in the array are:
My
Programming
Notes
C++
Java
Assembly
Lemon
Dark
Light
Black
High
Low
Cellphone
Cat
Dog
Penguin
Japan
Peace
Love
Color
White
One
Brain
Eggplant
Phalanx
Countenance
Crayons
Ben
Dover
Eileen
Bob
Downe
Justin
Elizebeth
Rick
Rolled
Sam
Widge
Liza
Destruction
Grove
Aardvark
Primal
Sushi
Victoria
Ostrich
Zebra
Scrumptious
Carbohydrate
Sulk
Ecstatic
Acrobat
Pneumonoultramicroscopicsilicovolcanoconiosis
English
Kenneth
Jessica
Pills
Pencil
Dragon
Mint
Chocolate
Temperature
Cheese
Rondo
Silicon
Scabbiest
Palpitate
Invariable
Henpecked
Titmouse
Canoodle
Boobies
Pressure
Density
Cards
Twiat
Tony
Pink
Green
Yellow
Duck
Dodge
Movie
Zoo
Xiomara
Eggs
Marshmallows
Umbrella
Apple
Panda
Brush
Handle
Door
Knob
Mask
Knife
Speaker
Wood
Orient
LoveThere is currently 100 names in the array!
------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> s
Sorting the names contained in the array...
Success!
------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> d
The values in the array are:
Aardvark
Acrobat
Apple
Assembly
Ben
Black
Bob
Boobies
Brain
Brush
C++
Canoodle
Carbohydrate
Cards
Cat
Cellphone
Cheese
Chocolate
Color
Countenance
Crayons
Dark
Density
Destruction
Dodge
Dog
Door
Dover
Downe
Dragon
Duck
Ecstatic
Eggplant
Eggs
Eileen
Elizebeth
English
Green
Grove
Handle
Henpecked
High
Invariable
Japan
Java
Jessica
Justin
Kenneth
Knife
Knob
Lemon
Light
Liza
Love
Love
Low
Marshmallows
Mask
Mint
Movie
My
Notes
One
Orient
Ostrich
Palpitate
Panda
Peace
Pencil
Penguin
Phalanx
Pills
Pink
Pneumonoultramicroscopicsilicovolcanoconiosis
Pressure
Primal
Programming
Rick
Rolled
Rondo
Sam
Scabbiest
Scrumptious
Silicon
Speaker
Sulk
Sushi
Temperature
Titmouse
Tony
Twiat
Umbrella
Victoria
White
Widge
Wood
Xiomara
Yellow
Zebra
ZooThere is currently 100 names in the array!
------------------------------------------------------------
Welcome to the name sorting program...
From the following menu, select an option
R - Read in names from a file for sorting
E - Enter in names manually for sorting
D - Display the current names in the array
S - Sort the current names in the array
C - Clear the current names in the array
Q - Quit>> q
Saving the current contents of the array to the ouptut file..
Success!
C++ || Find The Day Of The Week You Were Born Using Functions, String, Modulus, If/Else, & Switch
This program displays more practice using functions, modulus, if and switch statements.
REQUIRED KNOWLEDGE FOR THIS PROGRAM
Functions
Strings
Modulus
If/Else Statements
Switch Statements
Knowledge of Leap Years
A Calendar
This program prompts the user for their name, date of birth (month, day, year), and then displays information back to them via cout. Once the program obtains selected information from the user, it will use simple math to determine the day of the week in which the user was born, and determine the day of the week their current birthday will be for the current calendar year. The program will also display to the user their current age, along with re-displaying their name back to them.
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 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 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 |
#include <iostream> #include <string> using namespace std; // a const variable containing the current year const int CURRENT_YEAR = 2012; // function prototypes string GetNameOfMonth(int numOfMonth); int GetLastTwoDigits(int fourDigitYear); string GetDayOfWeek(int numOfMonth, int lastTwoDigits, int numOfDay, int fourDigitYear); int main () { // declare variables string nameOfMonth = " ", dayOfWeek = " ", userName = " ", dayOfWeekCurrentYear = " " ; int numOfMonth=0, numOfDay=0, fourDigitYear=0, lastTwoDigits=0, lastTwoDigitsCurrentYear; // user inputs data cout << "Please enter your name: "; cin >> userName; cout << "nPlease enter the month in which you were born (between 1 and 12): "; cin >> numOfMonth; // converts the number the user inputted from above ^ // into a literal month name (i.e month #1 = January) nameOfMonth = GetNameOfMonth(numOfMonth); // user inputs data cout << "nPlease enter the day you were born (between 1 and 31): "; cin >> numOfDay; // checks to see if user entered valid data if (numOfDay < 1 || numOfDay > 31) { cout << "nYou have entered an invalid number of day. " << "Please enter a valid number." << endl << endl; exit(1); } // user inputs data cout << "nPlease enter the year you were born (between 1900 and 2099): "; cin >> fourDigitYear; cout << endl << endl; // checks to see if user entered valid data if (fourDigitYear < 1900 || fourDigitYear > 2099) { cout << "You have entered an invalid year. " << "Please enter a valid year." << endl << endl; exit(1); } // gets the las two digits in which the user was born // (i.e 1999: last two digits = 99) lastTwoDigits = GetLastTwoDigits(fourDigitYear); // gets the las two digits of the current year // (i.e 2012: last two digits = 12) lastTwoDigitsCurrentYear = GetLastTwoDigits(CURRENT_YEAR); // finds the day of the week in which the user was born dayOfWeek = GetDayOfWeek(numOfMonth, lastTwoDigits, numOfDay, fourDigitYear); // finds the day of the week the users current birthday will be this year dayOfWeekCurrentYear = GetDayOfWeek(numOfMonth, lastTwoDigitsCurrentYear, numOfDay, CURRENT_YEAR); // display data to user cout << "Hello " << userName <<". Here are some facts about you!" <<endl; cout << "You were born "<< nameOfMonth << numOfDay << " "<< fourDigitYear << endl; cout << "Your birth took place on a " << dayOfWeek << endl; cout << "This year your birthday will take place on a " << dayOfWeekCurrentYear << endl; cout << "You currently are, or will be " << (CURRENT_YEAR - fourDigitYear) << " years old this year!"<<endl; return 0; }// end of main // converts the number the user inputted from above ^ // into a literal month name (i.e month #1 = January) string GetNameOfMonth(int numOfMonth) { string nameOfMonth = " "; // a switch determining what month the user was born switch(numOfMonth) { case 1: nameOfMonth = "January "; break; case 2: nameOfMonth = "February "; break; case 3: nameOfMonth = "March "; break; case 4: nameOfMonth = "April "; break; case 5: nameOfMonth = "May "; break; case 6: nameOfMonth = "June "; break; case 7: nameOfMonth = "July "; break; case 8: nameOfMonth = "August "; break; case 9: nameOfMonth = "September "; break; case 10: nameOfMonth = "October "; break; case 11: nameOfMonth = "November "; break; case 12: nameOfMonth = "December "; break; default: cout << "You have entered an invalid number of month. nPlease enter a valid number.n" << "Program Terminating.."; exit(1); break; }// end of switch return nameOfMonth ; }// end of GetNamOfMonth // gets the las two digits in which the user was born/current year int GetLastTwoDigits(int fourDigitYear) { if (fourDigitYear >= 1900 && fourDigitYear <= 1999) { return (fourDigitYear - 1900); } else { return (fourDigitYear - 2000); } }// end of GetLastTwoDigits // finds the day of the week in which the user was born/current year string GetDayOfWeek(int numOfMonth, int lastTwoDigits, int numOfDay, int fourDigitYear) { string dayOfWeek = " "; int Total = 0, valueOfMonth = 0; if (numOfMonth == 1) valueOfMonth = 1; else if (numOfMonth == 2) valueOfMonth = 4; else if (numOfMonth == 3) valueOfMonth = 4; else if (numOfMonth == 4) valueOfMonth = 0; else if (numOfMonth == 5) valueOfMonth = 2; else if (numOfMonth == 6) valueOfMonth = 5; else if (numOfMonth == 7) valueOfMonth = 0; else if (numOfMonth == 8) valueOfMonth = 3; else if (numOfMonth == 9) valueOfMonth = 6; else if (numOfMonth == 10) valueOfMonth = 1; else if (numOfMonth == 11) valueOfMonth = 4; else if (numOfMonth == 12) valueOfMonth = 6; else cout <<"nError"; Total = lastTwoDigits / 4; Total += lastTwoDigits; Total += numOfDay; Total += valueOfMonth; // uses the 'Total' variable from above to determine the day // of the week in which you were born if ((fourDigitYear > 2000)&&((numOfMonth != 1)&&(numOfMonth != 2))&&(fourDigitYear != 2004)) { Total = Total + 6; } else if ((fourDigitYear < 2000) && ((numOfMonth == 1) || (numOfMonth == 2))) { Total = Total + 7; } else if ((fourDigitYear == 2000) && ((numOfMonth == 1) || (numOfMonth == 2))) { Total = Total -2; } else if ((fourDigitYear == 2004||fourDigitYear == 2000)&&((numOfMonth != 1)&&(numOfMonth != 2))) { Total = Total -1; } else if ((fourDigitYear % 4 == 0) && (fourDigitYear % 100 == lastTwoDigits) && (fourDigitYear % 400 == lastTwoDigits)) { Total = Total-2; } else if ((fourDigitYear > 2000)&&((numOfMonth == 1)||(numOfMonth == 2))&&(fourDigitYear != 2004)) { Total = Total + 6; } // uses the 'Total' variable from above to determine the day // of the week in which you were born/when you birthday will be this year if (Total % 7 == 1) dayOfWeek = "Sunday"; else if (Total % 7 == 2) dayOfWeek = "Monday"; else if (Total % 7 == 3) dayOfWeek = "Tuesday"; else if (Total % 7 == 4) dayOfWeek = "Wednesday"; else if (Total % 7 == 5) dayOfWeek = "Thursday"; else if (Total % 7 == 6) dayOfWeek = "Friday"; else if (Total % 7 == 0) dayOfWeek = "Saturday"; else cout<< "nError"; return dayOfWeek; }// 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 five separate times to display the different outputs its able to produce
Please enter your name: MyProgrammingNotes
Please enter the month in which you were born (between 1 and 12): 1
Please enter the day you were born (between 1 and 31): 1
Please enter the year you were born (between 1900 and 2099): 2012Hello MyProgrammingNotes. Here are some facts about you!
You were born January 1 2012
Your birth took place on a Sunday
This year your birthday will take place on a Sunday
You currently are, or will be 0 years old this year!
---------------------------------------------------------------------Please enter your name: Name
Please enter the month in which you were born (between 1 and 12): 4
Please enter the day you were born (between 1 and 31): 2
Please enter the year you were born (between 1900 and 2099): 1957Hello Name. Here are some facts about you!
You were born April 2 1957
Your birth took place on a Tuesday
This year your birthday will take place on a Monday
You currently are, or will be 55 years old this year!
---------------------------------------------------------------------Please enter your name: Name
Please enter the month in which you were born (between 1 and 12): 5
Please enter the day you were born (between 1 and 31): 7
Please enter the year you were born (between 1900 and 2099): 1999Hello Name. Here are some facts about you!
You were born May 7 1999
Your birth took place on a Friday
This year your birthday will take place on a Monday
You currently are, or will be 13 years old this year!
---------------------------------------------------------------------Please enter your name: Name
Please enter the month in which you were born (between 1 and 12): 8
Please enter the day you were born (between 1 and 31): 4
Please enter the year you were born (between 1900 and 2099): 1983Hello Name. Here are some facts about you!
You were born August 4 1983
Your birth took place on a Thursday
This year your birthday will take place on a Saturday
You currently are, or will be 29 years old this year!
---------------------------------------------------------------------Please enter your name: Name
Please enter the month in which you were born (between 1 and 12): 6
Please enter the day you were born (between 1 and 31): 7
Please enter the year you were born (between 1900 and 2099): 2987You have entered an invalid year. Please enter a valid year.
Press any key to continue . . .
C++ || Display Today’s Date Using a Switch
If statements, char’s and strings have been previously discussed, and this page will be more of the same. This program will demonstrate how to use a switch to display today’s date, converting from mm/dd/yyyy format to formal format (i.e January 5th, 2012).
This same program can easily be done using if statements, but sometimes that is not always the fastest programming method. Switch statements are like literal light switches because the code “goes down a line” to check to see which case is valid or not, just like if statements. You will see why switches are very effective when used right by examining this program.
NOTE: On some compilers, you may have to add #include < cstdlib> in order for the code to compile.
====== TODAY’S DATE USING A SWITCH ========
So to start our program out, lets define the variables.
1 2 3 4 5 6 7 8 9 10 |
#include <iostream> using namespace std; int main() { // Declare Variables int month; int day; int year; char backSlash; } |
Notice on line 9 there is a variable named “backslah.” This program was designed to display the date in this format.
Enter today's date: 10/7/2008
October 7th, 2008
So the only way to achieve that was to add a “place holder” variable during the user input process, which is demonstrated below.
1 2 3 |
// Collect Data cout << "Enter today's date: "; cin >> month >> backSlash >> day >> backSlash >> year; |
In line 3, you can see the format that the user will input the data in. They will input data in mm/dd/yyyy format, and having the “backslash” placeholder there will make that possible.
After the user enters in data, how will the program convert numbers into actual text? Next comes the switch statements.
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 |
// Check month switch(month) { case 1: { cout << "tJanuary "; break; } case 2: { cout << "tFebruary "; break; } case 3: { cout << "tMarch "; break; } case 4: { cout << "tApril "; break; } case 5: { cout << "May "; break; } case 6: { cout << "tJune "; break; } case 7: { cout << "tJuly "; break; } case 8: { cout << "tAugust "; break; } case 9: { cout << "tSeptember "; break; } case 10: { cout << "tOctober "; break; } case 11: { cout << "tNovember "; break; } case 12: { cout << "tDecember "; break; } default: { cout << "t" << month <<" is not a valid monthn"; exit(1); // this forces the program to quit } } |
Line 2 contains the switch declaration, and its comparing the variable of “month” to the 12 different cases that is defined within the switch statement. So this piece of code will “go down the line” comparing to see if the user inputted data is any of the numbers, from 1 to 12. If the user inputted a number which does not fall between 1 thru 12, the “default” case will be executed, prompting the user that the data they inputted was invalid, which can be seen in line 64. Notice line 67 has an exit code. This program will force an exit whenever the user enters invalid data.
Line 7 is very important, because that forces the computer to “break” away from the selected case whenever it is done examining the piece of code. It is important to add the break in there to avoid errors, which may result in the program giving you wrong output as the answer.
Next we will add another switch statement to convert the day of the month to have a number suffix (i.e displaying the number in 1st, 2nd, 3rd format). This is very similar to the previous switch statement
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
// Check Day switch(day) { case 1: case 21: case 31: { cout << day << "st, "; break; } case 2: case 22: { cout << day << "nd, "; break; } case 3: case 23: { cout << day << "rd, "; break; } default: { cout << day << "th, "; break; } } |
This block of code is very similar to the previous one. Line 2 is declaring the variable ‘day’ to be compared with the base cases, line 7 and so forth has the break lines, but line 4, 9 and 14 are different. If you notice, line 4, 9 and 14 are comparing multiple cases in one line. Yes with switch statements, you can do that. Just like you can compare multiple values in if statements, the same cane be done here. So this switch is comparing the number the user inputted, with the base cases, adding a suffix to the end of the number.
So far we have obtained data from the user, compared the month and day using switch statements and displayed that to the screen. Now all we have to do is output the year to the user. This is fairly simple, because the year is not being compared, you are just simply using a cout to display data to the user.
1 2 |
// Display Year cout << year << endl; |
Adding all the code together should give us this
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 |
#include <iostream> using namespace std; int main() { // Declare Variables int month; int day; int year; char backSlash; // Collect Data cout << "Enter today's date: "; cin >> month >> backSlash >> day >> backSlash >> year; // Check month switch(month) { case 1: { cout << "tJanuary "; break; } case 2: { cout << "tFebruary "; break; } case 3: { cout << "tMarch "; break; } case 4: { cout << "tApril "; break; } case 5: { cout << "May "; break; } case 6: { cout << "tJune "; break; } case 7: { cout << "tJuly "; break; } case 8: { cout << "tAugust "; break; } case 9: { cout << "tSeptember "; break; } case 10: { cout << "tOctober "; break; } case 11: { cout << "tNovember "; break; } case 12: { cout << "tDecember "; break; } default: { cout << "t" << month <<" is not a valid monthn"; exit(1); } } // Check Day switch(day) { case 1: case 21: case 31: { cout << day << "st, "; break; } case 2: case 22: { cout << day << "nd, "; break; } case 3: case 23: { cout << day << "rd, "; break; } default: { cout << day << "th, "; break; } } // Display Year cout << year << endl; // Terminate return 0; } // http://programmingnotes.freeweq.com |
Once compiled, you should get this as your output
Enter today's date: 1/5/2012
January 5th, 2012