Page 50 - DCAP404 _Object Oriented Programming
P. 50
Unit 2: Beginning of OOP Language
The do-while loop displays the current value of digit, increases its value by 1, and then tests to Notes
see if the current value of digit exceeds 9. If so, the loop terminates, otherwise, the loop continues,
using the new value of digit. Note that the test is carried out at the end of each pass through the
loop. The net effect is that the loop will be repeated 10 times, resulting in 10 successive lines of
output.
For example, let us see the calculation for the average of numbers:
/ * calculate the average of n number */
# include < stdio. h>
main ( )
{
int n,count = 1;
float x, average, sum = 0;
/* initialize and read in a value for n */
printf ( “How many numbers ?”);
scanf ( “%d” , %n);
/* read in the numbers 8/
do {
printf ( 8 x = 8) ;
scanf ( “% f , %x);
sum += x;
++ count ;
} while ( count < = n);
/* calculate the average and display the answer*/
average = sum /n
printf (“ \ n The average is &f \n “,average);
}
Notes One interesting thing about the while loop is that if the loop condition is false, the
while loop may not execute at all.
The for Statement
The for statement includes an expression that specifies an initial value for an index, another
expression that determines whether or not the loop is continued, and a third expression that
allows the index to be modified at the end of each pass.
The general form of the for statement is
for (expression-1; expression-2; expression-3) statement;
LOVELY PROFESSIONAL UNIVERSITY 43