Help needed with the while loop

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • lyle777
    New Member
    • Apr 2010
    • 8

    #1

    Help needed with the while loop

    Hi there
    I need help with the while loop, ive just started learning about it and I do not understand it. I heard that if the condition is true, the statements executes until
    it becomes false.

    It would be nice if someone could write me a small and simple example code
    that shows me how the while loop works.

    I was having trouble understanding the following:

    Code:
    #include <iostream>
    using namespace std;
    int main()
    {
        int length, width, num;
        
       cin >> num;
       
        while(num < 20) {
                      cout << "KKK ";
                      num++;
        }
        cin.get();
        cin.get();
        cin.get();
        return 0;
    }
    Last edited by Banfa; Apr 16 '10, 01:16 PM. Reason: Added [code]...[/code] tags
  • Dheeraj Joshi
    Recognized Expert Top Contributor
    • Jul 2009
    • 1129

    #2
    Until the condition becomes false while loop will be executed.

    In you example

    Code:
    cin >> num;
    
    while(num < 20) {
    cout << "KKK ";
    num++;
    }
    if user inputs value less than 20 while loop will execute and it prints numbers from user input value till 19.

    example: if user entered 15 then your program will print

    Code:
    15
    16
    17
    18
    19
    if user has entered something greater than 20 or 20. Your program won't print anything.

    Regards
    Dheeraj Joshi

    Comment

    Working...