C++ while loop nested if statment - c++

Hi I am having some trouble getting the correct smallest value and the correct largest value . I know it has to do with the while loop. the rest of the program works great. I found the correct average , sum and number of integers
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream inputfile;
char choice;
int NumberOfIntegers = 0,
SumOfIntegers = 0,
Average = 0 ,
LargestValue,
SmallestValue,
integer;
inputfile.open("random.txt");
if(!inputfile)
{
cout << "the file could not be open" << endl;
}
inputfile >> integer;
//initialize smallest and largest
SmallestValue = integer;
LargestValue = integer;
while(inputfile)
{
NumberOfIntegers++;
SumOfIntegers = SumOfIntegers + integer;
inputfile >> integer;
if( integer >> LargestValue || integer << SmallestValue)
{
if ( integer >> LargestValue)
LargestValue = integer;
else
SmallestValue = integer;
}
}
if(NumberOfIntegers > 0 )
{
Average = SumOfIntegers / NumberOfIntegers;
}
do
{
//Display Menu
cout << "Make a selection from the list" << endl;
cout << "A. Get the largest Value" << endl;
cout << "B. Get the smallest Value" << endl;
cout << "C. Get the sum of the values" << endl;
cout << "D. Get the average of the values" << endl;
cout << "E. Get the number of values entered" << endl;
cout << "F. End this program" << endl << endl;
cout << "Enter your choice --> ";
cin >> choice;
cout << endl;
switch (choice)
{
case 'a':
case 'A': cout << "The largest value is " << LargestValue << endl;
break;
case 'b':
case 'B': cout << "The smallest value is " << SmallestValue << endl;
break;
case 'c':
case 'C': cout << "The sum of the values entered is " << SumOfIntegers << endl;
break;
case 'd':
case 'D': cout << "The average of the values entered is " << Average << endl;
break;
case 'e':
case 'E': cout << "The number of values entered is " << NumberOfIntegers << endl;
break;
case 'f':
case 'F': cout << "Program is now ending" << endl;
return 1;
break;
default:
cout << choice << " is an invalid value. " << endl;
}
cout << endl;
} while( choice != 'f' || choice != 'F');
return 0;
}

integer >> LargestValue
Presumably that should be integer > LargestValue. >> is a shift operation, not a comparison. The same applies to <<.

You should also make sure you initialize LargestValue to something small and SmallestValue to something large. Otherwise you may miss outliers in your data.

Make your 'largest' & 'smallest' logic blocks separate -- there's no reason or correctness in joining them.
Note that for a list with only one item, that value will be both smallest and largest. Not only is it more complicated, it is incorrect to make these conditions mutually exclusive.
Use better names for your variables. Use "item" or "value" for what you are currently reading, everything is an integer so that is effectively meaningless. I prefer a lowercase first letter for variables.. been working in Java for a while :)
Avoid declaring variables before/ or outside of where they have meaningful value too, where possible.
int value;
inputfile >> value;
if (value > largestValue) {
largestValue = value;
}
if (value > smallestValue) {
smallestValue = value;
}
Also, you need to either detect 'first' or initialize smallest/largest to +/- MaxInt to ensure that the first value will be taken up.

Related

There is a problem in this C++ program (Decimal to Bin,Oct and Hex converter)

What I am trying to do is, create a program which converts Decimal values into other Number Systems(Binary, Octal and Hexa-Decimal) and shows the original Decimal value as-well-as the converted value.
It runs fine in first run but when the outer for loop runs the program again, the previous values which were printed by inner for loop are also printed right after its output in the next run. Any Suggestions?
Try running it, and see it yourself...
source code:-
#include <iostream>
using namespace std;
int main()
{
cout << "This program will help in Decimal to other radix conversion :-" << endl;
const int i = 10;
//Declaring array to store remainder values...
int RemArray [i] = {0};
//Declaring variable to use it as index of RemArray[]...
short int R=0;
char Exit = '\0';
//To iterate the whole program...
for (;;)
{
cout << "Enter Decimal digit: ";
long long int Decimal = 0;
cin >> Decimal;
long long int TempDecimal = Decimal;
cout << "Enter Desired Radix: ";
int Radix = 0;
cin >> Radix;
long long int Quotient = 1;
long long int Remainder = 0;
cout << endl;
while (Quotient != 0)
{
//Formula for conversion...
Quotient = Decimal / Radix;
Remainder = Decimal % Radix;
cout << "Quotient: " << Quotient << " <-> " << "Remainder: ";
//Using switch case so that hexa-decimal values could also be printed...
switch (Remainder)
{
case 10:
cout << "A" << endl;
break;
case 11:
cout << "B" << endl;
break;
case 12:
cout << "C" << endl;
break;
case 13:
cout << "D" << endl;
break;
case 14:
cout << "E" << endl;
break;
case 15:
cout << "F" << endl;
break;
default:
cout << Remainder << endl;
break;
}
Decimal = Quotient;
//Using array to store remainder values...to print them all together
RemArray [R] = Remainder;
R++;
}
cout << endl;
cout << "Therefore, " << TempDecimal << " = ";
/*Output the result...But When the program runs again, values obtained here remains
on the screen and prints them too on the next run of this loop...*/
for (int NewR = R-1, z=0; (NewR >= 0) && (z < R); NewR--,z++)
{
switch (RemArray [NewR])
{
case 10:
cout << "A";
break;
case 11:
cout << "B";
break;
case 12:
cout << "C";
break;
case 13:
cout << "D";
break;
case 14:
cout << "E";
break;
case 15:
cout << "F";
break;
default:
cout << RemArray [NewR];
break;
}
}
//Asking user to iterate the program again...
cout << endl << "Want to convert another digit (y/n): ";
cin >> Exit;
cout << endl;
if (Exit == 'n')
{
break;
}
}
cout << "GoodBye !!!" << endl;
return 0;
}

I can't print a vector inside a switch case

This is my first question here. I am just beginning to learn C++ and I am stuck at this exercise:
Your program should display a menu options to the user as follows:
P--Print the vector
A--Add a number
M--Display mean of the number
S--Display the smallest number
L--Display the largest number
Q--Quit
Enter your choice:
Basically, I need to do a menu for these operations. I got stuck at the part of printing the vector. I already tried to use (for auto:....) and also tried with the normal index (int i = 0...), but the contents in the vector don't appear, only the message "This is your list of numbers:". I also tried to create a function to make sure that the user was inputting an integer in the A case, but did not know how to do it :(
This is my code:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
bool control_end = false;
do
{
cout << "Please enter your desired function within the menu: " << endl;
cout << endl;
cout << "P--Print list of numbers" << endl;
cout << "A--Add a number"<< endl;
cout << "M--Display mean of the number"<< endl;
cout << "S--Display the smallest number"<< endl;
cout << "L--Display the largest number"<< endl;
cout << "Q--Quit "<< endl;
cout << endl;
cout << "Enter your choice: ";
char letra{};
cin >> letra;
vector<int> vector{};
switch(letra)
{
case 'A':
case 'a':
{
cout << "Please enter the value (integer) to be added to vector: ";
int value_add;
cin >> value_add;
cout << endl;
vector.push_back(value_add);
//(later do it) create a function to ensure that the value is an integer
break;
}
case 'p':
case 'P':
{
cout << "This is your list of numbers: \n";
for (unsigned int i=0 ;i < vector.size(); i++)
cout << vector[i] << " ";
break;
}
case 'm':
case 'M':
cout << "test M";
break;
case 's':
case 'S':
cout << "test S";
break;
case 'L':
case 'l':
cout << "test L";
break;
case 'q':
case 'Q':
cout << "Thank you for using the program" << endl;
control_end = true;
break;
default:
cout << "Invalid char. " << endl;
cout << endl;
break;
}
for(auto vec: vector)
cout << vec << endl;
}
while (control_end !=true);
return 0;
}
You created the variable vector inside your loop, so at the end of the loop the variable get destroyed and a new empty one is created on the next iteration. So, if you want your variable to retain values between loop iterations, you should declare it outside of the loop scope, the same way you did with the variable control_end.

input validation for choosing an item with a char, getting errors with cin.fail

cin is really difficult for me to understand with c++.
I want to choose an item on the menu but I want it to be clean, however I am running into issues with cin.fail.
I realize cin.fail checks the datatype so I should be clear when it comes to other data types.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int number;// define an integer variable called number
float cost;// a floating point variable called cost,
char beverage;// and a character variable called beverage
bool validBeverage;
cout << fixed << showpoint << setprecision(2);
do
{
cout << endl << endl;
cout << "Hot Beverage Menu" << endl << endl;
cout << "A: Coffee $1.00" << endl;
cout << "B: Tea $ .75" << endl;
cout << "C: Hot Chocolate $1.25" << endl;
cout << "D: Cappuccino $2.50" << endl <<endl << endl;
cout << "Enter the beverage A,B,C, or D you desire" << endl;
cout << "Enter E to exit the program" << endl << endl;
do
{
cin >> beverage;// Fill in the code to read in beverage
if (cin.fail)
{
cout << "You have entered an invalid value." << endl
<< "Please enter the letter corresponding to the menu." << endl;
}
} while (cin.fail);
switch(beverage)
{
case 'a': validBeverage = true;
case 'A': validBeverage = true;
case 'b': validBeverage = true;
case 'B': validBeverage = true;
case 'c': validBeverage = true;
case 'C': validBeverage = true;
case 'd': validBeverage = true;
case 'D': validBeverage = true;
break;
default: validBeverage = false;
}// end switch beverage
if (validBeverage == true)
{
do
{
cout << "How many cups would you like?" << endl;
// Fill in the code to read in number
cin >> number;
if (cin.fail() || number <= 0)
{
cout << "You have entered an invalid value." << endl <<
"Please enter an integer greater than 0." << endl;`enter code here`
}
} while (cin.fail() || number <= 0);
}
switch (beverage)// Fill in the code to begin a switch
statement that is controlled by beverage
{
case 'a': (float)cost = number * 1.0;
cout << "The total cost is $ " << cost << endl;
break;
case 'A': (float)cost = number * 1.0;
cout << "The total cost is $ " << cost << endl;
break;
case 'b': (float)cost = number * 0.75;// Fill in the
code to give the case for tea ( $0.75 a cup)
cout << "The total cost is $ " << cost << endl;
break;
case 'B': (float) cost = number * 0.75;// Fill in the
code to give the case for hot chocolate ($1.25 a cup)
cout << "The total cost is $ " << cost << endl;
break;
case 'c': (float)cost = number * 1.25;
cout << "The total cost is $ " << cost << endl;
break;
case 'C': (float)cost = number * 1.25;
cout << "The total cost is $ " << cost << endl;
break;
case 'd': (float)cost = number * 2.50;// Fill in the
code to give the case for cappuccino ($2.50 a cup)
cout << "The total cost is $ " << cost << endl;
break;
case 'D': (float)cost = number * 2.50;// Fill in the
code to give the case for cappuccino ($2.50 a cup)
cout << "The total cost is $ " << cost << endl;
break;
case 'e':
cout << "Please come again." << endl;
break;
case 'E':
cout << " Please come again." << endl;
break;
default:cout << "Invalid Selection."; // Fill in the
code to write a message indicating an invalid selection.
cout << " Try again please" << endl;
}
}while (beverage != 'e' || beverage != 'E'); // Fill in the code to
finish the do-while statement with the condition that beverage does not
equal E or e.
// Fill in the appropriate return statement
return 0;
}
Try using: if(!cin) which checks for data type on input.

Switch Statement - Nested Functions - C++

I want to have a function called "userPrompt" andit ask for the user to enter a value for integer named "choose" so after that I would be able to use switch statement.
But It dosen't work it says: "choose" undeclared.
I suppose it would start the main function first,and inside of it the first command would be initializing the userPrompt func. then thanks to userPrompt I would have a choose value so that the switch would work.
So what is the problem with this code?
How can I use nested functions?(I hope it is called like that)
Is my code's order wrong?
Any help will be appreciated.
userPrompt(){
int choose;
cout << " Please Choose An Option : " << endl;
cout << " Type 1 to Add new grades : " << endl;
cout << " Type 2 to Calculate the average grades : " << endl;
cout << " Type 3 to Calculate the total grades : " << endl;
cout << " Type 4 to Exit : " << endl;
cin >> choose;
}
int main()
{
userPrompt();
switch(choose){
case 1
getGrade();
userPrompt();
break;
case 2
int average;
getGrade();
average = total/counter;
cout << average;
break;
case 3
getGrade();
cout << total;
break;
case 4
cout << "Thanks for Trying" << endl;
return 0;
system("pause");
break;
default
cout << "Please Choose A Valid Option ! : " << endl;
validOption();
}
}
C++ uses "scope" which sort of translates into the "visibility" of variables. The "choose" variable of your userPrompt() function is only "visible" (within reach) inside the scope of the userPrompt() function.
So you could declare the userPrompt() function as
int userPrompt() // Returns the user choice
{
... // your existing code here
return choose;
}
Then inside main() you would do something like:
int main()
{
int choice = userPrompt();
switch(choice)
...
You forgot to put colon in your case and also you need to return choose.
case 1:
Try this:
int userPrompt(){
int choose;
cout << " Please Choose An Option : " << endl;
cout << " Type 1 to Add new grades : " << endl;
cout << " Type 2 to Calculate the average grades : " << endl;
cout << " Type 3 to Calculate the total grades : " << endl;
cout << " Type 4 to Exit : " << endl;
cin >> choose;
return choose;
}
int main()
{
int choose = userPrompt();
switch(choose){
case 1:
getGrade();
userPrompt();
break;
case 2:
int average;
getGrade();
average = total/counter;
cout << average;
break;
case 3:
getGrade();
cout << total;
break;
case 4:
cout << "Thanks for Trying" << endl;
return 0;
system("pause");
break;
default:
cout << "Please Choose A Valid Option ! : " << endl;
validOption();
}
}
change the code to this :
int userPrompt(){ //--> changed into a function returning the choice
int choose;
cout << " Please Choose An Option : " << endl;
cout << " Type 1 to Add new grades : " << endl;
cout << " Type 2 to Calculate the average grades : " << endl;
cout << " Type 3 to Calculate the total grades : " << endl;
cout << " Type 4 to Exit : " << endl;
cin >> choose;
return choose;
}
int main()
{
//--> declare choose in main and assign a value using the function call
int choose = userPrompt();
switch(choose){
case 1:
getGrade();
userPrompt();
break;
case 2:
int average;
getGrade();
average = total/counter;
cout << average;
break;
case 3:
getGrade();
cout << total;
break;
case 4:
cout << "Thanks for Trying" << endl;
return 0;
system("pause");
break;
default
cout << "Please Choose A Valid Option ! : " << endl;
validOption();
}
}
Simple mistake. put colon in cases case 1: like that
`intialize the choose first and try it.
int choose = o;
In C++ every function has a return type. This means that it will return something or return void (i.e, return nothing). In your program userPrompt has no return type neither void or any other return type hence this part is the first error in your program.
The next error is that after every case label in the switch statement that label must be followed by a colon ':'

C++ while loop reading input

I submitted this program and it works perfectly, but my teacher says that there is something wrong with my while loop even though I am getting the correct answers. Any tips or help?
What happens in the while loop when the end of file is reached and the read on line 43 becomes invalid? The way your program is structured you do not see the problem, but it is there. Should restructure the while loop to account for this.
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream inputfile;
char choice;
int NumberOfIntegers = 0,
SumOfIntegers = 0,
Average = 0 ,
LargestValue,
SmallestValue,
integer;
inputfile.open("random.txt");
if(!inputfile)
{
cout << "the file could not be open" << endl;
}
inputfile >> integer;
//initialize smallest and largest
SmallestValue = integer;
LargestValue = integer;
while(inputfile)
{
NumberOfIntegers++;
SumOfIntegers = SumOfIntegers + integer;
inputfile >> integer;
if( integer > LargestValue || integer < SmallestValue)
{
if ( integer > LargestValue)
LargestValue = integer;
else
SmallestValue = integer;
}
}
if(NumberOfIntegers > 0 )
{
Average = SumOfIntegers / NumberOfIntegers;
}
//closing input file
inputfile.close();
do
{
//Display Menu
cout << "Make a selection from the list" << endl;
cout << "A. Get the largest Value" << endl;
cout << "B. Get the smallest Value" << endl;
cout << "C. Get the sum of the values" << endl;
cout << "D. Get the average of the values" << endl;
cout << "E. Get the number of values entered" << endl;
cout << "F. End this program" << endl << endl;
cout << "Enter your choice --> ";
cin >> choice;
cout << endl;
switch (choice)
{
case 'a':
case 'A': cout << "The largest value is " << LargestValue << endl;
break;
case 'b':
case 'B': cout << "The smallest value is " << SmallestValue << endl;
break;
case 'c':
case 'C': cout << "The sum of the values entered is " << SumOfIntegers << endl;
break;
case 'd':
case 'D': cout << "The average of the values entered is " << Average << endl;
break;
case 'e':
case 'E': cout << "The number of values entered is " << NumberOfIntegers << endl;
break;
case 'f':
case 'F': cout << "Program ending" << endl << endl;
cin.ignore();
cout << "\n\nPress Enter to end --> ";
cin.ignore();
return 0;
default:
cout << choice << " is an invalid value. " << endl;
}
cout << endl;
} while( choice != 'f' || choice != 'F');
return 0;
}
The "issue" I see is that you do not check the bool value of the stream after you read and before you process. To do this, you should put the read as the condition to the while loop.
if( ! inputfile >> integer )
{
// error code (no integer in file)
exit(0);
}
LargestValue = integer;
SmallestValue = integer;
NumberOfIntegers++;
SumOfIntegers = SumOfIntegers + integer;
while( inputfile >> integer )
{
NumberOfIntegers++;
SumOfIntegers = SumOfIntegers + integer;
//inputfile >> integer;
if( integer > LargestValue || integer < SmallestValue)
{
if ( integer > LargestValue)
LargestValue = integer;
else
SmallestValue = integer;
}
}
In this scenario, the result should be the same with your program because if the inputfile >> integer failed, I believe integer keeps the same value as before so it would not effect LargestValue or SmallestValue. Then you check the stream so NumberOfIntegers and SumOfIntegers won't be updated, which is correct. The only time your program would give undefined results (for LargestValue and SmallestValue) is if the file doesn't start with an integer and simply by checking the first read and handling it appropriately this will be fixed.