From my previous codes, we encountered looping statements that helped us with the repetitive parts of the program. Now, I will introduce you the two looping statements that is very useful in program control. These looping statements are the Do-While Loop and For Loop.
Now, I will show you the Do-While Loop. Do-While Loop processes the statement once before processing the condition. Do-While loop is used on programs that statements are needed to be executed first before processing the condition. To show you how the do-while loop work, I made a simple program that will execute it. Check out the codes below.
1:
2: #include <stdio.h>
3: #include <conio.h>
4:
5: int main()
6: {
7: int n;
8: int generate = 1;
9:
10: printf("Enter number: ");
11: scanf("%d", &n);
12:
13: do
14: {
15: printf("%d\t", generate);
16: generate += 1;
17: }while(generate <= n);
18:
19: getch();
20: }
When this program is run it will ask the user to enter any number. After that, the do-while loop will execute the argument. For example, when you input five (5) the program should display 1 2 3 4 5, respectively. In the condition part, your n (that is your input) will be the final value to how many times the loop should repeat the command. Generate will be the initial value. Generate starts with number one (1) so when it reaches generate += 1 it will display one (1) at first output, then it will go into the condition where generate will be compared to your input (n). If generate will not satisfy n it will go back to the statement and add one (1) to itself again then show another output, that will be two (2) this time because the first time it executed the loop it holds number one (1). Then it will go back to the condition and if it doesn't satisfy n it will go back again to the statement and do the same execution again. If generate satisfies the condition the loop will automatically stop and the outputs will be shown. Then you can terminate the program afterwards. You can check out the sample output below.
Hope you learned something. Feel free to leave a comment below. Thanks!
No comments:
Post a Comment
Please do leave a comment. It's gonna be a friendly conversation between programmers. Hope you do find our blog helpful. Thank you!