if else statement confused c++ - c++

#include <iostream>
using namespace std;
int main()
{
int positiveInteger;
cout << "Please input an integer up to 100." << endl;
cin >> positiveInteger;
int result = 0;
for (int i = 0; i <= positiveInteger; i++)
{
if ( positiveInteger >= 0 )
{
result += i;
}
else
{
cout << "Please input a positive integer." << endl;
}
}
cout << result;
return 0;
}
Above I have a for loop with an if else statement in the center. I am confused because I want it to be so when I enter a integer that is not negative it will loop the if result. But I want it to be so if I put in a negative number it says please input a positive integer. That's why I set it so in the if statement only numbers above and = to 0 would return the result, but if I enter a negative number I just get 0 I want it to say "Please input a positive integer". I don't understand what I'm doing wrong. Isn't the if statement if true pulls the if and if its not true pulls the else? Or am I missing something?

If you enter a negative number, you never get to enter the loop. An approach that fits better to such cases is:
do
{
input a number;
if( positive )
do something;
} while( not positive );

If I got it right, you want to
1. input a number;
2.1 If the number is positive you loop through it.
2.2 If it's negative you show the error message.
The problem is your loop, where the conditional is, checks if i (which is zero) is smaller then the number. However if you input a negative number i will be bigger then positiveInteger and you won't loop through the if. I fixed your code
using namespace std;
int main()
{
int positiveInteger;
cout << "Please input an integer up to 100." << endl;
cin >> positiveInteger;
int result = 0;
if ( positiveInteger >= 0 ){
for (int i = 0; i <= positiveInteger; i++)
{
result += i;
}
cout << result;
}
else {
cout << "Please input a positive integer." << endl;
}
return 0;
}

I think your code would benefit from some rearrangement. I'd structure it something like this:
do {
cout << "please enter a number between 1 and 100";
number = get_number():
} while (number < 1 || number > 100);
cout << sum_series(1, number);

The output you are getting is because your loop fails at non-negative numbers. You should try the following:
int main()
{
int positiveInteger;
cout << "Please input an integer upto 100." << endl;
cin >> positiveInteger;
int result = 0;
if ( positiveInteger < 0 )
{
cout << "Please input a positive integer." << endl;
}
else{
for (int i = 0; i <= positiveInteger; i++)
{
result += i;
}
cout << result;
}
return 0;
}

From my understanding, if the number is negative, you wish to take another input. But the cin statement is not under loop control to do it so. It just executes only one time irrespective of the nature of the number.

Related

while loop turning into an infinite loop for non bool values [duplicate]

I'm trying to build the Bulls & Cows game in C++. I've implemented most of the logic. The game runs continuously with the use of an infinite loop and generates a random value at each run.
What I'm trying to do now is to now is to take the user input and run the code if the input is valid (can ONLY be a 4 digit integer). This is my implementation:
#include ...
using namespace std;
vector<int> getDigits(int modelValue) {
vector<int> vectorValue;
int extractedDigit = 0;
int modulant = 10000;
int divisor = 1000;
for (int i = 0; i < 4; i++) {
extractedDigit = (modelValue % modulant) / divisor;
vectorValue.push_back(extractedDigit);
modulant /= 10;
divisor /= 10;
}return vectorValue;
}
int main() {
for (;;) {
int model = rand() % 9000 + 1000;
int guess = 0000;
int bulls = 0;
int cows = 0;
int counter = 1;
cout << "This is the random 4-digit integer: " << model << endl;
cout << "Enter a value to guess: ";
cin >> guess;
if ((guess >= 1000) && (guess <= 9999) && (cin)) {
vector<int> modelVector = getDigits(model);
vector<int> guessVector = getDigits(guess);
for (int i = 0; i < 4; i++) {
if (find(modelVector.begin(), modelVector.end(), guessVector[i]) != modelVector.end()) {
if (modelVector[i] == guessVector[i]) { bulls += 1; }
else { cows += 1; }
}
}cout << "There are " << bulls << " bulls and " << cows << " cows" << endl;
}
else {
cout << "Please enter a valid 4-digit integer between 0000 and 9999" << endl;
cin.clear();
}
}return 0;
}
But when I run and input something invalid, what I get is a continuously running .
There's nothing wrong with the way you read the user input, it just doesn't check for the input type before assigning the value into your 'guess' variable.
So, if an user put any value that isn't accepted by the integer type it would crash your application generating this infinite loop.
To protect your integer variable from wrong user inputs you must replace your direct input assignment:
cin >> guess;
By a protected one:
while(!(cin >> guess) || (guess < 1000)){
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Please, try again: ";
}
Into the while above you can see the "numeric_limits::max()" which is explained here:
Returns the maximum finite value representable by the numeric type T. Meaningful for all bounded types.
At the end you have a while holding the user into this reading loop while its input is under 1000 (as requested) or isn't a valid integer.
Try out cin.ignore(). It'll help you flush the cin buffer.

How to check for a valid user input in C++

I'm trying to build the Bulls & Cows game in C++. I've implemented most of the logic. The game runs continuously with the use of an infinite loop and generates a random value at each run.
What I'm trying to do now is to now is to take the user input and run the code if the input is valid (can ONLY be a 4 digit integer). This is my implementation:
#include ...
using namespace std;
vector<int> getDigits(int modelValue) {
vector<int> vectorValue;
int extractedDigit = 0;
int modulant = 10000;
int divisor = 1000;
for (int i = 0; i < 4; i++) {
extractedDigit = (modelValue % modulant) / divisor;
vectorValue.push_back(extractedDigit);
modulant /= 10;
divisor /= 10;
}return vectorValue;
}
int main() {
for (;;) {
int model = rand() % 9000 + 1000;
int guess = 0000;
int bulls = 0;
int cows = 0;
int counter = 1;
cout << "This is the random 4-digit integer: " << model << endl;
cout << "Enter a value to guess: ";
cin >> guess;
if ((guess >= 1000) && (guess <= 9999) && (cin)) {
vector<int> modelVector = getDigits(model);
vector<int> guessVector = getDigits(guess);
for (int i = 0; i < 4; i++) {
if (find(modelVector.begin(), modelVector.end(), guessVector[i]) != modelVector.end()) {
if (modelVector[i] == guessVector[i]) { bulls += 1; }
else { cows += 1; }
}
}cout << "There are " << bulls << " bulls and " << cows << " cows" << endl;
}
else {
cout << "Please enter a valid 4-digit integer between 0000 and 9999" << endl;
cin.clear();
}
}return 0;
}
But when I run and input something invalid, what I get is a continuously running .
There's nothing wrong with the way you read the user input, it just doesn't check for the input type before assigning the value into your 'guess' variable.
So, if an user put any value that isn't accepted by the integer type it would crash your application generating this infinite loop.
To protect your integer variable from wrong user inputs you must replace your direct input assignment:
cin >> guess;
By a protected one:
while(!(cin >> guess) || (guess < 1000)){
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Please, try again: ";
}
Into the while above you can see the "numeric_limits::max()" which is explained here:
Returns the maximum finite value representable by the numeric type T. Meaningful for all bounded types.
At the end you have a while holding the user into this reading loop while its input is under 1000 (as requested) or isn't a valid integer.
Try out cin.ignore(). It'll help you flush the cin buffer.

Exercise: for cycle and array

I have to write a program that allows to calculate the arithmetic average of an arbitrary numbers of values (chosen by the user)
It will outputs:
Number: 34
Number: 36
Number: 44
Number: //and I choose to stop input pressing
//Outputs:
It was inserted 3 numbers and the avarage is: 38
Of course i've forgot to post what i've done:
for (int x = 0; x < 50; x++){
cout << "Number: ";
cin >> number[x];
cout << "You have inserted the " << x << " element of the array;" << endl;
sum += number[x];
avarage = sum / number[x];
nEelementi = number[x];}
so I run the program, input some numbers, press something like ctrl+d or trying to add something to the code.. but it only goes from the first to the last element of the array with no values, becouse not entered, of course.. and then print absurd avarage and sum.
I know I don't need an array to do this but it's required from the exercise.. also the exercise only request to use for or while loop and arrays.
What I need is a way to stop the input and calculate the sum and avarage of only what I wrote.
edit1.
I've tried to dived by n writing for(x = 0; x < n, x++) because it made sense to me, but i think it "thinks" n, wrote like this, infinite, because the results is 0 (because the limit of a number divided by infinite is 0).. so i've started becoming mad.
Now i've started thinking that it would be easier to use while loop! and wrote
#include <iostream>
using namespace std;
int main() {
int num[50];
double sum = 0;
double average = 0;
int cont;
int end = 0;
while (cont < 50) {
cout << "num: ";
cin >> num[cont];
sum += num[cont];
cont++;
cout << "Want to continue 0 = sì, 1 = no";
cin >> end;
if (end == 1) {break;}
}
average = sum / cont;
cout << "You have insert " << cont << " elements" << endl;
cout << "LThe sum is: " << sum << endl;
cout << "The avarage is: " << average << endl;
return 0;
}
BUT still doesn't work. My professor says you should be able to stop input number by pressing ctrl+d so I'm not doing good.
Sorry for late answer but i have also to translate the code.. hope all translation is good:)
edit2.
#include <iostream>
int main() {
int sum = 0;
int num;
while ( std::cin ) {
std::cout << "Number: ";
std::cin >> num;
}
if ( std::cin >> num ) {
sum += num;
num++;
}
else {
std::cin.clear();
std::cout << "Input interrupted" << std::endl;
}
std::cout << "Sum is " << sum << std::endl;
std::cout << "You have entered " << num << " numbers" << std::endl;
return 0;
}
I love this new code, very simple and understandable to me, but I was not able to add sum operation, it only outputs 0! (leaving out average)
And also I was not able to determinate, and display, how many numbers I've entered. The last row of the code is just an example of what I want to do..
edit3.
Finally I made it.
#include <iostream>
using namespace std;
int main(){
double numero;
int index = 0;
double somma = 0.;
cout << "Inserire un numero: ";
while( cin )
{
if ( cin >> numero )
{
somma = somma + numero;
index++;
cout << "Inserire un numero: ";
}
else
{
cout << "Input interrotto" << endl;
}
}
cout << "Sono stati inseriti " << index << " numeri e la lora media è:
<< somma / index << endl;
return 0;
}
Thanks so much!
P.S. To the end, I don't need to use an array, it's just simple
There are a few problems here. One is that if the stream errors due to being closed or bad input, you don't recover and you just charge through your loop.
So first, make the loop terminate early if necessary. I'm also going to convert it to a while loop in preparation for the next part.
int x = 0;
while( std::cin && x < 50 )
{
std::cin >> number[x++];
}
Now it terminates early if the stream errors. But what if the user typed in "hello"? You could ignore it and continue like this:
if( std::cin >> number[x] )
{
x++;
}
else
{
std::cin.clear();
}
Notice that I didn't compute the sum or anything inside the loop. There's no need, since you are already putting them in an array. You can just do it after the loop. Here, I'm using std::accumulate
double sum = std::accumulate( number, number + x, 0.0 );
double average = 0.0;
if( x > 0 ) average = sum / x;
Now, you have also said you want an arbitrary number of values. Your original code allowed up to 50. Instead of storing them, you can instead just compute on the fly and discard the values.
double sum = 0.0;
int count = 0;
while( std::cin )
{
double value;
if( std::cin >> value )
{
sum += value;
count++;
}
else
{
std::cin.clear();
}
}
double average = 0.0;
if( count > 0 ) average = sum / count;
If you still want to store the values along the way, you can use a vector.
std::vector<double> numbers;
//...
numbers.push_back( value );
And if you want the user to choose the number of values:
std::cout << "Enter number of values: " << std::flush;
std::size_t max_count = 0;
std::cin >> max_count;
std::vector<double> numbers;
numbers.reserve( max_count );
while( std::cin && numbers.size() < max_count )
{
// ...
}

Error using For loop

I have problem running my loops.
I have to run a program where user enter 4 digit number, and it will show how many zero appear. This program will run depends on how many times user want it to run. so at the beginning I prompt user to enter the number of times the program will run, then the actual program will run in For loop. but so far, I can only run it once. Can someone help me? Thank you. Here is my code
#include <iostream>
using namespace std;
int main()
{
int numberTimes;
cout << "How many times do you want to run this check?\n";
cin >> numberTimes;
for (int counter = 0; counter < numberTimes; counter++);
{
int positiveInteger;
//prompt user to enter a positive integer
cout << "Please enter a positive integer value.\n";
cin >> positiveInteger;
//conditional statement
while((positiveInteger <=0) || (positiveInteger > 9999))
{
cout << "Invalid Value!!! Please try again.\n";
cout << "Please enter a positive integer value.\n";
cin >> positiveInteger;
}
cout << "Processing the value " << positiveInteger << ".\n";
int zeroCount = 0;
int firstNumber = positiveInteger%10; //separate the first number
if (firstNumber == 0) //determine if the first digit is zero
{
zeroCount = zeroCount + 1;
}
int digitOne = positiveInteger/10; //omitted first digit number
int secondNumber = digitOne%10; //separate the second number
if (secondNumber == 0) //determine if the second digit is zero
{
zeroCount = zeroCount + 1;
}
int digitTwo = digitOne/10; //omitted the second number
int thirdNumber = digitTwo%10; //separate the third number
if (thirdNumber == 0) //determine if the third digit is zero
{
zeroCount = zeroCount + 1;
}
int digitThree = digitTwo/10; //omitted the third number
int fourthNumber = digitThree%10; //separate the fourth number
if (fourthNumber == 0) //determine if the fourth digit is zero
{
zeroCount = zeroCount + 1;
}
cout << "Your first digit number is " << firstNumber << ".\n";
cout << "Your second digit number is " << secondNumber << ".\n";
cout << "Your third digit number is " << thirdNumber << ".\n";
cout << "Your fourth digit number is " << fourthNumber << ".\n";
cout << "Number of zero appear in your integer is " << zeroCount << ".\n";
if (zeroCount % 2 == 0) //determine if the number is even or odd
{
cout << "Your number zero appear even times.\n";
} else
{
cout << "Your number zero appear odd times.\n";
}
}
cout << "You have run this program " << numberTimes << ".\n";
cout << "Thank you and good bye.";
return 0;
}
The problem is using ; at the end of for line.
for (int counter = 0; counter < numberTimes; counter++);
In such a case that you used, it iterate the loop but do nothing.
In the other word,it is equal to the below program now :
for (int counter = 0; counter < numberTimes; counter++)
{
}
You can also use this program : (Add complementary lines)
#include <iostream>
using namespace std;
int main()
{
int positiveInteger;
int numberTimes;
int digit;
cout << "How many times do you want to run this check?\n";
cin >> numberTimes;
while(numberTimes)
{
int zeroRepitation=0;
cout << "Please enter a positive integer value.\n";
cin >> positiveInteger;
if ((positiveInteger <=0) || (positiveInteger > 9999))
{
cout << "Invalid Value!!! Try again!\n";
continue;
}
for (int i=1;i<5;i++)
{
digit = positiveInteger % 10;
if (digit=0)
{
++zeroRepitation;
}
positiveInteger = positiveInteger / 10;
}
cout<<"Number of zeros in this number= "<<zeroRepitation;
--numberTimes;
}
You put a semicolon at the end of the for statement. This:
for (int counter = 0; counter < numberTimes; counter++);
should be this:
for (int counter = 0; counter < numberTimes; counter++)

C calculating sum correctly

I can get the sum every time the user inputs an integer until either a negative number or non-integer is inputted. Problem is my sum calculations are off. I.E user putting 1000; sum outputs 1111, then user inputs 2000, it adds up to 3333. Just any advice is appreciated. I'll still experiment around with my coding.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int j , i = 0, k = 0,number;
double sum = 0;
cout << "Enter Positive integer number: ";
while(cin >> number)
{
cout << endl;
if( number < 0)//test if the number is negative
{
cout << "Ending program since user has input a negative number" <<endl;
break;
}
int temp = number;
int p = 1;
while( temp > 0) //counting number of digits
{
sum = sum+temp; //Sum attempt.
temp /= 10;
p *= 10;
i++;
}
cout << sum << endl;
j = i % 3;
p /= 10;
while( i > 0 )//display integer number with 1000 seperator
{
//this is giving me error
cout << char ((number/p) +'0');
number %= p;
p /= 10;
i--;
k++;
j--;
if ((k % 3 == 0 && i > 0)||(j == 0 && i > 2) )
{
cout <<",";
k = 0;
}
}
cout << endl << endl;
cout << "This program will exit if you input any non-integer characters\n";
cout << "Enter another integer number: ";
}
return 0;
}
It looks like you're trying to output an integer number with commas inserted at 1000 boundaries. ie: 1000000 would be displayed as 1,000,000.
This being the case, the easiest way to approach it might not be involving maths but simply to get a string representation of the int (atoi() for example) and count through that. From the back, count forward three chars, insert a comma, repeat until you run out of string.
The specifics of string handling are left as an exercise for the reader - looks like it's his homework after all. ;-)