Professional Documents
Culture Documents
7 Loops
7 Loops
Week2
Loops - The while statement
Loops - The while statement
} General form
while (expression)
statement
Loops - The while statement
} General form
FALSE
while (expression)
expression
statement
statement1 statement2
1. Evaluate expression
2. If TRUE then (a) execute statement1, (b) goto step 1.
3. If FALSE then execute statement 2.
} Read in English as:
while expression is TRUE execute statement 1.
If expression is FALSE then execute statement 2.
Example 1
1. Read a sequence of integers from the terminal until -1 is read.
2. Output sum of numbers read, not including the negative
number.
} First, let us write the loop, then add code for sum.
#include <stdio.h>
main() {
int a;
scanf(“%d”, &a); /* read into a */
while ( !( a == -1) ) {
scanf(“%d”, &a); /* read into a inside loop*/
}
}
Tracing the loop
Tracing the loop
#include <stdio.h>
main() {
int a;
scanf(“%d”, &a); /* read into a */
while ( !(a== -1)) {
scanf(“%d”, &a); /* read into a inside loop*/
}
}
$./a.out
4
15
-5
-1
Tracing the loop
#include <stdio.h>
main() {
int a;
scanf(“%d”, &a); /* read into a */
while ( !(a== -1)) {
scanf(“%d”, &a); /* read into a inside loop*/
}
}
“The instructor of this course owns the copyright of all the course materials. This lecture material
was distributed only to the students attending the course ESC-101 of IIT Kanpur, and should not
be distributed in print or through electronic media without the consent of the instructor. Students
can make their own copies of the course materials for their use.”