Home | About | Comments | Lectures | Notice | Registration
C Programming
Main Page
Review
Lesson Five
This lesson will introduce the use of the while loop and do while loop. A loop allows program statements to be repeated as many times as necessary to complete a job.
You Will Learn :
The general format for the While Loop is :
while (condition )
{
statement 1;
statement 2;
}
#include<stdio.h> int main() { int yards; float meters; yards = 1; while(yards <= 10) { meters = yards * .9144; printf("%d yards is %.4f meters \n", yards, meters); yards++; } exit(0); } |
Instructions :
Program 6 prints a metric conversion table as output. The body of the while loop will execute as long as the condition yards < = 10 is true. Just before the end of the loop is the statement yards++; this statement increments the value of yards by one each time the loop is executed.
Program 6.1 can be improved by using an if statement to ensure that the output is always grammatically correct. After the first execution of the body of the loop the output is 1 yards is 0.9144 meters.
Program 6 can be improved by using an if statement to ensure that the output is always grammatically correct. After the first execution of the body of the loop the output is 1 yards is 0.9144 meters.
The IF statement can be added to the source code to correct this error.
#include<stdio.h> int main() { int yards; float meters; yards = 1; while(yards <= 10) { meters = yards * .9144; if (yards ==1) printf("%d yard is %.4f meters \n", yards, meters); else printf("%d yards is %.4f meters \n", yards, meters); yards++; } exit(0); } |
One cannot afford to omit the yards++ statement. It could have been written as yards = yards + 1 ; but C has a more concise way of writing many statments. If omitted your program will be in an endless loop when executed because the value of yards will remain less than ten.
Always ensure that a while loop has an exit condition that will be true at some time during execution before using the while loop in your programs.
The Tutor |
|
Home | About | Comments | Lectures | Notice | Registration