Easy tutorial
for C / C ++ Control statement 5 (do while loop)
do while loop:
- The 'do while' loop is similar to the
'while' loop, but there is a characteristic difference. If the condition is
satisfied, the loop is executed. If the condition is not satisfied, the loop is
terminated.
- The 'while' loop terminates the
execution statement that iterates if it does not satisfy the condition. On the
other hand, the 'do while' loop executes the loop statement at least once.
- The structure is as follows.
do while loop
do
{
'execution
statement';
}while('condition');
Example Code
#include
<iostream>
using
namespace std;
int
main() {
int num;
cout << "Enter a natural number
between 1 and 10. : ";
cin >> num;
do{
cout << " Wrong !" <<
endl;
cout << " (Retry) Enter a natural
number between 1 and 10 : ";
cin >> num;
}while(num != 3);
cout << " Nice ! "
<<endl;
return 0;
}
-
Here is a simple code that transforms the 'while' loop example to 'do while'
loop. (Currently,
this code is written to show the difference between 'while' and 'do while'
loops but with error.)
results:
Enter
a natural number between 1 and 10. :
-
When you run it, you will be asked to enter a natural
number between 1 and 10. First, enter the correct answer 3 and hit Enter.
Enter
a natural number between 1 and 10. : 3
Wrong !
(Retry) Enter a natural number between 1 and
10 :
-
I entered correct answer 3 and but it says it is wrong. Although
'num' has been substituted for 3, the 'do while' loop is executed once and the
input is received again.
- That is, the conditional statement after the while
statement has not yet been reached. Let's put the other numbers once and enter
the correct answer.
Enter
a natural number between 1 and 10. : 3
Wrong !
(Retry) Enter a natural number between 1 and
10 : 8
Wrong !
(Retry) Enter a natural number between 1 and
10 : 3
Nice !
-
If you enter 8, it says "Wrong", and you get the input again. If you
enter the correct answer 3, "Nice !" will be printed.
-
Now let's fix the incorrect example. There are many ways to do this, but here
is a very simple fix.
#include
<iostream>
using
namespace std;
int
main() {
int num;
do{
cout << " Enter a natural number
between 1 and 10. : ";
cin >> num;
}while(num != 3);
cout << " Nice ! "
<< endl;
return 0;
}
-
When executed, the execution statement is executed and "Enter a natural
number between 1 and 10:" is printed. Let's type 3 from the beginning.
Enter
a natural number between 1 and 10. : 3
Nice !
-
You can see that the wrong part has been fixed. This
time, I'll put a few other numbers and type 3.
Enter a natural number between 1 and 10. : 1
Enter a natural number between 1 and 10. : 2
Enter a natural number between 1 and 10. : 6
Enter a natural number between 1 and 10. : 7
Enter a natural number between 1 and 10. : 3
Nice !
-
If the answer is wrong, you will be asked to continue
typing. If you type 3, "Nice!" Is displayed and the program is
terminated.
No comments:
Post a Comment