Académique Documents
Professionnel Documents
Culture Documents
Repetitive Statements
while ( expression)
{
statement block;
}
main()
{
int x=1;
while (x<=10)
{
printf (“ Number %d\n”,x);
x++;
}
getch ();
return 0;
}
Common Mistakes in while -- extra semi-colon;
do
statement block;
while ( expression);
main ()
{
int count =1;
do
{
printf ("%d\n", count);
}
while (count++ <=10) ;
printf ("BYE");
getch ();
return 0;
}
7.2 For( ) Statement
Form of loop which allows for
initialization and iteration control
Syntax:
for (i=0;i<=3;i++)
{
statement block
}
The for Statement
The for loop executes as follows:
The initial statement executes
The loop condition is evaluated
if the loop condition evaluates to true
execute the for loop statement
execute the update statement (the third expression in the
parentheses)
Repeat the previous step until the loop condition evaluates to false
The initial statement initializes a variable
The initial statement in the for loop is the first to
be executed and is executed only once
#include <stdio.h>
Example: addfor.c #include <conio.h>
/**********************************\
Read in numbers and add them up
Read in numbers, add Print out the sum and the average
them, and \**********************************/
print the sum and the main()
{
average
float nextNum, sum = 0.0;
int count, totalNumbers;
set sum to 0
set count to 0 printf("Insert total numbers\n");
input totalNumbers scanf("%d", &totalNumbers);
for ( count=0;
count < totalNumbers;
for (count < totalNumbers) count++ )
{ {
input nextNum printf("Insert next numbers\n");
add nextNum to sum scanf("%f", &nextNum);
sum += nextNum;
add 1 to count
printf("Sum was %f\n",sum);
} }
printf("Mean was %f\n",sum/count);
output "Sum was" sum getch ();
output "Mean was" return 0;
sum/count }
printf("Insert total numbers\n");
scanf("%d", &totalNumbers);
for ( count=0;
count < totalNumbers;
count++ )
{
printf("Insert next numbers\n");
scanf("%f", &nextNum);
sum += nextNum;
printf("Sum was %f\n",sum);
}
return 0; return 0;
} }
while and for (cont)
#include <stdio.h> #include <stdio.h>
int main()
Check
Initialize
condition
int main()
{ {
float nextNum, sum = 0.0;
int count, totalNumbers;
Check condition
float nextNum, sum = 0.0;
int count, totalNumbers;
scanf("%d", &totalNumbers);
scanf("%d", &totalNumbers);
count = 0;
while (count < totalNumbers) for ( count=0;
count < totalNumbers;
{ count++ )
scanf("%f", &nextNum); {
sum += nextNum; scanf("%f", &nextNum);
count++; sum += nextNum;
}
}
printf("Sum was %f\n",sum);
printf("Mean was %f\n", printf("Sum was %f\n",sum);
sum/count); printf("Mean was %f\n",
sum/count);
}
return 0; Update
return 0;
}
7.3 Break and Continue Statement
Break Statement Continue Statement
Use to exit from a Use only in repetitive
statement block statement
Transfer instruction
Use with:
execution sequence to
• switch..case test
• For condition for repetitive
• while () statement
• do..while()