C:Loops - Do it While You Can (Page 3 of 4 )
A Do While loop is similar to a While loop, except that with a Do While loop, the program always loops through at least one time. In the below example, we will create a program that asks a user for a number and then counts down from there:
#include <stdio.h>
int main()
{
int count;
printf("Please enter a number from 1-20: ");
scanf_s("%d",&count);
do
{
printf("%dn",count);
count--;
}
while(count>0);
return(0);
}
If you type in 0 in the prompt, you will see that the program still runs, even though the criteria of count>0 is not met. This is because the first time through, the program prints the text prior to seeing whether the condition was met. It will always loop at least once.
Try running this program and type in the number 23. As you can see, the program still works, even though we told the user to only enter a number from 1-20. To fix this, we can insert a second loop. Let's do so:
#include <stdio.h>
int main()
{
int count;
do
{
printf("Please enter a number between 1-20: ");
scanf_s("%d",&count);
}
while(count<1 || count>20);
do
{
printf("%dn",count);
count--;
}
while(count>0);
return(0);
}
Now if you run the program and try to enter anything larger than 20 or smaller than 0 at the prompt, it will loop through and have you make your choice again until you choose an appropriate number.
Other Uses for Loops
You can also use loops to create a dramatic pause in your program. Let's count down from ten and have it pause in between each loop:
#include <stdio.h>
int main()
{
int count;
int wait;
count=10;
do
{
printf("%in",count);
count--;
for(wait=0;wait<1000000000;wait++);
}
while(count>0);
return(0);
}
Next: The Break And Continue Statement >>
More BrainDump Articles
More By James Payne