Why doesn't this code work correctly? (C++) - c++

If I input this code:
#include<iostream>
using namespace std;
int main ()
{
int input, qty, min, max;
bool validity = 1;
cout << "How many integers would you like to enter? \n";
cin >> qty;
if (qty <= 0)
cout << "Please enter a positive number\n";
else
{
cout << "Please enter " << qty << " integers:" << endl;
for (int x=0; x < qty; x++)
{
cin >> input;
if (input > max)
max = input;
if (input < min)
min = input;
}
}
if (validity)
{
cout << "Minimum: " << min << endl;
cout << "Maximum: " << max << endl;
}
return 0;
}
It works as expected.
But if I have this:
#include<iostream>
using namespace std;
int main ()
{
int input, qty, min, max;
bool validity = 1;
cout << "How many integers would you like to enter? \n";
cin >> qty;
if (qty <= 0)
cout << "Please enter a positive number\n";
else
{
cout << "Please enter " << qty << " integers:" << endl;
for (int x=0; x < qty; x++)
{
cin >> input;
if (input > max)
max = input;
if (input < min)
min = input;
}
}
if (max > 2147483646)
{
cout << "Please enter a valid value for integers." << endl;
validity = 0;
}
if (min < -2147483647)
{
cout << "Please enter a valid value for integers." << endl;
validity = 0;
}
if (validity)
{
cout << "Minimum: " << min << endl;
cout << "Maximum: " << max << endl;
}
return 0;
}
It gives me erroneous values.
What am I doing wrong? Any help is greatly appreciated. (I'm a noob btw). Adding a little text here so that I can post this question.............................

max and min are uninitialized. In C++, this means the values can be anything at all, unless in say Java where primitives are auto-initialized to 0.
One way to fix is to set a first flag, and set max and min the the first value entered.
bool first = true;
for (int x=0; x < qty; x++)
{
cin >> input;
if( first )
{
max = input;
min = input;
first = false;
}
if (input > max)
max = input;
if (input < min)
min = input;
}
Here's what I mean by uninitialized. When starting up, min and max can be anything. Anything at all. Try it by printing out the value of min and max before your loop. It should (could) be different every time you run the program. Basically the value depends on what data was in that memory location the last time it was used.
So the if( input > max) is checking to see if input is greater than some random number between -2billion and 2 billion. (not useful). The first flag I put in there initializes min/max in the first iteration of the for loop, or the first value entered by the user, which is guaranteed to be both the min and the max of the entered value since it's the only entered value.

Related

C++ : Making a do while loop repeat

I'm very sorry for the super newbie question, but I cannot for the life of me understand how to make a do while loop repeat. I changed a while loop into a do while loop and now I don't know how to get it to ask "would you like to repeat Y or N?" any explanation?
I've read various posts that accomplish a do while loop repeat, but they don't make sense to me.
Am I essentially going to wrap this code into another do while loop? Do I move the boolean expression to before the while?
#include <iostream>
using namespace std;
int main(void)
{
int x;
int count = 0;
int N;
double sum = 0;
double average;
char ans;
{
cout << "Enter number of values, N, to be read in <Enter>:" << endl;
cin >> N;
do
{
cout << "\n Enter a grade <Enter>: ";
cin >> x;
sum = sum + x;
count++; //
} while (count < N);
if (N == 0)
cout << "You have entered 0 numbers. No average will be computed. Bye! \n";
else {
average = average = sum / N;
cout << "The average of these " << N << " grades is " << average << endl;
}
cout << "Would you like to enter more values to calculate your grade average?\n";
system("pause");
return 0;
}
}
can do this:
char repeat='y';
cout << "Enter number of values, N, to be read in <Enter>:" << endl;
cin >> N;
do
{
for(int i=0;i<n;i++){
cout << "\n Enter a grade <Enter>: ";
cin >> x;
sum = sum + x;
count++; //
}
if (N == 0)
cout << "You have entered 0 numbers. No average will be computed. Bye! \n";
else {
average = average = sum / N;
cout << "The average of these " << N << " grades is " << average << endl;
}
cout << "Would you like to enter more values to calculate your grade average?\n";
cin>>repeat;
}while(repeat=='y');
May be this is what you need, with char YorN you are considering if to continue or break the inner do-while.
#include <iostream>
using namespace std;
int main(void)
{
int x;
int count = 0;
int N;
double sum = 0;
double average;
char ans;
char YorN;
do{
cout << "Enter number of values, N, to be read in <Enter>:" << endl;
cin >> N;
do
{
cout << "\n Enter a grade <Enter>: ";
cin >> x;
sum = sum + x;
count++; //
} while (count < N);
if (N == 0)
cout << "You have entered 0 numbers. No average will be computed. Bye! \n";
else {
average = average = sum / N;
cout << "The average of these " << N << " grades is " << average << endl;
}
cout << "Would you like to enter more values to calculate your grade average?\n";
cin>>YorN;
} while (YorN=='Y');
return 0;
}
Although there are a ton of ways to do it better, this code allows me to explain what is happening. Do-While loops are definitely pretty tricky. However, just remember that a do-while loop is designed to run at least once.
In the case of our code, we set up if statements to test against running code where it is not appropriate.
Take a look at how the very first if statement is N > 0, the if-statement does execute, please do not forget that. Once more for emphasis, the if statement DOES execute, it just results in false.
With that being said, you use a do-while loop when you want your code block to execute AT LEAST once. Notice how our while statement has two things we're testing for, one, is the answer 'Y' from the user to continue, and if it is, is the newly inputted N value greater than 0?
You might be wondering if the inner most if statement ever executes at least once, well the answer is it depends on the previous if statement result if(N > 0) and if(count == N && N != 0) both execute once every single time the while loop stays true. However that nested if depends on it's parent result.
I hope this cleared some things up for you on do-while loops.
#include <iostream>
using namespace std;
int main(void)
{
int x;
int count = 0;
int N;
double sum = 0;
double average;
char ans = 'Y';
cout << "Enter number of values, N, to be read in <Enter>:" << endl;
cin >> N;
do
{
if(N > 0){ //THIS IF STATEMENT WILL ALWAYS RUN AT LEAST ONCE
cout << "\n Enter a grade <Enter>: ";
cin >> x;
sum = sum + x;
count++;
}
if(count == N && N != 0) {//THIS IF STATEMENT WILL ALSO ALWAYS RUN AT LEAST ONCE
average = average = sum / N;
cout << "The average of these " << N << " grades is " << average << endl;
cout << "Would you like to enter more values to calculate your grade average?\n";
cin>>ans;
if(ans == 'Y') {//This one depends on it's parents result.
x = 0;
N = 0;
sum = 0;
count = 0;
cout << "Enter number of values, N, to be read in <Enter>:" << endl;
cin >> N;
}
}
} while (ans == 'Y' && N != 0);
if (N == 0)
cout << "You have entered 0 numbers. No average will be computed. Bye! \n";
system("pause");
return 0;
}

Program that checks whether numbers are already in an array

This program is supposed to accept values from the keyboard, and require that the user re-enter the value for the employee's id number. However it keeps outputting "Invalid variable" even if I enter a correct value. It needs to only output that if the value is already been entered. For example
if I enter "3453" as the id number it will still output "Invalid Variable" even if I have not entered that number before.
#include <iostream>
using namespace std;
struct Employee
{
int idNum;
double payRate;
char firstName, lastName;
};
int main()
{
int error;
const int SIZE = 5;
Employee employee[SIZE];
for (int k = 0; k < SIZE; ++k)
{
employee[k].idNum = 0;
employee[k].payRate = 0;
}
for (int count = 0; count < SIZE; ++count)
{
error = 0;
cout << "Enter the employee's id number " << endl;
cin >> employee[count].idNum;
for (int i = 0; i < SIZE; ++i)
{
if (employee[i].idNum == employee[count].idNum)
error = 1;
}
while (error == 1)
{
cout << "Invalid entry. Please enter a new id number " << endl;
cin >> employee[count].idNum;
for (int i = 0; i < SIZE; ++i)
{
error = 0;
if (employee[i].idNum == employee[count].idNum)
error = 1;
}
}
cout << "Enter the employee's pay rate " << endl;
cin >> employee[count].payRate;
cout << "Enter the employee's first name " << endl;
cin >> employee[count].firstName;
cout << "Enter the employee's last name " << endl;
cin >> employee[count].lastName;
int choice;
cout << "Enter 1 to search for an employee by id number, enter 2 to search by last name, and enter 3 to search by pay "
<< endl;
cin >> choice;
}
int choice;
cout << "Enter 1 to search for an employee by id number, enter 2 to search by last name, and enter 3 to search by pay "
<< endl;
cin >> choice;
if (choice == 1)
{
int idNumC;
cout << "Enter an id number ";
cin >> idNumC;
for (int count = 0; count < SIZE; ++count)
{
if (employee[count].idNum == idNumC)
cout << employee[count].idNum;
}
}
if (choice == 2)
{
char name;
cout << "Enter the employee's last name " << endl;
cin >> name;
for (int count = 0; count < SIZE; ++count)
{
if (employee[count].lastName == name)
cout << "ID number: " << employee[count].idNum
<< " First name: " << employee[count].firstName
<< " Last Name: " << employee[count].lastName
<< " Hourly Pay: " << endl;
}
}
if (choice == 3)
{
int name;
cout << "Enter the employee's last name " << endl;
cin >> name;
for (int count = 0; count < SIZE; ++count)
{
if (employee[count].payRate == name)
cout << "ID number: " << employee[count].idNum
<< " First name: " << employee[count].firstName
<< " Last Name: " << employee[count].lastName
<< " Hourly Pay: " << endl;
}
}
}
My program also will not accept a value of more than one letter into the name. If I try and enter that into the program, the program keeps printing "Invalid entry" until I hit ctrl+c.
for (int i = 0; i < SIZE; ++i)
This checks every element in the array, including the one you have just read. You probably meant to put
for (int i = 0; i < count; ++i)
which will check every element up to (but not including) the one you have just read.
in
for (int i = 0; i < SIZE; ++i)
{
if (employee[i].idNum == employee[count].idNum)
error = 1;
}
employee[count] is one of the employee[i] you're going to compare against which means at some point you will
if (employee[count].idNum == employee[count].idNum)
Which is guaranteed to be true.
But if instead you
int tempId;
cin >> tempId;
for (int i = 0; i < SIZE; ++i)
{
if (employee[i].idNum == tempId)
error = 1;
}
and then set
employee[count].idNum = tempId;
at some later time, you can avoid this problem.
Addendum: I recommend picking this logic up and placing it in its own function. That way A) you don't have to repeat it inside the loop a few lines down where you're repeating the check for each retry and it gets the logic out of the way of the rest of the code. B) you can use the same function later for any other "Does this employee exist?" checks you need to write in the future.
In general You want to have lots of simple, easily-tested functions over one monolithic jack-of-all-trades.

On C++ run program if correct otherwise ask input again

I'm new into programing. I'm working on a program that will tell the odd and even numbers that are less or equal to the user's input (for inputs >=0). How do I make the program run if value is >=0 and ask for the input again if the value is <0.
Here is the program:
> #include <iostream>
using namespace std;
int main() {
cout << "Please enter only a positive value\n";
// Get number from user
int input = 0;
cout << "Enter a number:\n";
cin >> input;
int number = 1;
while (input >= 0 && number <= input) {
// Print some numbers
cout << "Here are some odd numbers:\n";
while (number <= input) {
cout << number << endl;
number = number + 2;
}
// Print some numbers
cout << "Here are some even numbers:\n";
int number2 = 0;
while (number2 <= input) {
cout << number2 << endl;
number2 = number2 + 2;
}
}
return 0;
}
Correct code:
#include <iostream>
using namespace std;
int main() {
cout << "Please enter only a positive value\n";
// Get number from user
int input = 0;
cout << "Enter a number:\n";
cin >> input;
while (input < 0) {
cout << "Input is negative. Enter again: \n";
cin >> input;
}
int number = 1;
while (input >= 0 && number <= input) {
// Print some numbers
cout << "Here are some odd numbers:\n";
while (number <= input) {
cout << number << endl;
number = number + 2;
}
// Print some numbers
cout << "Here are some even numbers:\n";
int number2 = 0;
while (number2 <= input) {
cout << number2 << endl;
number2 = number2 + 2;
}
}
return 0;
}
Note that I added this chunk:
while (input < 0) {
cout << "Input is negative. Enter again: \n";
cin >> input;
}
to handle negative inputs.
while (input < 0)
{
cout << "Enter a number:\n";
cin >> input;
if (input < 0)
// Here you can print something to tell that input was not correct
}

In C++, I need to create a program that loops and stops when a certain number is entered, Then displays the max and min

*edit: Fixed the code after realizing I was being a dumbass
Fixed code that works:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
int one, two, three = 0, highnum, lownum;
cout << "Enter your first integer: ";
cin >> one;
cout << "\nEnter your second integer: ";
cin >> two;
if (one > two)
{
highnum = one;
lownum = two;
}
while (one != -99 && two != -99 && three != -99)
{
cout << "\nEnter integers until you want to stop (-99 to stop): ";
cin >> three;
if (three > one && three > two || three < one && three < two )
{
if (three > one && three > two && three > lownum)
{
highnum = three;
}
else if ( three < one && three < two && three < lownum)
{
lownum = three;
}
}
else if (one > three && one > two || one < three && one < two)
{
if (one > three && one > two)
{
highnum = one;
}
else if (one < three && one < two)
{
lownum = one;
}
}
else if ( two > three && two > one || two < one && two < three)
{
if ( two > three && two > one)
{
highnum = two;
}
else if (two < one && two < three)
{
lownum = two;
}
}
}
cout << "Your lowest number is: "<< lownum << endl << "Your highest number is: " << highnum << endl << endl;
return 0;
}
I am not sure if arrays are the way to go for this type of problem, as we have yet to learn them in our lecture, but I am having some trouble finding the logic behind this looping structure and how to store an infinite number of variables until -99 is entered. Any help is appreciated
The assignment text:
Write a program with a loop that lets the user enter a series of integers. The user should enter -99 to signal the end of the series. After all the numbers have been entered, the program should display the largest and smallest numbers entered.
So far I have taken two different approaches using different combinations of while and for loops, but so far, no dice. Anyone have any suggestions?
Here are the two different versions of the code
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
/*
int one, two, three=0;
cout << "Enter your first integer: ";
cin >> one;
cout << "Enter you second integer: ";
cin >> two;
while ( one != -99 && two != -99 && three != -99 )
{
cout << "Enter another integer. To stop the program enter -99: ";
cin >> three;
}
if (one < two && three)
cout << one << endl;
else if (two < one && three)
cout << two << endl;
else if (three < one && two)
cout << three << endl;
return 0;
*/
And here is my second attempt:
int number, number2, number3, counter = 1;
double mul = 1;
cout << "Enter your first number that is not -99";
cin >> number;
while (number !=-99)
{
cout << "Please enter your second number " <<endl<<endl;
cin >> number2;
}
for (number != -99; number != -99; counter ++)
{
cout <<"Please enter another number. ";
cin >> number3;
}
if (number < number2 && number3)
{
cout << "The low number is " << number << endl;
if (number2 < number3)
cout << "The high number is " << number3 << endl;
}
else if (number2 < number && number3)
{
cout<< "The low number is " << number2 << endl;
if (number < number3)
cout << "The high number is " << number3 << endl;
}
else if (number3 < number && number2)
{
cout << "The low numer is " << number3 << endl;
if (number < number2)
cout << "The high number is " << number2 << endl;
}
Your code and your question title is a little bit controversy.
Based on what I understand about your question, you enter a series of numbers, and when -99 is entered the program will output min, max; but your code is keep entering 2 numbers, compare them and produce output until -99 is entered.
Here is just my raw code, it's not tested yet.
int main() {
int max, min, number;
cout << "Enter your number (not -99): ";
cin >> number;
max = number;
min = number;
while(1) {
cout << "Enter your number (-99 to stop): ";
cin >> number;
if (number == -99) { break; }
if (max < number) { max = number; }
if (min > number) {min = number; }
}
cout << "max: " << max << endl;
cout << "min: " << min << endl;
return 0;
}
The following code should work granted a user doesn't enter numbers greater than or less than 1000000.
int max,min,input;
max = -1000000;
min = 1000000;
cout << "Enter number: ";
cin >> input;
while(input!=-99){
if(input<min) min = input;
if(input>max) max = input;
cout << "Enter number: ";
cin >> input;
}
cout << "Max: " << max << endl;
cout << "Min: " << min << endl;
/I encountered this question tonight and came up with this solution/
#include <iostream>
using namespace std;
int main()
{
int inputNum, lownum, highnum;
cout << "Enter as many numbers as you'd like and then I'll show you which\n";
cout << "was highest and which was lowest.\n";
cout << "Enter -99 to end program.\n\n=>";
cin >> inputNum;
//If user enters -99 right away
if (inputNum == -99)
{
cout << "Ok, we'll thanks for playing anyway\n";
cin.ignore(); //This & next line pause program after ending.
cin.get();
return 0;
}
//assign first input number to both high & low values
highnum = inputNum;
lownum = inputNum;
while (inputNum != -99)
{
cout << "Input number\n=>";
cin >> inputNum;
if (inputNum == -99)
{
break;
}
if (inputNum > highnum)
highnum = inputNum;
if (inputNum < lownum)
lownum = inputNum;
}
cout << "Low number was " << lownum << endl;
cout << "High number was " << highnum << endl;
cin.ignore(); //This & next line pause program after ending.
cin.get();
return 0;
}

Structures with arrays

I am having trouble with my code. I cannot seem to understand how to implement my balances into the arrays while using structures. Is there anyone that could help me?
#include <iostream>
#include <iomanip>
using namespace std;
struct BankAccount
{
int accountNum;
double accountBal;
double annualIntrest;
int term;
};
int main()
{
const int BANKACC = 5;
const int QUIT = 1;
const int MONTHS_IN_YEAR = 12;
int x,found,input,month;
double total = 0;
double average = 0;
BankAccount accounts[BANKACC];
for(x = 0; x < BANKACC; x++)
{
do
{
found = 0;
cout << "Enter in account # " << (x + 1) << endl;
cin >> accounts[x].accountNum;
while(accounts[x].accountNum < 1000 || accounts[x].accountNum > 9999)
{
cout << "Account number must be four didgets:" << endl;
cin >> accounts[x].accountNum;
}
for(int check = 0; check < x; check++)
{
while(accounts[x].accountNum == accounts[check].accountNum)
{
cout << endl << "Account Numbers cannot be the same, enter in a new account number." << endl;
found = 1;
break;
}
}
} while(found);
cout << "Enter the accounts balance." << endl;
cin >> accounts[x].accountBal;
while(accounts[x].accountBal < 0)
{
cout << "Account cannot have a negitive balance." << endl;
cin >> accounts[x].accountBal;
}
cout << "Enter the interest rate." << endl;
cin >> accounts[x].annualIntrest;
while(accounts[x].annualIntrest > 0 && accounts[x].annualIntrest > 0.15)
{
cout << "Annual interest must be from 0 to 0.15." << endl;
cin >> accounts[x].annualIntrest;
}
cout << "How many years will the term be held for? " << endl;
cin >> accounts[x].term;
while(accounts[x].term < 1 || accounts[x].term > 10)
{
cout << "The Term must be greater than 1 and should not exceed 10" << endl;
cin >> accounts[x].term;
}
}
for(int year = 1; year < accounts[x].term; year++)
{
for( month = 1; month < MONTHS_IN_YEAR; month++)
{
accounts[x].accountBal = accounts[x].accountBal * accounts[x].annualIntrest + accounts[x].accountBal;
total += accounts[x].accountBal;
x++;
}
month = 1;
average = total / BANKACC;
}
for(x = 0; x < BANKACC; x++)
{
cout << "Account # " << (x + 1) << "'s number is: " << accounts[x].accountNum;
cout << " The accounts balance is: " << accounts[x].accountBal;
cout << " The interest on the account is: " << accounts[x].annualIntrest << endl;
}
cout << "Average of all the bank accounts is: " << average << endl;
cout << "Which account do you want to access?" << endl <<
" To stop or look at none of the account numbers type " << QUIT << endl;
for(x = 0; x < BANKACC; x++)
{
cout << accounts[x].accountNum << " ";
}
cin >> input;
while(input != QUIT)
{
found = 0;
x = 0;
while(x < BANKACC && input != accounts[x].accountNum)
{
x++;
}
if(input == accounts[x].accountNum)
{
cout << "Account:" << accounts[x].accountNum << " balance is: " <<
accounts[x].accountBal << " Interest rate is: " << accounts[x].annualIntrest;
cout << endl << "Enter the another account number or type 1 to quit.";
found = 1;
cin >> input;
}
if(found == 0)
{
cout << "Sorry that account doesn't exist. Enter another account number.";
cin >> input;
}
}
system("pause");
return 0;
}
Everything looks ok, until this line:
for(int year = 1; year < accounts[x].term; year++)
This code is outside the scope of the for loop:
for(x = 0; x < BANKACC; x++) { ... }
I believe that the loop over the years should be inside the BANKACC loop. For one, by the time the code gets to this, x is out of bounds of the array it looks like.
But that is not the only problem. The loops that iterate over the years and months will always go 1 less than they should since they are starting from 1, and going until (< term) or (< months_in_year)
Also, the way the average is being computed also seems to be wrong.
Some problems I noticed :
What if in accounts[x].term is also 1 ? Ans: You would never get in to that loop.
Are you actually computing the average of all bank accounts? Ans: No
You said account must be of 4 digits. So, 1000 & 9999 are valid account numbers. So, your condition should have been - while( accounts[x].accountNum < 999 || accounts[x].accountNum > 10000) ) { /.... }
Assuming that, user will always enter intergers only between 1 to 10 for term, try this -
for( int x=0; x < BANKACC; ++x )
{
for(int year = 1; (year < accounts[x].term) || (year==accounts[x].term); ++year)
{
for( month = 0; month < MONTHS_IN_YEAR; ++month)
{
accounts[x].accountBal += accounts[x].accountBal * accounts[x].annualIntrest;
total += accounts[x].accountBal;
}
}
}
average =(double) (total / BANKACC);
Also, if had set the warnings on while compilation, you should have got useful messages regarding array out of bounds.