Loop

So i'm back

How can i make a loop in my program?
http://pastebin.com/ZMmTP6Lz
anyone willing to help me?

i want like

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main()
{
start
{
body
}
cout << "again?";
cin >> answer;
if (answer == 1)
{
goto START
}
else
{
return 0;
}
}
Last edited on
There are 3 different loop types in C++ (excluding the goto thingy):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
while(condition)
{
//repeat this stuff
}

do
{
//repeat this stuff
} while (condition);

for(/*do this before first iteration*/;
/*if this is true, perform iteration*/;
/*do this after each iteration*/)
{
//repeat this stuff
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//examples
int i = 0;
while(i<10)
{
++i;
cout<<i;
}

int i = 0;
do
{
++i;
cout<<i;
} while (i<10);

for(int i=0; i<10; ++i)
{
cout<<i;
}


The examples all pretty much do the same exact thing.
Last edited on
Small related question: In many situations, whiles and fors are interchangeable. If that's the case, is there a "best option", efficiency-wise?
Nope, not really. And you shouldn't worry about efficiency at those points, really. There are situations in which efficiency is important, but the difference between a for and a while loop is unlikely to be ever big enough to make it worth considering to make a decision between the two based on efficiency. Chances are your compiler implements the two exactly the same way anyways.
Depending on the situation though, it may be easier or more clear to write a 'while' loop over a 'for' loop, vice versa. Example:

it may be easier to write a while loop if you want something to repeat in process WHILE some condition is true. It may be easier to write a for loop if there are only a set number of steps in the program. Just food for thought.

However, yes they are both pretty much always interchangeable.
Last edited on
A for loop is also executed while some condition is true.
Topic archived. No new replies allowed.