I'm new at C++ programming, so I have a newbie question.
If the value of int b
is the user input, how would I create a loop that would run only "b" amount of times?
Example:
- User enters "5".
- The loop will run 5 times.
I'm new at C++ programming, so I have a newbie question.
If the value of int b
is the user input, how would I create a loop that would run only "b" amount of times?
Example:
You may eventually wish to change things a little here (e.g. ++i, etc.) and there to suit your various needs as you get more familiar and experienced with coding.
For now, in typical usage...
You can use a for
loop:
for ( int i = 0; i < b; i++ ) {
// do something here
}
Take note that you start from i = 0
in your first loop. In your second loop, i = 1, and so on so forth. In your last b-th loop, i = b-1. The i++
in the for
loop means that i
will be incremented by one at the end of each loop, automatically; there is no need for you to write another statement (such as i = i + 1) to increment i
inside the loop.
Or, you can use a while
loop.
while (i < b) {
// do something here
i++;
}
In the while
loop, you have to manually and explicitly increment i
yourself at the end of the loop.
If you need more help, you can refer to tutorials online for more examples, such as: http://www.tutorialspoint.com/cplusplus/cpp_while_loop.htm http://www.tutorialspoint.com/cplusplus/cpp_for_loop.htm
If your interested, you can also take a look at the do-while
loop:
http://www.tutorialspoint.com/cplusplus/cpp_do_while_loop.htm
int b;
cin>>b;
#taking user input for value of b
for(int i=0;i<b;i++){
#do whatever you want
}
This loop runs for b number of times.
Use An variable which we can increase and after specific target loop will stop executing. ex- In following code I used variable int times, which increases +1 every time when my condition fails. when this variable reaches specified target it stops executing
'''
int times = 0;
while (times < 2000 && other condition)
{
//Your Code
if (An Condition){
//Your Code
break;
}
else{
times += 1;
continue;
}
}
'''