how do you make a loop ask for another number after it runs through and does its math with the first number you give it? The code runs perfectly but I want it so I can put a new number in it for it to run through again without having to exit the program.
1 2 3 4 5 6 7 8 9 10 11 12
int num;
int answer = 1;
cout << "Enter a Number: " << endl;
cin >> num;
for (int multi = 1; num >= multi; multi++){
answer = answer * multi;
cout << answer << endl;
}
Put the code (lines 2-12 inclusive) inside of a do while loop and make it exit when num is something like 0 or -1 (you will also want to change the prompt to reflect the number to enter to exit).
I put it all in the for loop instead of a do while loop. I'm not sure how to do a dowhile loop. Is it the same as a do loop? I do have a new problem. If I type in 0 I get this: (lldb) No clue what it means. If 0 is typed in the answer should be one, not sure what it's doing.
int num; //Variables
int multi = 0;
int answer = 1;
cout << "Enter -1 to exit" << endl;
cout << "Enter a Number: ";
cin >> num;
do{
multi++;
answer = answer * multi;
cout << answer << endl;
//To start over the loop and enter in a new number
if (num == multi){
cout << "Enter a Number: ";
cin >> num;
multi = 0;
answer = 1;
}
//For negative numbers and how to exit (-1)
while (num < 0){
if(num == -1){
exit(1);
}
else{
cout << "Invalide Number" << endl <<
"The number must be a whole number" << endl;
cout << "Enter a Number: ";
cin >> num;
}
}
}while (num > multi);
}
I change the loop to a do loop but I still have one problem. When I enter in 0 the code just exits. I'm not sure why.
You have initialized multi as 0. And in your do-while loop, you check whether num is greater than multi. So, if you input num as 0, the while test condition evalutates as false, hence exiting your loop.