Tag Archives: While Loop
C++ || Printing Various Patterns Using Nested Loops
This page will demonstrate various programs which illustrates the use of nested loops to print selected patterns to the screen.
REQUIRED KNOWLEDGE FOR THIS PAGE
The following are famous homework assignments which are usually presented in an entry level programming course.
There are a total of ten (10) different patterns on this page, which is broken up into sections. This page will list:
(4) methods of printing a triangle
(4) methods of printing an upside down triangle
(1) method which prints a square
(1) method which prints a giant letter 'X'
======= PRINTING A TRIANGLE =======
This program prints a triangle shape to the screen.
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 |
#include <iostream> using namespace std; int main() { // declare variables int number=0; int counter=1; // get data from user cout<<"Enter a number: "; cin>>number; // this is the start of the nested loop. // NOTE: many use two nested 'for' loops, but // sometimes its nice to switch things up while(counter <= number) { for(int x=0; x < counter; ++x) { cout<<"* "; } cout<<endl; ++counter; } return 0; }// http://programmingnotes.org/ |
In the above example, the user has a choice of entering the number of rows which will be displayed to the screen
SAMPLE OUTPUT:
Enter a number: 9
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
======= PRINTING A TRIANGLE WITH NUMBERS =======
The following program uses the same concept as above, but this time instead of using stars “*”, numbers will be printed to the screen.
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 |
#include <iostream> using namespace std; int main() { // declare variables int number=0; int counter=1; int copy=0; // get data from user cout<<"Enter a number: "; cin>>number; // this variable is just a copy // of the number that the user just entered // which will be used in the nested loop copy=number; // this is the start of the nested loop. // NOTE: many use two nested 'for' loops, but // sometimes its nice to switch things up while(counter <= number) { for(int x=0; x < counter; ++x) { cout<<copy<<" "; } cout<<endl; --copy; ++counter; } return 0; }// http://programmingnotes.org/ |
SAMPLE OUTPUT:
Enter a number: 9
9
8 8
7 7 7
6 6 6 6
5 5 5 5 5
4 4 4 4 4 4
3 3 3 3 3 3 3
2 2 2 2 2 2 2 2
1 1 1 1 1 1 1 1 1
======= PRINTING A TRIANGLE WITH NUMBERS IN-ORDER =======
The following program uses the same concept as above, but this time instead of using stars “*”, numbers will be printed to the screen in-order.
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 |
#include <iostream> using namespace std; int main() { // declare variables int number=0; int counter=1; int copy=0; // get data from user cout<<"Enter a number: "; cin>>number; // this is the start of the nested loop. // NOTE: many use two nested 'for' loops, but // sometimes its nice to switch things up while(counter <= number) { copy=number; for(int x=0; x < counter; ++x) { cout<<copy-(counter-1)<<" "; ++copy; } cout<<endl; ++counter; } return 0; }// http://programmingnotes.org/ |
SAMPLE OUTPUT:
Enter a number: 9
9
8 9
7 8 9
6 7 8 9
5 6 7 8 9
4 5 6 7 8 9
3 4 5 6 7 8 9
2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
======= PRINTING A TRIANGLE WITH NUMBERS USING MULTIPLICATION =======
This example demonstrates another triangle, this time printing a multiplication table.
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 |
#include <iostream> using namespace std; int main() { // declare variables int number=0; int counter=1; // get data from user cout<<"Enter a number: "; cin>>number; // this is the start of the nested loop // NOTE: many use two nested 'for' loops, but // sometimes its nice to switch things up while(counter <= number) { for(int x=1; x <= counter; ++x) { cout<<number*x<<" "; } cout<<endl; ++counter; } return 0; }// http://programmingnotes.org/ |
SAMPLE OUTPUT:
Enter a number: 9
9
9 18
9 18 27
9 18 27 36
9 18 27 36 45
9 18 27 36 45 54
9 18 27 36 45 54 63
9 18 27 36 45 54 63 72
9 18 27 36 45 54 63 72 81
======= PRINTING AN UPSIDE-DOWN TRIANGLE =======
This program is similar to the first one, this time printing the triangle upside-down.
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 |
#include <iostream> using namespace std; int main() { // declare variables int number=0; int counter=0; int copy=0; // get data from user cout<<"Enter a number: "; cin>>number; // this variable is just a copy // of the number that the user just entered // which will be used in the nested loop copy=number; // this is the start of the nested loop // NOTE: many use two nested 'for' loops, but // sometimes its nice to switch things up while(counter <= number) { for(int x=1; x <= copy; ++x) { cout<<"* "; } cout<<endl; --copy; ++counter; } return 0; }// http://programmingnotes.org/ |
SAMPLE OUTPUT:
Enter a number: 9
* * * * * * * * *
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
======= PRINTING AN UPSIDE-DOWN TRIANGLE WITH NUMBERS =======
This program is similar to the second one, this time printing the triangle upside-down.
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 |
#include <iostream> using namespace std; int main() { // declare variables int number=0; int counter=1; int copy=0; // get data from user cout<<"Enter a number: "; cin>>number; // this variable is just a copy // of the number that the user just entered // which will be used in the nested loop copy=number; // this is the start of the nested loop // NOTE: many use two nested 'for' loops, but // sometimes its nice to switch things up while(counter <= number) { for(int x=1; x <= copy; ++x) { cout<<copy<<" "; } cout<<endl; --copy; ++counter; } return 0; }// http://programmingnotes.org/ |
SAMPLE OUTPUT:
Enter a number: 9
9 9 9 9 9 9 9 9 9
8 8 8 8 8 8 8 8
7 7 7 7 7 7 7
6 6 6 6 6 6
5 5 5 5 5
4 4 4 4
3 3 3
2 2
1
======= PRINTING AN UPSIDE-DOWN TRIANGLE WITH NUMBERS IN-ORDER =======
The following program uses the same concept as above, but this time instead of using stars “*”, numbers will be printed to the screen in-order.
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 |
#include <iostream> using namespace std; int main() { // declare variables int number=0; int counter=1; int copy=0; // get data from user cout<<"Enter a number: "; cin>>number; copy=number; // this is the start of the nested loop. // NOTE: many use two nested 'for' loops, but // sometimes its nice to switch things up while(counter <= number) { for(int x=counter; x <= copy; ++x) { cout<<x<<" "; } cout<<endl; ++counter; } return 0; }// http://programmingnotes.org/ |
SAMPLE OUTPUT:
Enter a number: 9
1 2 3 4 5 6 7 8 9
2 3 4 5 6 7 8 9
3 4 5 6 7 8 9
4 5 6 7 8 9
5 6 7 8 9
6 7 8 9
7 8 9
8 9
9
===== PRINTING AN UPSIDE-DOWN TRIANGLE WITH NUMBERS USING MULTIPLICATION =====
This program is similar to the third one, this time printing the triangle upside-down.
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 |
#include <iostream> using namespace std; int main() { // declare variables int number=0; int counter=1; int copy=0; // get data from user cout<<"Enter a number: "; cin>>number; // this variable is just a copy // of the number that the user just entered // which will be used in the nested loop copy=number; // this is the start of the nested loop // NOTE: many use two nested 'for' loops, but // sometimes its nice to switch things up while(counter <= number) { for(int x=1; x <= copy; ++x) { cout<<number*x<<" "; } cout<<endl; --copy; ++counter; } return 0; }// http://programmingnotes.org/ |
SAMPLE OUTPUT:
Enter a number: 9
9 18 27 36 45 54 63 72 81
9 18 27 36 45 54 63 72
9 18 27 36 45 54 63
9 18 27 36 45 54
9 18 27 36 45
9 18 27 36
9 18 27
9 18
9
======= PRINTING A SQUARE =======
This program prints a square to the screen.
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 |
#include <iostream> using namespace std; int main() { // declare variables int row=0; int column=0; int number=0; cout<<"Enter the number of rows to be printed: "; cin >> number; row = number; // draw top while (row > 0) { cout<<"*"; --row; } cout<<endl; row = number - 2; column = number; // draw middle while (row > 0) { while (column > 0) { if ((column == number) || (column == 1)) { cout<<"*"; } else { cout<<" "; } --column; } cout<<endl; column = number; --row; } row = number; // draw bottom while (row > 0) { cout<<"*"; --row; } cout<<endl; return 0; }// http://programmingnotes.org/ |
SAMPLE OUTPUT:
1 2 3 4 5 6 7 8 9 10 |
Enter the number of rows to be printed: 9 ********* * * * * * * * * * * * * * * ********* |
======= PRINTING THE LETTER “X” =======
The final program for this page will print a giant letter “X” to the screen.
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 |
#include <iostream> #include <cstdlib> using namespace std; int main() { // declare variables int number=0; int counter1=0; cout<<"Enter the size of the shape: "; cin >> number; // set 'counter1' equal to 'number' counter1=-number; // start of the nested loop while(counter1 <=number) { for (int counter2 = -number; counter2 <= number; ++counter2) { if (abs(counter1) == abs(counter2)) { cout<<"x"; } else { cout<<" "; } } ++counter1; cout<<endl; } return 0; }// http://programmingnotes.org/ |
SAMPLE OUTPUT:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
Enter the size of the shape: 9 x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x |
And there you have it. Simple shapes made possible in C++.
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.
C++ || Stack Based Postfix Evaluation (Single Digit)
This page consists of another homework assignment which was presented in a C++ Data Structures course. While the previously discussed program dealt with converting Infix expressions to Postfix, this program will demonstrate exactly how to evaluate them.
NOTE: Want to convert & evaluate multi digit, decimal, and negative numbers? Click here!
REQUIRED KNOWLEDGE FOR THIS PROGRAM
What Is Postfix?
How To Convert Infix To Postfix Equations
Stack Data Structure
Cin.getline
How To Evaluate Postfix Expressions
The Order Of Operations
#include "ClassStackType.h"
The title of this page is called – “Stack Based Postfix Evaluation (Single Digit).” Why “single digit?” The program demonstrated on this page has the ability to evaluate a postfix equation, but it only has the ability to evaluate single digit values. What do I mean by that? Consider the infix equation: 5+2. When that expression is converted to postfix, it will come out to be: 52+, and the answer will be 7 (5+2=7). But what if we have an equation like 12+2? When that expression is converted to postfix, it will come out to be: 122+. The postfix conversion is correct, but when you try to evaluate the expression, we do not know if the math operation should be 12+2 or 1+22, it can be read either way.
Question: So why is this program being displayed if it only works for single digits?
Answer: Because it demonstrates the process of evaluating postfix equations very well.
Want to convert & evaluate multi digit, decimal, and negative numbers? Click here!
Before we get into things, here is a helpful algorithm for evaluating a postfix expression in pseudo 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 |
// An algorithm for postfix evaluation. // For example, (1 + 2) / (5 + 6) translates to 1 2 + 5 6 + / // which equals the result of 0.272727 // Valid operands are single digits: 0-9 // Valid operators are: +, -, *, /, ^, $ // Highest precedence: ^, $ // Lowest precedence: +,- // the operators ')' and '('never goes on stack. double EvaluatePostfix(string postfix) { while there is input { if input is a number push current number on stack else if input is a math operator and stack is not empty set operand2 to the top of the operand stack pop the stack set operand1 to the top of the operand stack pop the stack apply the math operation that represents to operand1 and operand2 push the result onto the stack else error } // When the loop is finished, the operand stack will contain one item, // the result of evaluating the expression pop the stack return the answer to the caller }// http://programmingnotes.org/ |
Once you understand the process of converting from infix to postfix, adding the ability to evaluate multiple digits within this program should be doable.
======= POSTFIX EVALUATION =======
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 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 |
// ============================================================================ // Author: Kenneth Perkins // Date: Mar 24, 2012 // Taken From: http://programmingnotes.org/ // File: PostfixEvaluation.cpp // Description: Demonstrate the use of a stack based postfix evaluation. // ============================================================================ #include <iostream> #include <cstdlib> #include <cmath> #include "ClassStackType.h" using namespace std; // function prototypes void DisplayDirections(); double EvaluatePostfix(char* postfix); bool IsMathOperator(char token); double DoMath(double op1, double op2, char token); int main() { // declare variables char expression[50]; // array holding the postfix data double answer = 0; // display directions to user DisplayDirections(); // get data from user cout<<"\nPlease enter a postfix expression: "; cin.getline(expression, sizeof(expression)); cout <<"\nThe postfix expression = "<<expression<<endl; cout<<"\nCalculations:\n"; answer = EvaluatePostfix(expression); cout<<"\nFinal answer = "<<answer<<endl; return 0; }// end of main void DisplayDirections() { cout << "\n==== Postfix Evaluation ====\n" <<"\nMath Operators:\n" <<"+ || Addition\n" <<"- || Subtraction\n" <<"* || Multiplication\n" <<"/ || Division\n" <<"% || Modulus\n" <<"^ || Power\n" <<"$ || Square Rootn\n" <<"Sample Postfix Equation: 45^14*232+$2-/12%24*/* \n"; }// end of DisplayDirections double EvaluatePostfix(char* postfix) { // declare function variables int counter = 0; int currentNum = 0; char token = 'a'; double op1 = 0; double op2 = 0; double answer = 0; StackType<double> doubleStack; // loop thru array until there is no more data while(postfix[counter] != '\0') { // push numbers onto the stack if(isdigit(postfix[counter])) { currentNum = postfix[counter] - '0'; doubleStack.Push(currentNum); } else if(isspace(postfix[counter])) { // DO NOTHING } // if expression is a math operator, pop numbers from stack // & send the popped numbers to the 'DoMath' function else if((IsMathOperator(postfix[counter])) && (!doubleStack.IsEmpty())) { token = postfix[counter]; // if expression is square root operation // only pop stack once if(token == '$') { op2 = 0; op1 = doubleStack.Top(); doubleStack.Pop(); answer = DoMath(op1,op2,token); doubleStack.Push(answer); } else { op2 = doubleStack.Top(); doubleStack.Pop(); op1 = doubleStack.Top(); doubleStack.Pop(); answer = DoMath(op1,op2,token); doubleStack.Push(answer); } } else { cout<<"\nINVALID INPUT\n"; exit(1); } ++counter; } // pop the final answer from the stack, and return to main answer = doubleStack.Top(); doubleStack.Pop(); return answer; }// end of EvaluatePostfix bool IsMathOperator(char token) {// this function checks if operand is a math operator switch(token) { case '+': return true; break; case '-': return true; break; case '*': return true; break; case '/': return true; break; case '%': return true; break; case '^': return true; break; case '$': return true; break; default: return false; break; } }// end of IsMathOperator double DoMath(double op1, double op2, char token) {// this function carries out the actual math process double ans = 0; switch(token) { case '+': cout<<op1<<token<<op2<<" = "; ans = op1 + op2; break; case '-': cout<<op1<<token<<op2<<" = "; ans = op1 - op2; break; case '*': cout<<op1<<token<<op2<<" = "; ans = op1 * op2; break; case '/': cout<<op1<<token<<op2<<" = "; ans = op1 / op2; break; case '%': cout<<op1<<token<<op2<<" = "; ans = (int)op1 % (int)op2; break; case '^': cout<<op1<<token<<op2<<" = "; ans = pow(op1, op2); break; case '$': cout<<char(251)<<op1<<" = "; ans = sqrt(op1); break; default: ans = 0; break; } cout<<ans<<endl; return ans; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
Want to convert & evaluate multi digit, decimal, and negative numbers? Click here!
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 three separate times to display different output)
====== RUN 1 ======
==== Postfix Evaluation ====
Math Operators:
+ || Addition
- || Subtraction
* || Multiplication
/ || Division
% || Modulus
^ || Power
$ || Square RootSample Postfix Equation: 45^14*232+$2-/12%24*/*
Please enter a postfix expression: 1 2 + 5 6 + /
The postfix expression = 1 2 + 5 6 + /Calculations:
1+2 = 3
5+6 = 11
3/11 = 0.272727
Final answer = 0.272727====== RUN 2 ======
==== Postfix Evaluation ====
Math Operators:
+ || Addition
- || Subtraction
* || Multiplication
/ || Division
% || Modulus
^ || Power
$ || Square RootSample Postfix Equation: 45^14*232+$2-/12%24*/*
Please enter a postfix expression: 35*76^+
The postfix expression = 35*76^+Calculations:
3*5 = 15
7^6 = 117649
15+117649 = 117664
Final answer = 117664====== RUN 3 ======
==== Postfix Evaluation ====
Math Operators:
+ || Addition
- || Subtraction
* || Multiplication
/ || Division
% || Modulus
^ || Power
$ || Square RootSample Postfix Equation: 45^14*232+$2-/12%24*/*
Please enter a postfix expression: 45^4*32+$2-/12%24*/*
The postfix expression = 45^4*32+$2-/12%24*/*Calculations:
4^5 = 1024
1024*4 = 4096
3+2 = 5
√5 = 2.23607
2.23607-2 = 0.236068
4096/0.236068 = 17350.9
1%2 = 1
2*4 = 8
1/8 = 0.125
17350.9*0.125 = 2168.87
Final answer = 2168.87
C++ || Stack Based Infix To Postfix Conversion (Single Digit)
This page consists of another homework assignment which was presented in a C++ Data Structures course. No matter which institution you attend, it seems every instructor assigns a program similar to this at one time or another.
Want to evaluate a postfix expression? Click here.
Want to convert & evaluate multi digit, decimal, and negative numbers? Click here!
REQUIRED KNOWLEDGE FOR THIS PROGRAM
What Is Infix?
What Is Postfix?
Stack Data Structure
Cin.getline
How To Convert To Postfix
The Order Of Operations
#include "ClassStackType.h"
The program demonstrated on this page has the ability to convert a normal infix equation to postfix equation, so for example, if the user enters the infix equation of (1*2)+3, the program will display the postfix result of 12*3+.
Before we get into things, here is a helpful algorithm for converting from infix to postfix in pseudo 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 |
// An algorithm for infix to postfix expression conversion. // For example, a + b - c translates to a b + c - // a + b * c translates to a b c * + // (1 + 2) / (5 + 6) goes to 1 2 + 5 6 + / // Valid operands are single digits: 0-9, a-z, A-Z // Valid operators are: +, -, *, /, (, ), ^, $ // Highest precedence: ^, $ // Lowest precedence: +,- // ) never goes on stack. // ( has lowest precedence on the stack and highest precedence outside of stack. // Bottom of the stack has the lowest precedence than any operator. // Use a prec() function to compare the precedence of the operators based on the above rules. // Note there is little error checking in the algorithm! void ConvertInfixToPostfix(string infix) { while there is input { if input is a number or a letter place onto postfix string else if input is '(' // '(' has lowest precedence in the stack, highest outside push input on stack else if input is ')' while stack is not empty and top of stack is not '(' place item from top of stack onto postfix string pop stack if stack is not empty // pops '(' off the stack pop stack else error // no matching '(' else if input is a math operator if stack is empty push input on stack else if prec(top of stack) >= prec(current math operator) while stack is not empty and prec(top of stack) >= prec(current math operator) place item from top of stack onto postfix string pop stack push current math operator on stack else error } while stack is not empty { place item from top of stack onto postfix string pop stack } }// http://programmingnotes.org/ |
======= INFIX TO POSTFIX CONVERSION =======
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 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 |
// ============================================================================ // Author: Kenneth Perkins // Date: Mar 23, 2012 // Taken From: http://programmingnotes.org/ // File: PostfixConversion.cpp // Description: Demonstrate the use of a stack based infix to // postfix conversion. // ============================================================================ #include <iostream> #include <cctype> #include <cstdlib> #include <cstring> #include "ClassStackType.h" using namespace std; // function prototypes void DisplayDirections(); void ConvertInfixToPostfix(char* infix); int OrderOfOperations(char token); bool IsMathOperator(char token); int main() { // declare variables char expression[50]; // array holding the infix data // display directions to user DisplayDirections(); // get data from user cout<<"\nPlease enter an infix expression: "; cin.getline(expression, sizeof(expression)); cout <<"\nThe Infix expression = "<<expression<<endl; ConvertInfixToPostfix(expression); cout<<"The Postfix expression = "<<expression<<endl; return 0; }// end of main void DisplayDirections() { cout << "\n==== Infix to Postfix Conversion ====\n" <<"\nMath Operators:\n" <<"+ || Addition\n" <<"- || Subtraction\n" <<"* || Multiplication\n" <<"/ || Division\n" <<"% || Modulus\n" <<"^ || Power\n" <<"$ || Square Root\n" <<"Sample Infix Equation: (((4^5)*14)/($(23+2)-2))*(1%2)/(2*4)\n"; }// end of DisplayDirections void ConvertInfixToPostfix(char* infix) { // declare function variables int infixCounter = 0; int postfixCounter = 0; char token = 'a'; char postfix[50]; StackType<char> charStack; // loop thru array until there is no more data while(infix[infixCounter] != '\0') { // push numbers/letters onto 'postfix' array if(isdigit(infix[infixCounter]) || isalpha(infix[infixCounter])) { postfix[postfixCounter] = infix[infixCounter]; ++postfixCounter; } else if(isspace(infix[infixCounter])) { // DO NOTHING } else if(IsMathOperator(infix[infixCounter])) { // if stack is empty, place first math operator onto stack token = infix[infixCounter]; if(charStack.IsEmpty()) { charStack.Push(token); } else { // get the current math operator from the top of the stack token = charStack.Top(); charStack.Pop(); // use the 'OrderOfOperations' function to check equality // of the math operators while(OrderOfOperations(token) >= OrderOfOperations(infix[infixCounter])) { // if stack is empty, do nothing if(charStack.IsEmpty()) { break; } // place the popped math operator from above ^ // onto the postfix array else { postfix[postfixCounter] = token; ++postfixCounter; // pop the next operator from the stack and // continue the process until complete token = charStack.Top(); charStack.Pop(); } } // push any remainding math operators onto the stack charStack.Push(token); charStack.Push(infix[infixCounter]); } } // push outer parentheses onto stack else if(infix[infixCounter] == '(') { charStack.Push(infix[infixCounter]); } else if(infix[infixCounter] == ')') { // pop the current math operator from the stack token = charStack.Top(); charStack.Pop(); while(token != '(' && !charStack.IsEmpty()) { // place the math operator onto the postfix array postfix[postfixCounter] = token; ++postfixCounter; // pop the next operator from the stack and // continue the process until complete token = charStack.Top(); charStack.Pop(); } } else { cout<<"\nINVALID INPUT\n"; exit(1); } ++infixCounter; } // place any remaining math operators from the stack onto // the postfix array while(!charStack.IsEmpty()) { postfix[postfixCounter] = charStack.Top(); ++postfixCounter; charStack.Pop(); } postfix[postfixCounter] = '\0'; // copy the data from the postfix array into the infix array // the data in the infix array gets sent back to main // since the array is passed by reference strcpy(infix,postfix); }// end of ConvertInfixToPostfix int OrderOfOperations(char token) {// this function checks priority of each math operator int priority = 0; if(token == '^'|| token == '$') { priority = 4; } else if(token == '*' || token == '/' || token == '%') { priority = 3; } else if(token == '-') { priority = 2; } else if(token == '+') { priority = 1; } return priority; }// end of OrderOfOperations bool IsMathOperator(char token) {// this function checks if operand is a math operator switch(token) { case '+': return true; break; case '-': return true; break; case '*': return true; break; case '/': return true; break; case '%': return true; break; case '^': return true; break; case '$': return true; break; default: return false; break; } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
Want to convert & evaluate multi digit, decimal, and negative numbers? Click here!
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Want to evaluate a postfix expression? Click here for sample code.
Once compiled, you should get this as your output
(Note: the code was compile three separate times to display different output)
====== RUN 1 ======
==== Infix to Postfix Conversion ====
Math Operators:
+ || Addition
- || Subtraction
* || Multiplication
/ || Division
% || Modulus
^ || Power
$ || Square RootSample Infix Equation: (((4^5)*14)/($(23+2)-2))*(1%2)/(2*4)
Please enter an infix expression: ((a+b)+c)/(d^e)
The Infix expression = ((a+b)+c)/(d^e)
The Postfix expression = ab+c+de^/====== RUN 2 ======
==== Infix to Postfix Conversion ====
Math Operators:
+ || Addition
- || Subtraction
* || Multiplication
/ || Division
% || Modulus
^ || Power
$ || Square RootSample Infix Equation: (((4^5)*14)/($(23+2)-2))*(1%2)/(2*4)
Please enter an infix expression: (3*5)+(7^6)
The Infix expression = (3*5)+(7^6)
The Postfix expression = 35*76^+====== RUN 3 ======
==== Infix to Postfix Conversion ====
Math Operators:
+ || Addition
- || Subtraction
* || Multiplication
/ || Division
% || Modulus
^ || Power
$ || Square RootSample Infix Equation: (((4^5)*14)/($(23+2)-2))*(1%2)/(2*4)
Please enter an infix expression: (((4^5)*14)/($(23+2)-2))*(1%2)/(2*4)
The Infix expression = (((4^5)*14)/($(23+2)-2))*(1%2)/(2*4)
The Postfix expression = 45^14*232+$2-/12%24*/*
C++ || Snippet – How To Reverse An Integer Using Modulus & While Loop
This page will consist of a simple program which demonstrates how to reverse an integer (not an int array) using modulus and a while loop.
REQUIRED KNOWLEDGE FOR THIS SNIPPET
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 |
#include <iostream> using namespace std; // function prototype int ReverseNumber(int number); int main() { // declare variables int number = 0; int numReversed = 0; // get data from user cout << "Enter a number: "; cin >> number; // function call which will return the reversed number numReversed = ReverseNumber(number); // display new data to user cout <<endl<< number << " reversed is: "<< numReversed <<endl; return 0; }// end of main int ReverseNumber(int number) { // declare function variable int rev=0; while(number > 0) { rev = rev * 10 + (number % 10); number = number/10; } return rev; }// 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 three separate times to display different output)
==== RUN #1 ====
Enter a number: 2012
2012 reversed is: 2102==== RUN #2 ====
Enter a number: 1987
1987 reversed is: 7891==== RUN #3 ====
Enter a number: 241
241 reversed is: 142
C++ || 8 Different Ways To Reverse A String/Character Array In C++
This page will consist of 8 different ways to reverse a character array, and a string literal (std::string).
REQUIRED KNOWLEDGE FOR THE PROGRAMS
Character Arrays
String Literals
Cin.getline - Use For Char Arrays
Getline - Use For std::string
Length
Strlen
Strcpy
While Loops
For Loops
Recursion - What is it?
#include < algorithm>
#include < stack>
The methods on this page will be broken up into sections. This page will list:
(3) methods which reverses string literals (std::string)
(4) methods which reverses character arrays
(1) method which utilizes the stack to "reverse" a character sequence
Some methods listed on this page demonstrates the use of reversing a character sequence without the use of strlen/length.
======= REVERSE AN STD::STRING =======
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> #include <algorithm> #include <string> using namespace std; int main() { // declare variable string name=""; cout << "Enter your name: "; getline(cin,name); // built in C++ function to reverse an std::string reverse(name.begin(), name.end()); cout <<"\nYour name reversed is: " <<name << endl; return 0; }// http://programmingnotes.org/ |
SAMPLE OUTPUT
Enter your name: My Programming NotesYour name reversed is: setoN gnimmargorP yM
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 |
#include <iostream> #include <string> using namespace std; // function prototypes void Reverse(string name); int main() { // declare variable string name=""; // get user data cout<<"Enter your name: "; getline(cin,name); cout<<"\nYour name reversed is: "; // function declaration Reverse(name); cout<<endl; return 0; }// end of main void Reverse(string name) { if(name == "") // the base case { return; } else // the recursive step { Reverse(name.substr(1)); cout<<name.at(0); } }// http://programmingnotes.org/ |
SAMPLE OUTPUT
Enter your name: My Programming NotesYour name reversed is: setoN gnimmargorP yM
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 |
#include <iostream> #include <string> using namespace std; // function prototypes void Reverse(string name); int main() { // declare variable string name=""; // get user data cout<<"Enter your name: "; getline(cin,name); cout<<"\nYour name reversed is: "; // function declaration Reverse(name); cout<<endl; return 0; }// end of main void Reverse(string name) { // get the length of the string int nameLength = name.length()-1; while(nameLength >= 0) { cout<<name[nameLength]; --nameLength; } }// http://programmingnotes.org/ |
SAMPLE OUTPUT
Enter your name: My Programming NotesYour name reversed is: setoN gnimmargorP yM
======= REVERSE A CHARACTER ARRAY =======
The following will demonstrate (4) methods which reverses a character array.
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 |
#include <iostream> using namespace std; // function prototype void Reverse(char name[]); int main() { // declare variable char name[30]; // get user data cout<<"Enter your name: "; cin.getline(name, sizeof(name)); cout<<"\nYour name reversed is: "; // function declaration Reverse(name); cout<<endl; return 0; }// end of main void Reverse(char name[]) { if(*name=='\0') // the base case { return; } else // the recursive step { Reverse(name+1); cout<<*(name); } }// http://programmingnotes.org/ |
SAMPLE OUTPUT
Enter your name: My Programming NotesYour name reversed is: setoN gnimmargorP yM
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 |
#include <iostream> using namespace std; // function prototypes void Reverse(char name[]); int main() { // declare variable char name[30]; // get user data cout<<"Enter your name: "; cin.getline(name, sizeof(name)); cout<<"\nYour name reversed is: "; // function declaration Reverse(name); cout<<endl; return 0; }// end of main void Reverse(char name[]) { int nameLength = 0; //get the length of array while(name[nameLength] != '\0') { ++nameLength; } //decrease the length of by 1 --nameLength; // display reversed string while(nameLength >= 0) { cout<<name[nameLength]; --nameLength; } }// http://programmingnotes.org/ |
SAMPLE OUTPUT
Enter your name: My Programming NotesYour name reversed is: setoN gnimmargorP yM
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 |
#include <iostream> #include <cstring> using namespace std; // function prototypes void Reverse(char name[]); int main() { // declare variable char name[30]; // get user data cout<<"Enter your name: "; cin.getline(name, sizeof(name)); // function declaration Reverse(name); cout<<"\nYour name reversed is: "<< name<<endl; return 0; }// end of main void Reverse(char name[]) { // private variables int nameLength = 0; char copy[30]; strcpy(copy,name); //get lenght of array while(name[nameLength] != '\0') { ++nameLength; } //decrease the length of by 1 --nameLength; // reverse the array for(int x = 0; x <= nameLength; ++x) { // rearange the order of the two arrays name[nameLength - x] = copy[x]; } }// http://programmingnotes.org/ |
SAMPLE OUTPUT
Enter your name: My Programming NotesYour name reversed is: setoN gnimmargorP yM
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 |
#include <iostream> #include <cstring> using namespace std; // function prototypes void Reverse(char name[]); int main() { // declare variable char name[30]; // get user data cout<<"Enter your name: "; cin.getline(name, sizeof(name)); // function declaration Reverse(name); cout<<"\nYour name reversed is: "<< name<<endl; return 0; }// end of main void Reverse(char name[]) { // get the length of the current word in the array index int nameLength = strlen(name)-1; // increment thru each letter within the current char array index // reversing the order of the array for(int currentChar=0; currentChar < nameLength; --nameLength, ++currentChar) { // copy 1st letter in the array index into temp char temp = name[currentChar]; // copy last letter in the array index into the 1st array index name[currentChar] = name[nameLength]; // copy temp into last array index name[nameLength] = temp; } }// http://programmingnotes.org/ |
SAMPLE OUTPUT
Enter your name: My Programming NotesYour name reversed is: setoN gnimmargorP yM
======= REVERSE A CHARACTER SEQUENCE USING A STACK =======
The following will demonstrate (1) method which reverses a character sequence using the STL stack.
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 |
#include <iostream> #include <stack> using namespace std; // function prototypes void Reverse(stack<char> &name); int main() { // using the internal system stack stack<char> name; char singleChar; cout<<"Enter your name: "; while(cin.get(singleChar) && singleChar != '\n') { name.push(singleChar); } cout<<"\nYour name reversed is: "; // function declaration Reverse(name); cout<<endl; return 0; }// end of main void Reverse(stack<char> &name) { while(!name.empty()) { cout << name.top(); name.pop(); } }// http://programmingnotes.org/ |
SAMPLE OUTPUT
Enter your name: My Programming NotesYour name reversed is: setoN gnimmargorP yM
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++ || Snippet – How To Read & Write Data From A File
This page will consist of a demonstration of a simple quadratic formula program, which highlights the use of the input/output mechanisms of manipulating a text file. This program will read in data from a file (numbers), manipulate that data, and output new data into a different text file.
REQUIRED KNOWLEDGE FOR THIS SNIPPET
NOTE: The data file that is used in this example can be downloaded here.
Also, 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 > Projects > [Your project name] > [Your project name]
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 |
// ============================================================================ // Author: Kenneth Perkins // Date: Feb 12, 2012 // Taken From: http://programmingnotes.org/ // File: FileInput.cpp // Description: Demonstrates how to read data from a file // ============================================================================ #include <iostream> #include <fstream> #include <cstdlib> // used for the 'exit' command #include <cmath> using namespace std; int main () { // declare variables ifstream infile; ofstream outfile; double a=0,b=0,c=0; double root1=0, root2=0; // this opens the input file // YOUR INPUT FILE NAME GOES BELOW infile.open("INPUT_Quadratic_programmingnotes_freeweq_com.txt"); // check to see if the file even exists, & if not then EXIT if(infile.fail()) { cout<<"\nError, the input file could not be found!\n"; exit(1); // exits the program } // this opens the output file // if the file doesnt already exist, it will be created outfile.open("OUTPUT_Quadratic_programmingnotes_freeweq_com.txt"); // this loop reads in data until there is no more // data contained in the file while(infile.good()) { // this assigns the incoming data to the // variables 'a', 'b' and 'c' // NOTE: it is just like a cin >> statement infile >> a >> b >> c; // NOTE: if you want to read in data into an array // your declaration would be like this // ------------------------------------ // infile >> a[counter] >> b[counter] >> c[counter]; // ++counter; } // this does the quadratic formula calculations root1 = ((-b) + sqrt(pow(b,2) - (4*a*c)))/(2*a); root2 = ((-b) - sqrt(pow(b,2) - (4*a*c)))/(2*a); // this displays the numbers to screen via cout cout <<"For the numbers\na = "<<a<<"\nb = "<<b<<"\nc = "<<c<<endl; cout <<"\nroot 1 = "<<root1<<"\nroot 2 = "<<root2<<endl; // this saves the data to the output file // NOTE: its almost exactly the same as the cout statement outfile <<"For the numbers\na = "<<a<<"\nb = "<<b<<"\nc = "<<c<<endl; outfile <<"\nroot 1 = "<<root1<<"\nroot 2 = "<<root2<<endl; // close the input/output files once you are done using them infile.close(); outfile.close(); // stops the program from automatically closing cin.get(); 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
For the numbers
a = 2
b = 4
c = -16root 1 = 2
root 2 = -4
C++ || Snippet – Bubble Sort, Selection Sort, Insertion Sort, Quick Sort & Merge Sort Sample Code For Integer Arrays
This page consists of algorithms for sorting integer arrays. Highlighted on this page are Bubble Sort, Selection Sort, Insertion Sort, Quick Sort, and Merge Sort.
In terms of performance and speed, the sorting algorithms on this page will be listed from the (on average) worst, to best case implementations.
Selection sort and Insertion sort are two simple sorting algorithms which are often more efficient than Bubble Sort, though all three techniques aren’t the top of the class algorithmically for sorting large data sets.
====== BUBBLE SORT ======
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 |
// ============================================================================ // Author: Kenneth Perkins // Date: Feb 11, 2012 // Taken From: http://programmingnotes.org/ // File: bubbleSort.cpp // Description: Demonstrates how to sort an array using bubble sort // ============================================================================ #include <iostream> #include <iomanip> #include <ctime> #include <cstdlib> using namespace std; // const int const int NUM_INTS = 12; // function prototype void BubbleSort(int arry[], int arraySize); int main() { // variable declarations int arry[NUM_INTS]; srand(time(NULL)); // place random numbers into the array for (int x = 0; x < NUM_INTS; ++x) { arry[x] = rand() % 100 + 1; } cout << "Original array values" << endl; // output the original array values for (int x = 0; x < NUM_INTS; ++x) { cout << setw(4) << arry[x]; } // creates a line seperator cout << "\n--------------------------------------------------------\n"; BubbleSort(arry, NUM_INTS); cout << "The current sorted array" << endl; // output the current sorted array values for (int x = 0; x < NUM_INTS; ++x) { cout << setw(4) << arry[x]; } cout << endl; cin.get(); return 0; }// end of main void BubbleSort(int arry[], int arraySize) { bool sorted = false; do { sorted = true; for (int x = 0; x < arraySize - 1; ++x) { if (arry[x] > arry[x + 1]) { int temp = arry[x]; arry[x] = arry[x + 1]; arry[x + 1] = temp; sorted = false; } }// end of for loop --arraySize; } while (!sorted); }// http://programmingnotes.org/ |
SAMPLE OUTPUT:
Original array values
91 65 53 93 54 41 69 76 55 90 10 62
--------------------------------------------------------
The current sorted array
10 41 53 54 55 62 65 69 76 90 91 93
====== SELECTION SORT ======
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 |
// ============================================================================ // Author: Kenneth Perkins // Date: Feb 11, 2012 // Taken From: http://programmingnotes.org/ // File: selectionSort.cpp // Description: Demonstrates how to sort an array using selection sort // ============================================================================ #include <iostream> #include <iomanip> #include <ctime> #include <cstdlib> using namespace std; // const int const int NUM_INTS = 12; // function prototype void SelectionSort(int arry[], int arraySize); int main() { // variable declarations int arry[NUM_INTS]; srand(time(NULL)); // place random numbers into the array for (int x = 0; x < NUM_INTS; ++x) { arry[x] = rand() % 100 + 1; } cout << "Original array values" << endl; // output the original array values for (int x = 0; x < NUM_INTS; ++x) { cout << setw(4) << arry[x]; } // creates a line seperator cout << "\n--------------------------------------------------------\n"; SelectionSort(arry, NUM_INTS); cout << "The current sorted array" << endl; // output the current sorted array values for (int x = 0; x < NUM_INTS; ++x) { cout << setw(4) << arry[x]; } cout << endl; cin.get(); return 0; }// end of main void SelectionSort(int arry[], int arraySize) { for (int currentNumber = 0; currentNumber < arraySize; ++currentNumber) { int index_of_min = currentNumber; for (int previousNumber = currentNumber + 1; previousNumber < arraySize; ++previousNumber) { if (arry[index_of_min] > arry[previousNumber]) { index_of_min = previousNumber; } } int temp = arry[currentNumber]; arry[currentNumber] = arry[index_of_min]; arry[index_of_min] = temp; } }// http://programmingnotes.org/ |
SAMPLE OUTPUT:
Original array values
87 74 58 64 4 43 23 16 3 93 9 80
--------------------------------------------------------
The current sorted array
3 4 9 16 23 43 58 64 74 80 87 93
====== INSERTION SORT ======
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 |
// ============================================================================ // Author: Kenneth Perkins // Date: Feb 11, 2012 // Taken From: http://programmingnotes.org/ // File: insertionSort.cpp // Description: Demonstrates how to sort an array using insertion sort // ============================================================================ #include <iostream> #include <iomanip> #include <ctime> #include <cstdlib> using namespace std; // const int const int NUM_INTS = 12; // function prototype void InsertionSort(int arry[], int arraySize); int main() { // variable declarations int arry[NUM_INTS]; srand(time(NULL)); // place random numbers into the array for (int x = 0; x < NUM_INTS; ++x) { arry[x] = rand() % 100 + 1; } // output the original array values cout << "Original array values" << endl; for (int x = 0; x < NUM_INTS; ++x) { cout << setw(4) << arry[x]; } // creates a line seperator cout << "\n--------------------------------------------------------\n"; InsertionSort(arry, NUM_INTS); // display sorted values cout << "The current sorted array" << endl; // output the current sorted array values for (int x = 0; x < NUM_INTS; ++x) { cout << setw(4) << arry[x]; } cout << endl; cin.get(); return 0; }// end of main void InsertionSort(int arry[], int arraySize) { int previousIndex = 0; int currentValue = 0; // iterate through entire list for (int index = 1; index < arraySize; ++index) { currentValue = arry[index]; previousIndex = index - 1; while (previousIndex >= 0 && arry[previousIndex] > currentValue) { arry[previousIndex + 1] = arry[previousIndex]; previousIndex = previousIndex - 1; }// end while loop arry[previousIndex + 1] = currentValue; }// end for loop }// http://programmingnotes.org/ |
SAMPLE OUTPUT:
Original array values
97 80 94 74 10 38 87 7 87 14 3 97
--------------------------------------------------------
The current sorted array
3 7 10 14 38 74 80 87 87 94 97 97
====== QUICK SORT ======
Quicksort is one of the fastest sorting algorithms, and is often the best practical choice for sorting, as its average expected running time for large data sets is more efficient than the previously discussed methods.
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 |
// ============================================================================ // Author: Kenneth Perkins // Date: Feb 11, 2012 // Taken From: http://programmingnotes.org/ // File: quickSort.cpp // Description: Demonstrates how to sort an array using quick sort // ============================================================================ #include <iostream> #include <ctime> #include <iomanip> #include <cstdlib> using namespace std; // const int const int NUM_INTS = 12; // function prototypes void QuickSort(int arry[], int arraySize); void QuickSort(int arry[], int start, int end); int Partition(int arry[], int start, int end); int main() { // variable declarations int arry[NUM_INTS]; srand(time(NULL)); // place random numbers into the array for (int x = 0; x < NUM_INTS; ++x) { arry[x] = rand() % 100 + 1; } cout << "Original array values" << endl; // output the original array values for (int x = 0; x < NUM_INTS; ++x) { cout << setw(4) << arry[x]; } // creates a line seperator cout << "\n--------------------------------------------------------\n"; QuickSort(arry, NUM_INTS); cout << "The current sorted array" << endl; // output the current sorted array values for (int x = 0; x < NUM_INTS; ++x) { cout << setw(4) << arry[x]; } cout << endl; cin.get(); return 0; }// end of main // the initial function call and initiates the sort void QuickSort(int arry[], int arraySize) { QuickSort(arry, 0, arraySize - 1); }// end of QuickSort // recursive call that carries out the sort void QuickSort(int arry[], int start, int end) { if (start < end) { // partition the arry and get the new pivot position int newPiviotIndex = Partition(arry, start, end); // quick sort the first part QuickSort(arry, start, newPiviotIndex); // quick sort the second part QuickSort(arry, newPiviotIndex + 1, end); } }// end of QuickSort int Partition(int arry[], int start, int end) { // choose a random pivot int pivotIndex = start + rand() % (end - start + 1); std::swap(arry[end], arry[pivotIndex]); // swap pivot with last element int left = start; // left index int right = end; // right index // compare and select smallest from the subarray for (int index = start; index <= right; ++index) { if (arry[index] < arry[right]) { std::swap(arry[index], arry[left]); ++left; } } // move pivot to its final place std::swap(arry[right], arry[left]); return left; // return the position of the new pivot }// http://programmingnotes.org/ |
SAMPLE OUTPUT:
Original array values
50 94 1 16 51 63 41 17 70 28 6 34
--------------------------------------------------------
The current sorted array
1 6 16 17 28 34 41 50 51 63 70 94
====== MERGE SORT ======
Merge sort is a fast, stable sorting routine which, in the worst case, does about (on average) 39% fewer comparisons than quick sort.
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 |
// ============================================================================ // Author: Kenneth Perkins // Date: Feb 11, 2012 // Taken From: http://programmingnotes.org/ // File: mergeSort.cpp // Description: Demonstrates how to sort an array using merge sort // ============================================================================ #include <iostream> #include <iomanip> #include <ctime> #include <cstdlib> using namespace std; // const int const int NUM_INTS = 12; // function prototypes void MergeSort(int arry[], int arraySize); void MergeSort(int arry[], int start, int end); void Merge(int arry[], int start, int midPt, int end); int main() { // variable declarations int arry[NUM_INTS]; srand(time(NULL)); // place random numbers into the array for (int x = 0; x < NUM_INTS; ++x) { arry[x] = rand() % 100 + 1; } cout << "Original array values" << endl; // output the original array values for (int x = 0; x < NUM_INTS; ++x) { cout << setw(4) << arry[x]; } // creates a line seperator cout << "\n--------------------------------------------------------\n"; MergeSort(arry, NUM_INTS); cout << "The current sorted array" << endl; // output the current sorted for (int x = 0; x < NUM_INTS; ++x) { cout << setw(4) << arry[x]; } cout << endl; cin.get(); return 0; }// end of main // the initial function call and initiates the sort void MergeSort(int arry[], int arraySize) { MergeSort(arry, 0, arraySize - 1); }// end of MergeSort // recursive call that carries out the sort void MergeSort(int arry[], int start, int end) { // no significant comparisons are done during splitting if (start < end) { int midPt = (start + end) / 2; MergeSort(arry, start, midPt); MergeSort(arry, midPt + 1, end); Merge(arry, start, midPt, end); } }// end of MergeSort // sorts the sub array void Merge(int arry[], int start, int midPt, int end) { int leftFirst = start; int leftLast = midPt; int rightFirst = midPt + 1; int rightLast = end; int* tempArray = new int[rightLast + 1]; int index = leftFirst; int saveFirst = leftFirst; while ((leftFirst <= leftLast) && (rightFirst <= rightLast)) {// compare and select smallest from two subarrays if (arry[leftFirst] < arry[rightFirst]) { tempArray[index] = arry[leftFirst]; // smallest assigned to temp ++leftFirst; } else { tempArray[index] = arry[rightFirst]; ++rightFirst; } ++index; } while (leftFirst <= leftLast) { tempArray[index] = arry[leftFirst]; ++leftFirst; ++index; } while (rightFirst <= rightLast) { tempArray[index] = arry[rightFirst]; ++rightFirst; ++index; } for (index = saveFirst; index <= rightLast; ++index) {// copies from temp array to the initial array arry[index] = tempArray[index]; } delete[] tempArray; }// http://programmingnotes.org/ |
SAMPLE OUTPUT:
Original array values
18 46 41 30 84 97 54 49 19 32 70 30
--------------------------------------------------------
The current sorted array
18 19 30 30 32 41 46 49 54 70 84 97
C++ || Dynamic Arrays – Create A Music Store Database Which Sorts CD Information & Display Grand Total
This program was presented as a homework assignment in a programming class to demonstrate the use of dynamic arrays, and pointer variables. The pointer variables which are displayed in this program are very excessive; and many are not needed, but it was good practice when trying to understand the logic behind it all.
REQUIRED KNOWLEDGE FOR THIS PROGRAM
Pointer Variables
Dynamic Arrays
2-D Dynamic Arrays - How To Declare
Bubble Sort
While Loops
For Loops
Constant Variables
Functions
Switch Statements
Toupper
Strcpy
Strcmp
This is an interactive program, which simulates a database for a music store, in which the user inputs data into the program (artist, CD title, genre, sales price, tax) and stores that information into multiple dynamic arrays (2-D and/or one dimensional dynamic arrays). The program will also apply any discounts that may currently be available for the selected CD genre, and applies that discount to the current CD information. When the user chooses to quit, the program will sort any data which is currently stored inside the array (by artist) in ascending order, and output the subtotal, tax applied, and grand total for all of the CD information which is entered into the array to the user.
After the program is complete, it will display a summary of the data which was stored into the array like so:
1 2 3 4 5 6 7 8 9 |
My Programming Notes Record Company Sales Report for 2/9/2012 Artist Title SalesPrice Genre DiscountRate SubTotal SalesTax GrandTotal Name1 CD1 12.99 Jazz 18.00% 10.65 1.26 11.91 Name2 CD2 12.99 Rap 7.00% 12.08 1.26 13.34 -------------------------------------------------------------------------------------------------------- Total (2 transactions) 22.73 2.52 25.25 |
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 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 |
// ============================================================================= // This is an interactive program, which simulates a database for a music store // in which the user inputs data into the program (atrist, CD title, genre, // sales price, tax) and stores the data into a dynamic array. The program will // also apply any discounts that may currently be available to the selected CD // genre, and applies that discount to the current CD. When the user choses // to quit, the program will sort any data that is stored inside the array // (by artist) in ascending order and it will output the subtotal, tax applied, // and grand total for all of the CD information which is entered into the array // ============================================================================= #include <iostream> #include <iomanip> #include <string> #include <ctime> using namespace std; // function prototypes double* GetDiscounts(); void DisplayMenu(); void GetCDInfo(char** &artist, char** &CDTitle, char** &genre,double* &salesPrice, double* &taxRate, int* numItems); void GetDiscountRate(double* salesPrice,char** musicGenre, char** genre,int* numItems, double* &discountPercent,double* discountRate); void GetSubTotal(double* salesPrice, double* discountRate, int* numItems,double* subTotal); void GetTaxAmount(double* salesPrice, double* taxRate, int*numItems,double* salesTax); void GetGrandTotal(double* subTotal,double* salesTax,int* numItems,double* grandTotal); void SortData(char**artist, char**CDTitle, double*salesPrice, char**genre,double*discountPercent, double*subTotal, double*salesTax, double*grandTotal, int* numItems); void DisplayData(char**artist, char**CDTitle, double*salesPrice, char**genre,double*discountPercent, double*subTotal, double*salesTax, double*grandTotal, int* numItems); // constant discount values // these values are defines within the // 'GetDiscounts' function const double* discounts = GetDiscounts(); // ============================================================================= // main // ============================================================================= int main() { //-- Declare Variables START ---// // numItems for artist array int* numItems = new int(0); // 2-D Dynamic array for music genres char** musicGenre = new char*[7]; for(int index=0; index < 7; ++index) {musicGenre[index] = new char[13];} musicGenre[0]= "Classical"; musicGenre[1]= "Country"; musicGenre[2]= "International"; musicGenre[3]= "Jazz"; musicGenre[4]= "Pop"; musicGenre[5]= "Rock"; musicGenre[6]= "Rap"; // 2-D Dynamic Array for artist name char** artist = new char*[50]; for(int index=0; index < 50; ++index) {artist[index] = new char[20];} // 2-D Dynamic array for CD titles char** CDTitle = new char*[50]; for(int index=0; index < 50; ++index) {CDTitle[index] = new char[20];} // 2-D Dynamic array of music genre char** genre = new char*[50]; for(int index=0; index < 50; ++index) {genre[index] = new char[20];} // array for list price double* salesPrice = new double[20]; // array for tax rate double* taxRate = new double[20]; // array for discount amount double* discountRate= new double[20]; // array for sales price double* subTotal = new double[20]; // array for taxamount double* salesTax= new double[20]; // array for grandTotal double* grandTotal = new double[20]; // array for discount percent double* discountPercent = new double[20]; // variable for the while loop menu char* userInput = new char('n'); // variable if the user wants to enter more data char* enterMoreData = new char('y'); //-- Declare Variables END ---// // display menu DisplayMenu(); cin >> userInput; // loop thru menu options while((toupper(*userInput) !='Q')) { switch(toupper(*userInput)) { case 'E': // get artist info GetCDInfo(artist, CDTitle, genre, salesPrice, taxRate, numItems); // get discount GetDiscountRate(salesPrice, musicGenre, genre, numItems,discountPercent, discountRate); // get sub total GetSubTotal(salesPrice, discountRate, numItems,subTotal); // get tax amount GetTaxAmount(salesPrice, taxRate, numItems,salesTax); // get cash price GetGrandTotal(subTotal, salesTax, numItems,grandTotal); // ask if they want to enter more data cout << "nDo you want to enter more CD's? (y/n): "; cin >> *enterMoreData; if(toupper(*enterMoreData)=='Y') { (++*numItems); } else { (++*numItems); *userInput='q'; } break; case 'D': DisplayData(artist, CDTitle, salesPrice, genre, discountPercent,subTotal,salesTax, grandTotal, numItems); break; default: cout<<"nYou have selected an invalid command"; break; } //creates a line separator cout<<endl; cout<<setfill('-'); cout<<left<<setw(30)<<""<<right<<setw(30)<<""<<endl; // if user wants to enter more data, display menu to screen if(toupper(*enterMoreData)=='Y') { DisplayMenu(); cin >> userInput; } }// end of while loop // sort the current data inside the array SortData(artist, CDTitle, salesPrice, genre, discountPercent,subTotal,salesTax, grandTotal, numItems); // display the current data inside the array DisplayData(artist, CDTitle, salesPrice, genre, discountPercent,subTotal,salesTax, grandTotal, numItems); return 0; }// End of Main // ============================================================================= // DisplayMenu // displays the menu to the user // ============================================================================= void DisplayMenu() { cout<<"Welcome to the CD Management System!"; cout<<"nFrom the following menu, select an option"; cout<<"nnE - Enter new CD information into the database"; cout<<"nD - Display the current information in the database"; cout<<"nQ - Quit"; cout<<"nn>> "; }// End of DisplayMenu // ============================================================================= // DisplayData // displays the current contents in the array. If there is nothing in the array // the program promts a message to the user // ============================================================================= void DisplayData(char**artist, char**CDTitle, double*salesPrice, char**genre, double*discountPercent, double*subTotal, double*salesTax, double*grandTotal, int* numItems) { double* totSalePrice = new double(0); double* totSalesTax = new double(0); double* totgrandTotal = new double(0); // variables which will get the current date time_t t = time(0); // get current CPU time struct tm * now = localtime(& t); // if array is empty, display message if(*numItems ==0) { cout<<"nThe database is currently empty!n"; } else { // displays the company header to the user cout<<setfill(' '); cout << "nttttMy Programming Notes Record Company" << "ntttt Sales Report for "<<now->tm_mon + 1<<"/"<<now->tm_mday<<"/"<<now->tm_year + 1900<<"nn"; // displays the categories which will be shown to the user cout <<setw(1)<<right<<"Artist"<<setw(13)<<"Title"<<setw(13)<<"SalesPrice" <<setw(13)<<"Genre"<<setw(20)<<"DiscountRate"<<setw(13)<<"SubTotal" <<setw(13)<<"SalesTax"<<setw(13)<<"GrandTotal"; // displays the data which is currently inside the array's cout<<fixed<<setprecision(2); for(int* index = new int(0); *index < *numItems; ++*index) { cout << endl; cout <<setw(1)<<right<<artist[*index]<<setw(15)<<CDTitle[*index] <<setw(13)<<salesPrice[*index]<<setw(15)<<genre[*index]<<setw(13) <<discountPercent[*index]*100<<"%"<<setw(15)<<subTotal[*index]<<setw(16) <<salesTax[*index]<<setw(13)<<grandTotal[*index]; } // finds the total prices for the entire list of CD's for(int* index = new int(0); *index < *numItems; ++*index) { *totSalePrice+= subTotal[*index]; *totSalesTax+= salesTax[*index]; *totgrandTotal+= grandTotal[*index]; } // creates a line separator cout<<setfill('-'); cout<<endl<<endl<<left<<setw(52)<<""<<right<<setw(52)<<""<<endl; // displays the total to the user cout<< "Total ("<<*numItems<<" transactions)ttttttt" <<*totSalePrice<<"tt"<<*totSalesTax<<"t"<<*totgrandTotal<<endl; } }// End of DisplayData // ============================================================================= // SortData // sorts all the data which is currently present in the arrays via bubble sort // this function does not display any data to the user // ============================================================================= void SortData(char**artist, char**CDTitle, double*salesPrice, char**genre,double*discountPercent, double*subTotal, double*salesTax, double*grandTotal, int* numItems) { // bool which will tell us if sorting is complete bool sorted = false; // temporary variables for sorting purposes only char* tempArtist = new char[20]; char* tempCDTitle= new char[20]; char* tempGenre= new char[20]; double* tempListPrice= new double[20]; double* tempDiscountPercent = new double[20]; double* tempsubTotal = new double[20]; double* tempTaxAmt = new double[20]; double* tempgrandTotal = new double[20]; // this is the bubble sort // which sorts the entries by artist in ascending order while (sorted==false) { sorted=true; for(int* index= new int(0); *index < *numItems-1; ++*index) { // checks the artist to see if they are in the correct order if (strcmp(artist[*index],artist[*index+1]) > 0) { // swaps artist places strcpy(tempArtist, artist[*index]); strcpy(artist[*index], artist[*index+1]); strcpy(artist[*index+1], tempArtist); // swaps CD title strcpy(tempCDTitle, CDTitle[*index]); strcpy(CDTitle[*index], CDTitle[*index+1]); strcpy(CDTitle[*index+1], tempCDTitle); // swaps music genre strcpy(tempGenre, genre[*index]); strcpy(genre[*index], genre[*index+1]); strcpy(genre[*index+1], tempGenre); // swaps the CD price *tempgrandTotal = grandTotal[*index]; grandTotal[*index] = grandTotal[*index+1]; grandTotal[*index+1] = *tempgrandTotal; // swaps the tax amount *tempTaxAmt = salesTax[*index]; salesTax[*index] = salesTax[*index+1]; salesTax[*index+1] = *tempTaxAmt; // swaps the sales price *tempsubTotal = subTotal[*index]; subTotal[*index] = subTotal[*index+1]; subTotal[*index+1] = *tempsubTotal; // swaps the discount percent *tempDiscountPercent = discountPercent[*index]; discountPercent[*index] = discountPercent[*index+1]; discountPercent[*index+1] = *tempDiscountPercent; // swaps the list price *tempListPrice = salesPrice[*index]; salesPrice[*index] = salesPrice[*index+1]; salesPrice[*index+1] = *tempListPrice; // sets the 'sorted' variable to false sorted=false; }// end of if statement }// end for loop }// end while loop }// End of SortData // ============================================================================= // GetGrandTotal // calculates the grand total for the current transaction // ============================================================================= void GetGrandTotal(double* subTotal,double* salesTax,int* numItems,double* grandTotal) { grandTotal[*numItems]= (subTotal[*numItems])+(salesTax[*numItems]); }// End of GetgrandTotal // ============================================================================= // GetTaxAmount // calculates the sales tax for the current transaction // ============================================================================= void GetTaxAmount(double* salesPrice, double* taxRate, int*numItems,double* salesTax) { salesTax[*numItems] = (salesPrice[*numItems])* (taxRate[*numItems]); }// End of GetTaxAmount // ============================================================================= // GetSubTotal // gets the subtotal for the current transaction // ============================================================================= void GetSubTotal(double* salesPrice, double* discountRate, int* numItems,double* subTotal) { subTotal[*numItems] = (salesPrice[*numItems]) - (discountRate[*numItems]); }// End of GetsubTotal // ============================================================================= // GetDiscountRate // gets the discount rate for the currently selected CD // ============================================================================= void GetDiscountRate(double* salesPrice,char** musicGenre, char** genre,int* numItems, double* &discountPercent, double* discountRate) { // comapres the user inputted current genre to the pre-defined // genres as defined in the main function, then assigns a // discount to the current CD if(strcmp(genre[*numItems],musicGenre[0]) == 0) // if music genre is Classical {discountPercent[*numItems] = discounts[0];} else if(strcmp(genre[*numItems],musicGenre[1]) == 0) // if music genre is Country {discountPercent[*numItems] = discounts[1];} else if(strcmp(genre[*numItems],musicGenre[2]) == 0) // if music genre is International {discountPercent[*numItems] = discounts[2];} else if(strcmp(genre[*numItems],musicGenre[3]) == 0) // if music genre is Jazz {discountPercent[*numItems] = discounts[3];} else if(strcmp(genre[*numItems],musicGenre[4]) == 0) // if music genre is Pop {discountPercent[*numItems] = discounts[4];} else if(strcmp(genre[*numItems],musicGenre[5]) == 0) // if music genre is Rock {discountPercent[*numItems] = discounts[5];} else if(strcmp(genre[*numItems],musicGenre[6]) == 0) // if music genre is Rap {discountPercent[*numItems] = discounts[6];} else{discountPercent[*numItems] = discounts[4];} // if music genre is not any of these ^, then there is no discount // assign the discount rate to the current CD discountRate[*numItems] = (discountPercent[*numItems]) * (salesPrice[*numItems]); }// End of GetDiscountRate // ============================================================================= // GetCDInfo // obtains the CD information from the user // ============================================================================= void GetCDInfo(char** &artist, char** &CDTitle, char** &genre, double* &salesPrice, double* &taxRate, int* numItems) { cin.ignore(); cout << "nEnter the name of the artist: "; cin.getline(artist[*numItems],50, 'n'); cout << "nEnter the title of the CD: "; cin.getline(CDTitle[*numItems],50, 'n'); cout << "nEnter the genre: "; cin.getline(genre[*numItems], 20); cout << "nEnter the sales price $"; cin >> salesPrice[*numItems]; cout << "nEnter the sales tax: "; cin >> taxRate[*numItems]; }// End of GetInfo // ============================================================================= // GetDiscounts // returns the discount rate for the selected genre // ============================================================================= double* GetDiscounts() { double* temp = new double[7]; temp[0] = .09; // discount rate for Classical temp[1] = .03; // discount rate for Country temp[2] = .11; // discount rate for International temp[3] = .18; // discount rate for Jazz temp[4] = .00; // discount rate for Pop temp[5] = .10; // discount rate for Rock temp[6] = .07; // discount rate for Rap return temp; }// 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
Welcome to the CD Management System!
From the following menu, select an optionE - Enter new CD information into the database
D - Display the current information in the database
Q - Quit>> e
Enter the name of the artist: Nm8
Enter the title of the CD: CD8
Enter the genre: Rock
Enter the sales price $12.99
Enter the sales tax: .098
Do you want to enter more CD's? (y/n): y------------------------------------------------------------
Welcome to the CD Management System!
From the following menu, select an optionE - Enter new CD information into the database
D - Display the current information in the database
Q - Quit>> e
Enter the name of the artist: Nm7
Enter the title of the CD: CD7
Enter the genre: Country
Enter the sales price $10.99
Enter the sales tax: .078
Do you want to enter more CD's? (y/n): y------------------------------------------------------------
Welcome to the CD Management System!
From the following menu, select an optionE - Enter new CD information into the database
D - Display the current information in the database
Q - Quit>> e
Enter the name of the artist: Nm6
Enter the title of the CD: CD6
Enter the genre: Pop
Enter the sales price $11.50
Enter the sales tax: .067
Do you want to enter more CD's? (y/n): y------------------------------------------------------------
Welcome to the CD Management System!
From the following menu, select an optionE - Enter new CD information into the database
D - Display the current information in the database
Q - Quit>> e
Enter the name of the artist: Nm5
Enter the title of the CD: CD5
Enter the genre: Jazz
Enter the sales price $12.24
Enter the sales tax: .045
Do you want to enter more CD's? (y/n): y------------------------------------------------------------
Welcome to the CD Management System!
From the following menu, select an optionE - Enter new CD information into the database
D - Display the current information in the database
Q - Quit>> e
Enter the name of the artist: Nm4
Enter the title of the CD: CD4
Enter the genre: Other
Enter the sales price $12.99
Enter the sales tax: .094
Do you want to enter more CD's? (y/n): y------------------------------------------------------------
Welcome to the CD Management System!
From the following menu, select an optionE - Enter new CD information into the database
D - Display the current information in the database
Q - Quit>> e
Enter the name of the artist: Nm3
Enter the title of the CD: CD3
Enter the genre: Classical
Enter the sales price $11.45
Enter the sales tax: .078
Do you want to enter more CD's? (y/n): y------------------------------------------------------------
Welcome to the CD Management System!
From the following menu, select an optionE - Enter new CD information into the database
D - Display the current information in the database
Q - Quit>> e
Enter the name of the artist: Nm2
Enter the title of the CD: CD2
Enter the genre: International
Enter the sales price $10.99
Enter the sales tax: .093
Do you want to enter more CD's? (y/n): y------------------------------------------------------------
Welcome to the CD Management System!
From the following menu, select an optionE - Enter new CD information into the database
D - Display the current information in the database
Q - Quit>> e
Enter the name of the artist: Nm1
Enter the title of the CD: CD1
Enter the genre: Rap
Enter the sales price $12.99
Enter the sales tax: .0975
Do you want to enter more CD's? (y/n): n
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
My Programming Notes Record Company Sales Report for 2/9/2012 Artist Title SalesPrice Genre DiscountRate SubTotal SalesTax GrandTotal Nm1 CD1 12.99 Rap 7.00% 12.08 1.27 13.35 Nm2 CD2 10.99 International 11.00% 9.78 1.02 10.80 Nm3 CD3 11.45 Classical 9.00% 10.42 0.89 11.31 Nm4 CD4 12.99 Other 0.00% 12.99 1.22 14.21 Nm5 CD5 12.24 Jazz 18.00% 10.04 0.55 10.59 Nm6 CD6 11.50 Pop 0.00% 11.50 0.77 12.27 Nm7 CD7 10.99 Country 3.00% 10.66 0.86 11.52 Nm8 CD8 12.99 Rock 10.00% 11.69 1.27 12.96 -------------------------------------------------------------------------------------------------------- Total (8 transactions) 89.16 7.85 97.01 |
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 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++ || 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