Lecture06 - Copy
Lecture06 - Copy
University of Ottawa
Winter 2025
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
In-Class Exercise: Go To Brightspace
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
Outline
1 Loops
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
Loops
Loops
for-loop
for (initializeCounter; S; modifyCounter)
DoX;
Execute InitializeCounter;
FALSE is S
True?
TRUE
Execute DoX;
Execute modifyCounter;
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
Loops
int i, x=0;
i=0;
int i, x=0;
for (i=0; i<3; i++)
x=x+i+2;
printf("%d\n", x);
FALSE
i<3?
TRUE
i++ here is the same as x=x+i+2;
i=i+1, i.e., increasing i
i++;
by 1.
printf("%d\n", x);
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
Loops
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
Loops
Write a Program
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
Loops
Coding Demonstration
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
Loops
while-loop
while (S)
DoX;
FALSE is S
True?
TRUE
Execute DoX;
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
Loops
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
Loops
int i, x=0;
int i, x=0;
i=0; for (i=0; i<3; i++)
x=x+i+2;
printf("%d\n", x);
FALSE
i<3? int i, x=0;
i=0;
TRUE while (i<3)
x=x+i+2; {
x=x+i+2;
i++; i++;
}
printf("%d\n", x);
printf("%d\n", x);
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
Loops
Definite while-loop
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
Loops
Indefinite while-loop
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
Loops
int sentinel;
sentinel = 1;
while (sentinel != -1)
{
printf("Enter a value ( -1 to exit the
loop)\n");
scanf("%d", &sentinel);
}
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
Loops
Write a Program
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
Loops
Coding Demonstration
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .