Pages

Tuesday, September 26, 2017

Easy tutorial for C / C ++ Control statement 4 (while loop)

Easy tutorial for C / C ++ Control statement 4 (while loop)

while loop:

- As an another control statement that does repetitive tasks, there are 'while' or 'do while' loops.

- The difference from the 'for' loop is that it creates a conditional expression, repeats if the condition is satisfied, and exits the loop if it does not satisfy the condition.

- That is, there is no initial expression and no increment / decrement expression.

- First, let's look at the 'while' loop. The structure is as follows.

while loop

while (condition) {
'execution statement';
}

- If the 'condition' is true, the 'execution statement' is executed repeatedly; if false, the 'while' loop is exited.

- Let's look back at a simple example.

Example Code

#include <iostream>
using namespace std;

int main() {    
     int num;
     cout << "Enter a natural number between 0 and 10. : ";
     cin >> num;

     while(num != 3){
          cout << " Wrong !" << endl;
          cout << " (Retry) Enter a natural number between 0 and 10. : ";
          cin >> num;
          }

     cout << " Nice !" << endl;

          return 0;
}

- The integer variable 'num' is declared and the natural number is input through 'cin'.

- The condition of the 'while' loop is 'num is not equal to 3'.

- If the value of 'num' is different from 3 (when the condition is true), continue to loop and "Wrong!" and "(Retry) Enter a natural number between 0 and 10." are printed.

- If the value of 'num' is 3, the conditional expression is false.

- As a result, it exits the loop and prints out the sentence "Nice!".

results

Enter a natural number between 0 and 10. :

- When you run it, you will be prompted to enter a natural number between 0 and 10. First, type 7 and hit enter.

Enter a natural number between 0 and 10.  :  7
Wrong !
(Retry) Enter a natural number between 0 and 10.  :

- "Wrong!" Is displayed and the sentence to be input again is displayed.

Enter a natural number between 0 and 10.  :  7
Wrong !
(Retry) Enter a natural number between 0 and 10.  :  9
Wrong !
(Retry) Enter a natural number between 0 and 10.  :  2
Wrong !
(Retry) Enter a natural number between 0 and 10.  :  4
Wrong !
(Retry) Enter a natural number between 0 and 10.  :  5
Wrong !
(Retry) Enter a natural number between 0 and 10.  :  3
Nice !

- Currently, I know the answer 3. I'll try typing some other numbers.

- It says it's still wrong.

- If you type 3, "Nice!" is printed and the program ends.

No comments:

Post a Comment