hello guys, is there a way to avoid chechking if statements when it is complited and dont exit with the loop. for example;
for(int i=0;i<10;i++)
{
if(i==1) {stop checking this if but dont exit in the loop and check another if};
else if(i==5) {same and so on};
}
is there any ideas??
don't loop. its only 10, and you are making a mess of it with the conditions.
just do this:
statement for i = 0;
statement for i = 1;
statement for i = 2;
statement for i = 3;
statement for i = 4;
statement for i = 5;
statement for i = 6;
statement for i = 7;
statement for i = 8;
statement for i = 9;
there are other ways if you had a lot more than 10, but unrolling here looks best to me -- you don't have to loop, you don't need to worry about i anymore, just do the statements as needed in order, you don't need the conditions, etc. It cleans up nicely.
Hi, biwkina.
Please, try to add further details. In a for-loop, the variable you loop on takes a different value at every iteration; therefore, in your example, only one ‘if’ will result in being true at every iteration:
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
int main()
{
for(int i = 0; i < 10; ++i) {
if(i == 1) { std::cout << "This instruction will execute only once\n"; }
if(i == 5) { std::cout << "Guess what? I'll execute only once\n"; }
if(i == 6) { std::cout << "Surprise! This sentence won't be repeated\n"; }
}
return 0;
}
Output:
This instruction will execute only once
Guess what? I'll execute only once
Surprise! This sentence won't be repeated