Dowhile, Do, For
Dowhile, Do, For
Session 4
Seema Sirpal
Delhi University Computer Centre
Looping
In this case, the block of code being executed must update the
condition being tested in order for the loop to terminate at some point.
If the test condition is not modified somehow within the loop, the loop
will never terminate. This creates a programming bug known as an
infinite loop.
While
If the condition is false from the start the block of code is not
executed at all.
#include <stdio.h>
int main()
{
int count = 1;
The difference between a "do" loop and a "while" loop is that the
while loop tests its condition at the top of its loop; the "do" loop tests
its condition at the bottom of its loop.
If the test condition is false as the while loop is entered the block of
code is skipped. Since the condition is tested at the bottom of a do
loop, its block of code is always executed at least once. The "do"
loops syntax is as follows
do {
block of code
} while (condition is satisfied)
Do
Example of the use of a do loop:
The following program is a game that allows a user to guess a number
between 1 and 100. A "do" loop is appropriate since we know that
winning the game always requires at least one guess.
#include <stdio.h>
int main()
{
int number = 44;
int guess;
printf("Guess a number between 1 and 100\n");
do {
printf("Enter your guess: ");
scanf("%d",&guess);
if (guess > number) {
printf("Too high\n");
}
if (guess < number) {
printf("Too low\n");
}
} while (guess != number);
printf("You win. The answer is %d",number);
return 0;
}
For
The for loop can execute a block of code for a fixed number of
repetitions. Its syntax is as follows.
Suppose the user of the last example never enters "N", but the loop
should terminate when 100 is reached, regardless.
This loop starts one counter at 0 and another at 100, and finds a
midpoint between them.
Here is a silly example that will repeatedly echo a single number until a
user terminates the loop;
For practice, try implementing programs that will count down from 10
to 1 using while, do and for loops.
Solution using while
#include <stdio.h>
int main()
{
int i = 10;
while (i > 0)
{
printf("%d\n",i);
i = i - 1;
}
return 0;
}
Solution using do
Solution using do
#include <stdio.h>
int main()
{
int i = 10;
do {
printf("%d\n",i);
i = i - 1;
} while (i > 0);
return 0;
}
Solution using for
int main()
{
int i;
return 0;
}