Information Technology Center

Home | About | Comments | Lectures | Notice | Registration

MASTERING C WITH MC KENZIE

Lesson Six

  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 :


Iterations - The While Loop

The general format for the While Loop is :

   while (condition ) 
{
    statement 1;
    statement 2;
}

Turbo C Source Code

#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.


Points to Note

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 Assignment

  1.  Write a program to calculate the average of a set of numbers entered by the user
  2.  The program must ask the user to enter the number of numbers first before using a while loop to get the input values.
  3.  Find the sum of the values then calculate the average and print the average as your output.

 

.......End of Lesson Six.......

 

 


Lecturer:

The Tutor
Do you have a question or a comment ?
tutordam@yahoo.com


Home | About | Comments | Lectures | Notice | Registration