For loop inside for loop execute only one time - c++

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.

Related

While loop not ending when condition is met

void getPlayerRolls(int RollValues[], int& AttemptCount) {
int i = 0;
int FrameNumber = 0;
int RollNumber = 0;
while(RollValues[i] != -1) {
FrameNumber++;
cout << "Frame # " << FrameNumber << endl;
cout << "Roll #1 "
<< " ";
cin >> RollValues[i];
i++;
cout << "Roll #2 "
<< " ";
cin >> RollValues[i];
i++;
cout << endl;
}
}
My expectation is that when a -1 is entered for one of the roll values that the program terminates. I tried to create a while loop that works with an array but I am having trouble determining how to do this.
I removed lines from your function that are not part of the problem, but maybe this will clarify:
while(RollValues[i] != -1) {
cin >> RollValues[i];
i++;
cin >> RollValues[i];
i++;
i++;
}
What is the value of i by the time the loop condition variable is tested?
The first rollvalue entered is read into some place in the array, but then i is incremented, so if you read back from RollValues[i] you read from a different place in memory! Not only that, you never look at the first roll before accepting the second. And then you increment i yet again. By the time you're back at the top of the loop, i has been advanced 3 times, and neither of the entered rolls is ever tested.
You have other issues too, such as
receiving an array has no "size" information associated, so you do not now how big of an array the caller provided. Your code therefore cannot protect against overruning the memory.
in your while loop, you advance 3 times per iteration, so even if your loop condition checks for boundary cases, you still could have walked off the end of the array before getting back to the top of the loop.
Therefore, I suggest the following:
1) pass in the size of your array into your function, or use a safer data structure, such as std::array or std::vector
2) only process a single roll per loop, and check that you're within bounds before advancing.
3) don't advance your index variable until you're done looking at the value in that place that it refers.

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.

While won't start loop after y/n input 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.

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
}

stuck in a infinite do while loop

I am trying to make a simple guess my number game in c++ but the computer need to guess my number. But the problem is that I am stuck in this infinite loop. I am just a beginner so it's a really basic program.
This is my code:
int secretNumber = rand() %100 + 1; // random number between 1-100
int tries=0;
int input;
cout <<"typ your number\n";
cin >> input;
do
{
cout <<secretNumber <<endl;
++tries;
if (secretNumber > input)
{
cout <<"To high i guess?\n";
}
else if (secretNumber < input)
{
cout <<"To low I guess?\n";
}
else
{
cout <<"Yes, i got it in " <<tries <<" tries!";
}
}while (input != secretNumber);
return 0;
}
place cin >> input into loop body
I think you should move the random number generation inside the loop.
The value of the variable input is never changed in the loop, so the terminating condition input != secretNumber is never met.
You should take the input inside the loop. So write cin >> input at the beginning of the loop.
Edit:
If the computer should guess, then still the value of input needs to be changed in the loop, which is not present in your code. The loop runs with the same value in input every time.
To make you computer make a guess, you should follow some scheme. The computer may draw the numbers at random - which you can get through moving secretNumber = rand()%100 + 1 inside the loop. But this approach may not perform good, the loop may still run for a very long time. This is shown in #Kaii's answer.
A more efficient approach is the Binary Search. In this case you should keep track of the guesses the computer makes. Keep two variables high and low which should store the guesses higher and lower than input respectively. Whenever a guess in higher than the number, store it in high, and store any guess lower than input in low. Then the computer should try its new guess between high and low. A random guess should be secretNumber = low + rand() % (high - low). In worst case it will take as much as 100 iterations. For the best results, each guess should be (high + low) / 2. According to the conditions, one of high and low will be updated in each iteration. This approach will ensure that the computer will guess the correct number within 7 guesses.
In your code it should be like this:
int secretNumber = rand() % 100 + 1; // random number between 1-100
int tries=0;
int input;
int low = 1, high = 100;
cout <<"typ your number\n";
cin >> input;
do
{
secretNumber = (high + low) / 2;
cout << secretNumber <<endl;
++tries;
if (secretNumber > input)
{
cout << "Too high I guess?\n";
high = secretNumber;
}
else if (secretNumber < input)
{
cout << "Too low I guess?\n";
low = secretNumber;
}
else
{
cout << "Yes, i got it in " << tries << " tries!";
}
} while (input != secretNumber);
return 0;
the computer is only guessing (by random) once when the program starts, but should guess each time the loop is iterated. you should move the random number generation inside the loop:
int secretNumber = 0;
int tries=0;
int input;
cout <<"typ your number\n";
cin >> input;
do
{
/* the fix is here */
secretNumber = rand() %100 + 1; // random number between 1-100
cout <<secretNumber <<endl;
++tries;
if (secretNumber > input)
{
cout <<"To high i guess?\n";
}
else if (secretNumber < input)
{
cout <<"To low I guess?\n";
}
else
{
cout <<"Yes, i got it in " <<tries <<" tries!";
}
}while (input != secretNumber);
return 0;
You have to do the input within the loop. Right now you prompt for a value BEFORE you start looping, then never ask the user for another number. If the guess can't be changed, the loop can never exit.
changing to
do {
cin >> input;
will solve the infinite loop.
infinite loop in your code because the argument for while always true until you get the true number.
you need to add another argument. example you want set maximal tries to 5 times. then it will be like this
do{
//do your stuff here
}while((input != secretNumber)&&(tries<=5))
when you input wrong number for 5 times, the application will finish