While won't start loop after y/n input C++ - c++

Problem: while doesn't work to start loop over when user inputs y.
I have spent hours searching all forums including Stack Overflow for a clue and tried to figure this out (learning C++ on my own). Based on what I have read I have tried: a do loop works when placed at beginning but it incorrectly calculates by multiplying prior numb entry by next entry factorial (flushing problem?), I tried break and it stops calculation but it also stops without getting to cout <<“Do another?”. I have also tried adding/moving braces around statements and if statements (in desperation).
//problem #6 page 127 Robert Lafore OOP Prg C++ 4th ed.
#include <iostream>
using namespace std;
int main()
{
unsigned int numb;
unsigned long fact = 1; //long for larger numbers
char ch;
cout << "Enter a number ";
cin >> numb;
for (int j = numb; j > 0; j--) //multiply 1 by
{
fact *= j;
cout << "Factorial is "<< fact << endl;
cout << "Do another? (y/n)\n";
cin >> ch;
}
while(ch !='n');
return 0;
}

Your logic isn't quite right - you need to perform the operation once, then ask, and redo the entire operation.
Right now, you do a for loop for your operation, then get the character the user types every loop iteration, then just start a while loop that never terminates.
do/while is a good candidate for this:
do
{
fact = 1; // Reinitialize for subsequent loops
cout << "Enter a number ";
cin >> numb;
for(int j = numb; j > 0; j--) //multiply 1 by
{
fact *= j;
}
cout << "Factorial is " << fact << endl;
cout << "Do another? (y/n)\n";
cin >> ch;
}
while (ch == 'y'); // Switched to make anything other than 'y' break out

You need to do this:
do
{
for(int j=numb; j>0; j--) //multiply 1 by
{
fact *=j;
}
cout <<"Factorial is "<< fact<<endl;
cout <<"Do another? (y/n)\n";
cin >> ch;
}
while (ch != 'n');
What's wrong:
Your code goes into a for loop:
for(int j=numb; j>0; j--)
It calculates the factorial...but the code to do another one is in the for loop! Your program flow is like this:
Enter the for loop
Multiply fact by j and store the value in fact
Print the value of fact
Ask to do another
Store the value in ch
Continue the for loop
See the problem? You are asked to do another for each iteration of the for loop. Then, the while loop does this:
Loop while ch isn't equal to 'n'.
But...the loop is infinite! After the last iteration of the for loop, ch doesn't change. So, if the last value was 'y', well, the while loop keeps on looping over...and over...and over...since it has no body, it just continues forever.

You have sort of the right bits of code, but the bits of code are in the wrong places.
Move the output and input for "Do Another" to after the for-loop.
Add do { before cout << "enter a number;`
Add '} beforewhile(ch != 'n');`
Right now, you have a forever loop when ch is not 'n', since nothing changes ch inside the actual loop.

Related

For loop inside for loop execute only one time

I'm using while loop inside for loop to repeat for loop, but it only execute one time.
I did this code:
#include<iostream>
using namespace std;
int h, rep = 0;
int main() {
cout << "Please enter pyramid's height: ";
cin >> h;
cout << "Please enter Repetition Number: ";
cin >> rep;
for(int i = 0; i <= h; i++) {
while(0 < rep) {
for(int j = 0; j <= h; j++) {
if(i >= j)
cout << "x ";
else
cout << " ";
}
rep--;
}
cout << endl;
}
}
while(0<rep){
--rep;
}
At the conclusion of this while loop rep is 0. This is what the shown code tells your computer to do, so that's what your computer does. Your computer does this because of the Golden Rule Of Computer Programming: "Your computer always does exactly what you tell it to do instead of what you want it do".
A corollary to the Golden Rule states: "your computer never does anything you never tell your computer to do". You told your computer to stop the while loop when rep reaches 0, so rep is now 0. rep will still be 0 on the second iteration of the outer loop, so when it gets to this while loop, the second time, rep is still 0. You never told your computer to reset rep to the original value it had before the while loop, so your computer never does that.
If you would like for rep to be reset to its original value, every time, you need to tell your computer to do exactly that. It will also be simpler not to even use rep here, but copy its value to a different variable, and have the while loop use and decrement the other variable; so the same thing happens every time.

Using arrays with for-loops

Questions:
why is the first "cin >>" having "score[0]" saved to it? Since the program is asking for 5 numbers, wouldn't it make sense to save the entered numbers into an array of 5 ("score[4]")?
I also don't understand the syntax of the second "cin >> score[i]." I thought "cin>>" was coupled with "cout<<" when there was data input.
//Enter five scores. Show how much each differs from the highest score.
#include <iostream>
using namespace std;
int main()
{
int i, score[5], max;
cout<<"Enter 5 scores:\n";
cin >> score[0];
max = score[0];
for (i = 1; i < 5; i++)
{
cin >> score[i];
if (score[i] > max)
max = score[i];
}
cout <<"Highest score: " <<max<<endl
<<"The scores and their\n"
<<"diff. from highest are:\n";
for (i = 0; i < 5; i++)
cout << score[i] << " off by "
<< (max - score[i]) << endl;
return 0;
}
cin is stdin. This is a UNIX thing. Basically it's the input to your program. If you don't do anything else, it's your console or terminal session.
cout is stdout, another UNIX thing. It's output. Again, your console or terminal session if you don't do anything else with it. They aren't really coupled. It's two separate things, one for input only, one for output only.
Now, let's look at your code:
cin >> score[0];
max = score[0];
for (i = 1; i < 5; i++)
{
cin >> score[i];
if (score[i] > max)
max = score[i];
}
This could be simplified. You could get rid of the first two lines and change it to just this:
for (i = 0; i < 5; i++)
{
cin >> score[i];
if (score[i] > max)
max = score[i];
}
You'll just have to initialize max to a really negative value.
What cin >> does here is read a SINGLE value -- one score -- and then you stuff it into a single member of score. So you can NOT do something like this:
cin >> score;
That just won't work. Well, you might be able to make it work with operator overloading, but that's an advanced topic, and I've never tried. (I frankly never use the >> operator but find other ways to get input.)
Another thing: score[4] refers not to an array of size 5, but to the 5th item in the array, just like score[0] refers to the first item. It only refers to the size in the initial definition:
int score[5];
That's the only time the [5] is about the size. Otherwise it's an index into the array, starting at 0. So you have score[0] ... score[4].

Why do some sentinel loops require break to terminate? c++11

I have a loop that looks something like this
int temp = 0;
int menuItem;
while (temp != -1 && temp < 5)
{
cout << "Order " << temp + 1 << ": ";
cin >> menuItem;
arrayData[temp] = menuItem;
temp++;
break;
}
When I learned to use sentinels, I did not learn them using break...
for example.
int total = 0;
int points;
int game = 1;
cout << "Enter the points for game #" << game << endl;
cin >> points;
while (points !=-1)
{
total += points;
game++;
cout << "Enter the points for game #" << game << endl;
cin >> points;
}
This second loop continues on towards infinity until the value -1 is entered, and then it stops without the need for a break;. My first loop however will not stop when the sentinel value is entered unless the break is included.
Why is that?
While statement always repeat until the set condition get to false. In your first code example
while (temp != -1 && temp < 5)
Here, the while loop will exit if temp is -1 or temp is equal to 5. But, you insert break in your code which is will stop or force your while loop condition to stop.
while (condition) {
// Some code.
// Even if the condition true, it will stop because of break.
break;
}
In your second code, the condition set to
while (points !=-1)
so the while will only stop or exit, if the points variable has value of -1.
After understand the basic, you will find the answer for your question on why on the first while it didn't stop if there is no break;. The answer is because the condition on that while is still true so that the while execute again.
break always breaks the loop when it´s called.
In your first loop, however, you´re reading menuItem, no temp.
So, if you in enter -1 menuItem equals -1, no temp.

Making an if condition return if its true or while return if its true

When the condition is true or false, how can I make it return back and ask the question again, making the user re-enter the value?
Here is what I want to implement:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int n;
cout<<"Enter numbers. Press 5 to stop: ";
cin>>n;
bool tr=true;
while(tr)
{
if(n!=5)
cout<<"You entered "<<n; //How to make it return again, since its false? I keep getting infinite loops :( ;
else
tr=false;
}
return 0;
}
You need to prompt the user in the while loop, so that it occurs in each iteration:
int n;
bool tr = true;
while(tr)
{
cout << "Enter numbers. Press 5 to stop: ";
cin >> n;
if(n!=5) {
cout << "You entered " << n;
} else {
tr = false;
}
}
Just put all your code (except 'n' and 'tr' definition) in while loop as follow:
int main()
{
int n;
bool tr=true;
while(tr)
{
cout<<"Enter numbers. Press 5 to stop: ";
cin>>n;
if(n!=5)
cout<<"You entered "<<n;
else
tr=false;
}
return 0;
}
The other answers all work, and there is something to be learned about improving program flow from them, but I believe the trick you're asking for is the continue keyword, which skips the remainder of this iteration of the loop.
bool tr = true;
int n;
while (tr)
{
cout << "Enter numbers...";
cin >> n;
if (n != 5)
continue;
else
tr = false;
}
EDIT Part 1: On the continue keyword.
You want to make your code as readable as possible. In this example, its use is unnecessary (as the other posters have shown); but it is the answer to the question "How do I skip the rest of processing in this iteration of my loop and continue to the next iteration?". Usually, such flow-breaking directives actually make code harder to read; but sometimes the opposite is true. Anything (or, at least, almost anything) that can be accomplished with continue or break, can be accomplished without them, so if you're going to use them, you want to have a definite reason for doing so. Usually, when I use continue, it's because I'm looping through a collection of inputs and I want to skip processing the loop whenever the input isn't in the format I'm expecting. Something like this (pseudo-code)...
foreach (Input i in ReceivedInputs)
{
if (i.isBad())
{
cout << "Bad input";
continue;
}
// Do massive block of calculating here.
}
is easier to read than this...
foreach (Input i in ReceivedInputs)
{
if (i.isBad())
cout << "Bad input";
else
{
// Do massive block of calculating here.
}
}
because the second version makes it harder to track what scope you're in, if you're looking toward the end of the massive block of calculating. In this case, I gain code readability by continue, so I use it. But simple code probably shouldn't use it. The break keyword is similar, though it's a lot easier to come up with examples where break is beneficial.
EDIT Part 2: On multiple iterations
This is just an issue of setting up the loop; there are no magic keywords here. The shortest way I can come up with, is probably something like this:
int n = 0;
int numberToTake = 10;
for ( int numbersTaken = 0; numbersTaken < numberToTake; ++numbersTaken)
{
cout << "Enter numbers...";
int n = 0;
for (cin >> n; n != 5; cin >> n)
cout << "Try again.";
// Do whatever processing on n you want to do here.
}
Though I should point out that, doing it this way, the only value you will ever get from the user will be 5, and if he inputs anything that doesn't fit in an integer, you will get unexpected behavior.
EDIT 3: After reading the comment more thoroughly, I think you're just looking for is the more traditional use of the for loop.
No need for the exra bool variable.
The idiom can be: Infinitely loop until the user enters 5:
for(;;) { // Loops infinitely
cout << "Enter numbers. Press 5 to stop: ";
cin >> n;
if(n == 5)
break; // Exits the loop
cout << "You entered " << n; // Before the if if you want to print 5 as well
}

do while loops can't have two cin statements?

I'm just following a simple c++ tutorial on do/while loops and i seem to have copied exactly what was written in the tutorial but i'm not yielding the same results. This is my code:
int main()
{
int c=0;
int i=0;
int str;
do
{
cout << "Enter a num: \n";
cin >> i;
c = c + i;
cout << "Do you wan't to enter another num? y/n: \n";
cin >> str;
} while (c < 15);
cout << "The sum of the numbers are: " << c << endl;
system("pause");
return (0);
}
Right now, after 1 iteration, the loop just runs without asking for my inputs again and only calculating the sum with my first initial input for i.
However if i remove the second pair of cout/cin statements, the program works fine..
can someone spot my error please? thank you!
After you read the string with your cin >> str;, there's still a new-line sitting in the input buffer. When you execute cin >> i; in the next iteration, it reads the newline as if you just pressed enter without entering a number, so it doesn't wait for you to enter anything.
The usual cure is to put something like cin.ignore(100, '\n'); after you read the string. The 100 is more or less arbitrary -- it just limits the number of characters it'll skip.
If you change
int str;
to
char str;
Your loop works as you seem to intend (tested in Visual Studio 2010).
Although, you should also probably check for str == 'n', since they told you that they were done.
...and only calculating the sum with my first initial input for i...
This is an expected behavior, because you are just reading the str and not using it. If you enter i >= 15 then loop must break, otherwise continues.
I think you wanted this thing
In this case total sum c will be less than 15 and continue to sum if user inputs y.
#include<iostream>
using namespace std;
int main()
{
int c=0;
int i=0;
char str;
do
{
cout << "Enter a num: \n";
cin >> i;
c = c + i;
cout << "Do you wan't to enter another num? y/n: \n";
cin >> str;
} while (c < 15 && str=='y');
cout << "The sum of the numbers are: " << c << endl;
return 0;
}