do/while loops

hi guys, i am new to programming and so far i am familiar with nested for loops. I don't understand how do while loops can be nested. What is the main difference between all the loops and how do you know which one to use ? or write?

i took a second year computer engineering course without taking first year :C so i have to learn everything on my own as fast as a i can, to reach up to my class members.
This website has plenty of info :)

http://www.cplusplus.com/doc/tutorial/control/


EDIT: I will help you if you get stuck so just let me know. I dont mind.
Last edited on
that was a really good reference, but they are easy examples, i have to understand longer programs using many loops/
Okay.

The do-while loop, is the same thing as the while loop, but it guarantees that your program runs through the loop at least once, even if the condition is false.

Here's an example :

1
2
3
4
5
6
7
/* The Program will run through this loop at least once because it is a do while loop... when it gets to the end of the loop, it will evaluate the condition
*/
do
{
cout << "Hi There" << endl;

}while(0);

So, in plain English, here's what it does:

Program recognizes the loop as a do-while loop. Which means that it can run through the loop at least one time, ignoring the condition, before testing the condition. Try changing 0, to 1, and see what happens(Lol, Infinite Loop!).

And a while loop is slightly different, but an easy and yet helpful loop that you will run across often in C++. Here goes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace std;
int main (void)
{
    int n = 11;
    int i = 1;

    cout << "Press enter to start the countdown." << endl;
    cin.ignore();

    while ( n >= i)
    {

        n--;

        cout << n << " ";


    }

    return 0;
}


And that is how you would use a while loop(You could also use a for loop). So, basically, this program, asks you to press enter. The user should press enter which should start the while loop. Here's how the while loop works:

1
2
3
4
5
6
7
8
while ( N(10) is GREATER THAN or EQUAL TO 1)
{

SUBTRACT N-1 EACH TIME

DISPLAY N

} 


Simple enough right? The condition stays true only if n is greater than or equal to 1... Once, N is less than 1, then the program breaks out of the while loop, to be warmly greeted by return 0;

Have fun.
Let me know if you need better examples, or my explanation wasn't clear :)

-Code Assassin

Last edited on
thanks that was great help !
Topic archived. No new replies allowed.