Tag Archives: Sentence
Python || Count The Total Number Of Characters, Vowels, & UPPERCASE Letters Contained In A Sentence Using A ‘For Loop’
Here is a simple program, which demonstrates more practice using the input/output mechanisms which are available in Python.
This program will prompt the user to enter a sentence, and then display the total number of uppercase letters, vowels and characters contained within that sentence. This program is very similar to an earlier project, this time, utilizing a for loop.
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 |
def main(): # declare variables numUpperCase = 0 numVowel = 0 numChars = 0 sentence = "" # get data from user sentence = input("Enter a sentence: ") # use a for loop, iterating over each item in the sentence for character in sentence: # do nothing, we dont care about whitespace if(character == ' '): continue # check to see if entered data is UPPERCASE if((character >= 'A') and (character <= 'Z')): numUpperCase += 1 # increment total number of uppercase by one # check to see if entered data is a vowel if((character == 'a')or(character == 'A')or(character == 'e')or (character == 'E')or(character == 'i')or(character == 'I')or (character == 'o')or(character == 'O')or(character == 'u')or (character == 'U')or(character == 'y')or(character == 'Y')): numVowel += 1 # increment Total number of vowels by one numChars += 1 # increment total number of chars being read # display data print("nTotal number of UPPERCASE letters: t%d" %(numUpperCase)) print("Total number of vowels: tt%d" %(numVowel)) print("Total number of characters: tt%d" %(numChars)) if __name__ == "__main__": main() # http://programmingnotes.org/ |
QUICK NOTES:
The highlighted portions are areas of interest.
Notice line 12 contains the for loop declaration. Note that each statement within the for loop block must be uniformly indented, otherwise the code will fail to compile.
Once compiling the above code, you should receive this as your output
Enter a sentence: My Programming Notes Is Awesome.
Total number of UPPERCASE letters: 5
Total number of vowels: 11
Total number of characters: 28
C++ || Stack – Using A Stack, Determine If A Set Of Parentheses Is Well-Formed
Here is another homework assignment which was presented in a C++ Data Structures course. This assignment was used to introduce the stack ADT, and helped prepare our class for two later assignments which required using a stack. Those assignments can be found here:
(1) Stack Based Infix To Postfix Conversion (Single Digit)
(2) Stack Based Postfix Evaluation (Single Digit)
REQUIRED KNOWLEDGE FOR THIS PROGRAM
Stack Data Structure
Cin.getline
#include "ClassStackListType.h"
A simple exercise for testing a stack is determining whether a set of parenthesis is “well formed” or not. What exactly is meant by that? In the case of a pair of parenthesis, for an expression to be well formed, consider the following table.
1 2 3 4 5 6 |
Well-Formed Expressions | Ill-Formed Expressions ------------------------------------|-------------------------------------- ( a b c [ ] ) | ( a b c [ ) ( ) [ ] { } | ( ( { ( a b c d e ) ( ) } | [ a b c d e ) ( ) } ( a + [ b - c ] / d ) | ( a + [ b - c } / d ) |
Given an expression with characters and parenthesis, ( ), [ ], and { }, our class was asked to determine if an expression was well formed or not by using the following algorithm:
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 |
// An algorithm for a Well Formed expression Set 'balanced' to true Set 'symbol' to the first character in the current expression while(there are more characters AND 'balanced' == true) { if('symbol' is an opening symbol) { Push 'symbol' onto the stack } else if('symbol' is a closing symbol) { if the stack is empty 'balanced' = false else Set the 'openSymbol' to the item at the top of the stack Pop the stack Check to see if 'symbol' matches 'openSymbol' (i.e - if openSymbol == '(' and symbol == ')' then 'balanced' = true) } Set 'symbol' to the next character in the current expression } if('balanced' == true AND stack is empty) { Expression is well formed } else { Expression is NOT well formed }// http://programmingnotes.org/ |
======= WELL-FORMED EXPRESSIONS =======
This program uses a custom template.h class. To obtain the code for that class, click 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 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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 14, 2012 // Taken From: http://programmingnotes.org/ // File: wellFormed.cpp // Description: Demonstrates how to check if an expression is well formed // ============================================================================ #include <iostream> #include "ClassStackListType.h" using namespace std; // function prototypes bool IsOpen(char symbol); bool IsClosed(char symbol); bool IsWellFormed(char openSymbol, char closeSymbol); int main() { // declare variables char expression[120]; char openSymbol; int index=0; bool balanced = true; StackListType<char> stack; // this is the stack declaration // obtain data from the user using a char array cout <<"Enter an expression and press ENTER. "<<endl; cin.getline(expression,sizeof(expression)); cout << "\nThe expression: " << expression; // loop thru the char array until we reach the 'NULL' character // and while 'balanced' == true while (expression[index]!='\0' && balanced) { // if input is an "open bracket" push onto stack // else, process info if (IsOpen(expression[index])) { stack.Push(expression[index]); } else if (IsClosed(expression[index])) { if(stack.IsEmpty()) { balanced = false; } else { openSymbol = stack.Top(); stack.Pop(); balanced = IsWellFormed(openSymbol, expression[index]); } } ++index; } if (balanced && stack.IsEmpty()) { cout << " is well formed..." << endl; } else { cout << " is NOT well formed!!! " << endl; } }// End of Main bool IsOpen(char symbol) { if ((symbol == '(') || (symbol == '{') || (symbol == '[')) { return true; } else { return false; } }// End of IsOpen bool IsClosed(char symbol) { if ((symbol == ')') || (symbol == '}') || (symbol == ']')) { return true; } else { return false; } }// End of IsClosed bool IsWellFormed(char openSymbol, char closeSymbol) { return (((openSymbol == '(') && closeSymbol == ')') || ((openSymbol == '{') && closeSymbol == '}') || ((openSymbol == '[') && closeSymbol == ']')); }// 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 compile four separate times to display different output)
====== RUN 1 ======
Enter an expression and press ENTER.
((
The expression: (( is NOT well formed!!!====== RUN 2 ======
Enter an expression and press ENTER.
(a{b[]}c)The expression: (a{b[]}c) is well formed...
====== RUN 3 ======
Enter an expression and press ENTER.
[(7 * 28) - 1987]The expression: [(7 * 28) - 1987] is well formed...
====== RUN 4 ======
Enter an expression and press ENTER.
{3 + [2 / 3] - (9 + 18) * 12)The expression: {3 + [2 / 3] - (9 + 18) * 12) is NOT well formed!!!
C++ || Char Array – Palindrome Checker Using A Character Array, ToUpper, Strlen, Strcpy, & Strcmp
The following is a palindrome checking program, which demonstrates more use of char array’s, ToUpper, Strlen, & Strcmp.
REQUIRED KNOWLEDGE FOR THIS PROGRAM
Character Arrays
Cin.getline
How to convert text in a char array from lower to uppercase
How to reverse a character array
Palindrome - What is it?
Strlen
Strcpy
Strcmp
While Loops
For Loops
Constant Variables
Setw
Using a constant value, by default, this program first asks the user to enter 5 words and/or sentences that they want to compare for similarity. If the text which was entered into the program is a palindrome, the program will prompt a message to the user via cout. This program determines similarity by using the strcmp function, to compare two arrays together. This program also demonstrates how to reverse a character array, aswell as demonstrates how to convert all the text which was placed into the char array from lower to UPPERCASE.
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 |
// ============================================================================ // Author: Kenneth Perkins // Date: Feb 26, 2012 // Taken From: http://programmingnotes.org/ // File: palindrome.cpp // Description: Demonstrates a simple palindrome checker // ============================================================================ #include <iostream> #include <iomanip> #include <cstdlib> #include <cctype> #include <cstring> using namespace std; // constant value const int NUM_WORDS = 5; // function prototypes void ConvertAllToUpper(char wordsCopy[][30], char palindrome[][30]); void ReverseCharArray(char palindrome[][30]); void CheckIfPalindrome(char wordsCopy[][30], char palindrome[][30], char words[][30]); int main() { // declare variable // this is a 2-D char array, which by default, has // the ability to hold 5 names, each 30 characters long char words[NUM_WORDS][30]; char wordsCopy[NUM_WORDS][30]; char palindrome[NUM_WORDS][30]; // get data from user cout << "\tWelcome to the Palindrome Check System!\n"; cout << "\nPlease enter " << NUM_WORDS << " word(s) to check for similarity:\n"; for (int index = 0; index < NUM_WORDS; ++index) { cout << "\t#" << index + 1 << ": "; cin.getline(words[index], 30); } // copy the user input into the 'wordsCopy' & // 'palindrome' char array for (int index = 0; index < NUM_WORDS; ++index) { strcpy(wordsCopy[index], words[index]); strcpy(palindrome[index], words[index]); } // 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:\n"; for (int index = 0; index < NUM_WORDS; ++index) { cout << "\tText #" << index + 1 << ": " << words[index] << endl; } // create a line seperator cout << endl; cout.fill('-'); cout << left << setw(30) << "" << right << setw(30) << "" << endl; // function declaration // convert all the text contained in the 2 arrays to // UPPERCASE ConvertAllToUpper(wordsCopy, palindrome); // function declaration // reverses all the text contained inside the char array // to determine if it is a palindrome ReverseCharArray(palindrome); // display the palindrome's to the screen cout << "\nHere are the palindrome's:\n"; // function declaration // checks to see if the text contained in the char // array is a palindrome or not CheckIfPalindrome(wordsCopy, palindrome, words); cin.get(); return 0; }// end of main void ConvertAllToUpper(char wordsCopy[][30], char palindrome[][30]) { int index = 0; // increment thru the current char array index while (index < NUM_WORDS) { // increment thru each letter within the current char array index for (unsigned currentChar = 0; currentChar < strlen(wordsCopy[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(wordsCopy[index][currentChar])) { wordsCopy[index][currentChar] = toupper(wordsCopy[index][currentChar]); palindrome[index][currentChar] = toupper(palindrome[index][currentChar]); } } ++index; } }// end of ConvertAllToUpper void ReverseCharArray(char palindrome[][30]) { int index = 0; // increment thru the current char array index while (index < NUM_WORDS) { // get the length of the current word in the array index int wordLength = strlen(palindrome[index]) - 1; // increment thru each letter within the current char array index // reversing the order of the array for (int currentChar = 0; currentChar < wordLength; --wordLength, ++currentChar) { // copy 1st letter in the array index into temp char temp = palindrome[index][currentChar]; // copy last letter in the array index into the 1st array index palindrome[index][currentChar] = palindrome[index][wordLength]; // copy temp into last array index palindrome[index][wordLength] = temp; } ++index; } }// end of ReverseCharArray void CheckIfPalindrome(char wordsCopy[][30], char palindrome[][30], char words[][30]) { int palindromeCount = 0; // increment thru the current char array index for (int index = 0; index < NUM_WORDS; ++index) { // if the contents in the 'wordsCopy' & 'palindrome' // are the same, then the word is a palindrome if (strcmp(wordsCopy[index], palindrome[index]) == 0) { cout << "\tText #" << index + 1 << ": " << words[index] << " is a palindrome" << endl; ++palindromeCount; } } if (palindromeCount == 0) { cout << "There were no palindrome's found in the current list!\n"; } }// 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
(Note: The code was compiled 2 seperate times to demonstrate different output)
====== RUN 1 ======
Welcome to the Palindrome Check System!
Please enter 5 word(s) to check for similarity:
#1: SteP oN nO PEts
#2: My ProGramminG NoTeS
#3: RaTs liVE ON No eViL StaR
#4: ABLe wAs I ErE I sAw ElBa
#5: LiVE Non Evil------------------------------------------------------------
This is what you entered into the system:
Text #1: SteP oN nO PEts
Text #2: My ProGramminG NoTeS
Text #3: RaTs liVE ON No eViL StaR
Text #4: ABLe wAs I ErE I sAw ElBa
Text #5: LiVE Non Evil------------------------------------------------------------
Here are the palindrome's:
Text #1: SteP oN nO PEts is a palindrome
Text #3: RaTs liVE ON No eViL StaR is a palindrome
Text #4: ABLe wAs I ErE I sAw ElBa is a palindrome
Text #5: LiVE Non Evil is a palindrome====== RUN 2 ======
Welcome to the Palindrome Check System!
Please enter 5 word(s) to check for similarity:
#1: today Is Great
#2: Tomorrow is Foriegn
#3: Sunday Brunch
#4: Hello SkiPper
#5: Mayday Ship DowN!------------------------------------------------------------
This is what you entered into the system:
Text #1: today Is Great
Text #2: Tomorrow is Foriegn
Text #3: Sunday Brunch
Text #4: Hello SkiPper
Text #5: Mayday Ship DowN!------------------------------------------------------------
Here are the palindrome's:
There were no palindrome's found in the current list!
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++ || Find The Prime, Perfect & All Known Divisors Of A Number Using A For, While & Do/While Loop
This program was designed to better understand how to use different loops which are available in C++.
This program first asks the user to enter a non negative number. After it obtains a non negative integer from the user, the program will determine if the inputted number is a prime number or not, aswell as determine if the user inputted number is a perfect number or not. After it obtains its results, the program will display to the screen if the user inputted number is prime/perfect number or not. The program will also display a list of all the possible divisors of the user inputted number via cout.
REQUIRED KNOWLEDGE FOR THIS PROGRAM
Do/While Loop
While Loop
For Loop
Modulus
Basic Math - Prime Numbers
Basic Math - Perfect Numbers
Basic Math - Divisors
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 |
#include <iostream> #include <iomanip> using namespace std; int main () { int userInput = 0; int divisor = 0; int sumOfDivisors = 0; char response ='n'; do{ // this is the start of the do/while loop cout<<"Enter a number: "; cin >> userInput; // if the user inputs a negative number, do this code while(userInput < 0) { cout<<"ntaSorry, but the number entered is less than the allowable limit. Please try again"; cout<<"nnEnter an number: "; cin >> userInput; } cout << "nInput number: " << userInput; // for loop adds sum of all possible divisors for(int counter=1; counter <= userInput; ++counter) { divisor = (userInput % counter); if(divisor == 0) { // this will repeatedly add the found divisors together sumOfDivisors += counter; } } // uses the 'sumOfDivisors' variable from ^ above for loop to // check if 'userInput' is prime if(userInput == (sumOfDivisors - 1)) { cout<<endl; cout << userInput << " is a prime number."; } else { cout<<endl; cout << userInput << " is not a prime number."; } // uses the 'sumOfDivisors' variable from ^ above for loop to // check if 'userInput' is a perfect number if (userInput == (sumOfDivisors - userInput)) { cout<<endl; cout << userInput << " is a perfect number."; } else { cout<<endl; cout << userInput << " is not a perfect number."; } cout << "nDivisors of " << userInput << " are: "; // for loop lists all the possible divisors for the // 'userInput' variable by using the modulus operator for(int counter=1; counter <= userInput; ++counter) { divisor = (userInput % counter); if(divisor == 0 && counter !=userInput) { cout << counter << ", "; } } cout << "and "<< userInput; // asks user if they want to enter new data cout << "nntDo you want to input another number?(Y/N): "; cin >> response; // creates a line seperator if user wants to enter new data cout.fill('-'); cout<<left<<setw(30)<<""<<right<<setw(30)<<""<<endl; // resets variable back to zero if the user wants to enter new data sumOfDivisors=0; }while(response =='y' || response =='Y'); // ^ End of the do/while loop. As long as the user chooses // 'Y' the loop will keep going. // It stops when the user chooses the letter 'N' return 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:
Enter a number: 8128
Input number: 8128
8128 is not a prime number.
8128 is a perfect number.
Divisors of 8128 are: 1, 2, 4, 8, 16, 32, 64, 127, 254, 508, 1016, 2032, 4064, and 8128Do you want to input another number?(Y/N): y
------------------------------------------------------------
Enter a number: 6Input number: 6
6 is not a prime number.
6 is a perfect number.
Divisors of 6 are: 1, 2, 3, and 6Do you want to input another number?(Y/N): y
------------------------------------------------------------
Enter a number: 241Input number: 241
241 is a prime number.
241 is not a perfect number.
Divisors of 241 are: 1, and 241Do you want to input another number?(Y/N): y
------------------------------------------------------------
Enter a number: 2012Input number: 2012
2012 is not a prime number.
2012 is not a perfect number.
Divisors of 2012 are: 1, 2, 4, 503, 1006, and 2012Do you want to input another number?(Y/N): n
------------------------------------------------------------
Press any key to continue . . .
C++ || Whats My Name? – Using a Char Array, Strcpy, Strcat, Strcmp, & Strlen
Here is another actual homework assignment which was presented in an intro to programming class.
REQUIRED KNOWLEDGE FOR THIS PROGRAM
This program first prompts the user to enter their name. Upon receiving that information, the program saves input into a character array of size 15. 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 use strcpy and strcat to copy/append the first, [middle], and last names into a completely new char array titled “fullname.” Lastly, if the users’ first, [middle], or last names are the same, the program will display that data to the screen via cout. The program will also display to the user the number of characters their full name contains using strlen.
NOTE: On some compilers, you may have to add #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 |
// ============================================================================ // File: NameString.cpp // ============================================================================ // // Description: // This program prompts the user for a first name, middle name and last name. // Each name string is to be saved in its own character array. Then a // "full name" string is created by copying the first name to a fourth array, // and concatenating the middle and last names. Once the full name is // in its own buffer, the total number of characters in the full name will // be displayed. // // ============================================================================ #include <iostream> using namespace std; //function prototypes void FirstMiddleLast(char firstname[]); void FirstLast(char firstname[]); // ==== main ================================================================== // // ============================================================================ int main() { char firstname[15]; // char array with ability to hold 15 characters char response = ' '; // get data from user. Notice, you dont need a loop to input data // into the char array cout << "Please enter your first name: "; cin >> firstname; // check to see if user has a middle name cout << "nDo you have a middle name?(Y/N): "; cin >> response; // you could also use a switch statement here if ((response=='y')||(response=='Y')) { FirstMiddleLast(firstname); // function declaration } else if ((response=='n')||(response=='N')) { FirstLast(firstname); // function declaration } else { cout << "nPlease press either 'Y' or 'N'nna" << "Program exiting...n"; } return 0; }// end of main // ==== FirstMiddleLast ======================================================= // // This function 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 // // Input: // limit [IN] -- The users first name // // Output: // The users full name, and the total number of characters in their name // // ============================================================================ void FirstMiddleLast(char firstname[]) { char middlename[15]; char lastname[15]; char fullname[30]; cout << "nPlease enter your middle name: "; cin >> middlename; cout <<"nPlease enter your last name: "; cin >> lastname; strcpy(fullname, firstname); // copies data from 'firstname' into 'fullname' array strcat(fullname, " "); // appends 'fullname' with a space strcat(fullname, middlename); // appends 'fullname' to contain the data from 'middlename' array strcat(fullname, " "); // appends 'fullname' with a space strcat(fullname, lastname); // appends 'fullname' to contain the data from 'lastname' array cout <<"ntYour full name is " << fullname << endl; cout << "tThe total number of characters in your name is: "; cout << strlen(fullname)-2 << endl; // gets total num of chars contained in the 'fullname' array, minus the 2 spaces // if strcmp returns 0, the two strings are the same if(strcmp(firstname, middlename) == 0) { cout << "tYour first and middle name are the samen"; } if(strcmp(middlename, lastname) == 0) { cout << "tYour middle and last name are the samen"; } if(strcmp(firstname, lastname) == 0) { cout << "tYour first and last name are the samen"; } }// end of FirstMiddleLast // ==== FirstLast ============================================================= // // This function 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 // // Input: // limit [IN] -- The users first name // // Output: // The users full name, and the total number of characters in their name // // ============================================================================ void FirstLast(char firstname[]) { char lastname[15]; char fullname[30]; cout <<"nPlease enter your last name: "; cin >> lastname; strcpy(fullname, firstname); // copies data from 'firstname' into 'fullname' array strcat(fullname, " "); // appends 'fullname' with a space strcat(fullname, lastname); // appends 'fullname' to contain the data from 'lastname' array cout <<"ntYour full name is " << fullname << endl; cout << "tThe total number of characters in your name is: "; cout << strlen(fullname)-1 << endl; // gets total num of chars contained in the 'fullname' array, minus the single space // if strcmp returns 0, the two strings are the same if(strcmp(firstname, lastname) == 0) { cout << "tYour first and last name are the samenn"; } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
CHAR ARRAY
Unlike integer arrays, a loop is not necessary in order to input data into a char array. This is highlighted on lines 32, 76, 79, and 125.
FUNCTIONS
Notice lines 18, 19, 69 and 119. When dealing with arrays, in order to pass variables to different functions, you need to include brackets[] letting the compiler know that you are passing an array variable. If you do not declare the functions as so, you will get a compiler error.
STRCPY/STRCAT
These functions are highlighted on lines 81-85, and 127-129. Read the comments within the code on those selected lines, they are helpful.
STRCMP
This compares two strings together to determine if they are the same. This is displayed on lines 92, 96, 100, and 136 when comparing the first, [middle], and last names together for sameness.
STRLEN
This finds the length of the current string, as noted on lines 89 and 133.
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 first name: My
Do you have a middle name?(Y/N): y
Please enter your middle name: Programming
Please enter your last name: NotesYour full name is My Programming Notes
The total number of characters in your name is: 18
-----------------------------------------------------------------------Please enter your first name: Programming
Do you have a middle name?(Y/N): N
Please enter your last name: NotesYour full name is Programming Notes
The total number of characters in your name is: 16
-----------------------------------------------------------------------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 full name is Notes Notes Notes
The total number of characters in your name is: 15
Your first and middle name are the same
Your middle and last name are the same
Your first and last name are the same
-----------------------------------------------------------------------Please enter your first name: My
Do you have a middle name?(Y/N): N
Please enter your last name: MyYour full name is My My
The total number of characters in your name is: 4
Your first and last name are the same
-----------------------------------------------------------------------Please enter your first name: My
Do you have a middle name?(Y/N): zPlease press either 'Y' or 'N'
Program exiting...
C++ || Count The Total Number Of Characters, Vowels, & UPPERCASE Letters Contained In A Sentence Using A ‘While Loop’
This program will prompt the user to enter a sentence, then upon entering an “exit code,” will display the total number of uppercase letters, vowels and characters contained within that sentence. This program is very similar to an earlier project, this time, utalizing a while loop, the setw and setfill functions.
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 |
#include <iostream> #include <iomanip> using namespace std; int main() { // declare variables int numUpperCase = 0; int numVowel = 0; int numChars = 0; char character = ' '; cout << "Enter a sentence: "; // Get sentence from user utilizing while loop while(cin >> character && character != '.') { // Checks to see if inputted data is UPPERCASE if ((character >= 'A')&&(character <= 'Z')) { ++numUpperCase; // Increments Total number of uppercase by one } // Checks to see if inputted data is a vowel if ((character == 'a')||(character == 'A')||(character == 'e')|| (character == 'E')||(character == 'i')||(character == 'I')|| (character == 'o')||(character == 'O')||(character == 'u')|| (character == 'U')||(character == 'y')||(character == 'Y')) { ++numVowel; // Increments Total number of vowels by one } ++numChars; // Increments Total number of chars by one } // end loop // display data using setw and setfill cout << setfill('.'); // This will fill any excess white space with period within the program cout <<left<<setw(36)<<"ntTotal number of upper case letters:"<<right<<setw(10) <<numUpperCase<<endl; cout <<left<<setw(36)<<"tTotal number of vowels:"<<right<<setw(10) <<numVowel<<endl; cout <<left<<setw(36)<<"tTotal number of characters:"<<right<<setw(10) <<numChars<<endl; return 0; }// http://programmingnotes.freeweq.com |
QUICK NOTES:
The highlighted portions are areas of interest.
In order to use the setfill and setw functions, remember to #include iomanip, as noted on line 2.
Notice line 17 contains the while loop declaration. The loop will continually ask the user to input data, and will not stop doing so until the user enters an exit character, and the defined exit character in this program is a period (“.”). So, the program will not stop asking the user to enter data until they enter a period.
Once compiling the above code, you should receive this as your output
Enter a sentence: My Programming Notes Is Awesome.
Total number of upper case letters:.........5
Total number of vowels:....................11
Total number of characters:................27