Lecture 13 Loops1
Lecture 13 Loops1
C Programming
AAST
CCIT
What is a Loop?
Count-Controlled Loops
Event-Controlled Loops
While Statement Syntax
Using a While Statement for Summing
and Counting
Nested While Loops
Loop Testing and Debugging
A loop is a repetition control structure.
event-controlled loops
some condition within the loop body
changes and this causes the repeating to
stop
SYNTAX
while ( Expression )
{ .
. /*loop body */
.
}
WHILE LOOP
FALSE
Expression
TRUE
body
statement
Parts of a While Loop
printf( “Done” ) ;
count
int count ;
count = 4;
count -- ;
}
printf( " Done " ) ;
count
int count ;
count = 4; 4
count -- ;
}
printf( " Done " ) ;
count
int count ;
count = 4; 4
count -- ;
}
printf( " Done " ) ;
count
int count ;
count = 4; 4
count -- ;
}
printf( " Done " ) ;
count
int count ;
count = 4; 3
count -- ;
}
printf( " Done " ) ;
count
int count ;
count = 4; 3
count -- ;
}
printf( " Done " ) ;
count
int count ;
count = 4; 3
count = 4; 2
count = 4; 2
count = 4; 2
count = 4; 1
count = 4; 1
count = 4; 1
count = 4; 0
count = 4; 0
count = 4; 0
main () 1. Priming
Index: 2
Index: 3
Index: 4
{ Index: 5
int index =1; 2. Test Condition
… [forever]
count = 1 ; /* initialize */
while ( GoOn == 1 )
{
printf(“ Enter Grade “);
scanf(“ %d “ , &thisGrade );
if ( thisGrade == -1 )
GoOn = 0 ; /* change flag value */
else {
count++;
total = total + thisGrade ;
}
}
printf( “ Total is %d \n “, total ) ;
write a program that reads in the
grades of 50 students in a course (out
of 100 points each ) and then count the
number of A students ( grade > 85 ) and
the number of B students (grade > 75 ).
Write a program that does a survey on a
certain question. The question has 3
possible answers. Run the survey on 20
people and then display the number of
people who chose each answer.
Example:
What is your favorite subject?
A. Mathematics
B. Economics
C. Programming
Is a looping control structure in which the loop
condition is tested after each iteration of the
loop.
SYNTAX
do
{
Statements
} while ( Expression ) ;
total = 0 ;
do
{
printf(“ Grade : “ ) ;
scanf(“ %d “ , &thisGrade ) ;
Statement
WHILE
Expression
TRUE
FALSE