Lab Module Chapter6
Lab Module Chapter6
Concept – Loop
Loop : a statement that will repeatedly execute a set of statements (known
as loop body) every time the loop’s expression is true. When the
expression is false, the execution of the program will break out of
the loop body.
Controlling expressions: an expression that will determine whether loop body
will be executed or not.
Iteration : each time the program execution goes through the loop body
Exercise 1: while Statement
General syntax:
while(controlling expression)
loop body
Example 1: the following statement computes the smallest power of 2 that is greater or equal to n
while (i < n) /* controlling expression */
i = i * 2; /* loop body */
Suppose the initial value of i is 1 and suppose the user is prompted to input an integer number that will be
stored as n, for each of the following values of n, what will be the final value of i?
N i
2 2
3 4
4 4
5 8
Notes:
1. The body of a while loop may not be executed at all, because the controlling expression is tested
before the body is executed.
example: consider the statement from example 2. What will happen if i is assigned to the value -5?
while (i > 0)
printf("T minus %d and counting\n", i--);
3. The controlling expression needs to be false at some point for the loop to terminate.
example: consider example 2. What will happen if i-- was replaced by i++?
The loop will executed forever
This is what we call as an Infinite Loop. This kind of statement will never terminate. It will execute
forever unless its body contains a statement that transfers control out of the loop (break, goto,
return) or calls a function that causes the program to terminate.
4. C programmers sometimes deliberately create an infinite loop by using a nonzero constant as the
controlling expression: while(1)…
Program 1: printing a table of squares
/* square.c - Prints a table of squares using a while statement */
#include <stdio.h>
int main(void)
{
int i, n;
#include <stdio.h>
int main(void)
{
int n, sum = 0;
printf("This program sums a series of integers.\n");
printf("Enter integers (0 to terminate): ");
scanf("%d", &n);
while (n != 0) {
sum += n;
scanf("%d", &n);
}
printf("The sum is: %d\n", sum);
return 0;
}
A sample run would be as follow:
This program sums a series of integers.
Enter integers (0 to terminate): 8 23 71 5 0
The sum is: 107
Challenges:
1. Write a program that will print out all even numbers between 1 and n
2. Write a program that will calculate the sum of all odd numbers between 0 and n
3. Write a C program that find the largest in a series of positive numbers entered by the user. The program
must prompt the user to enter numbers one by one. When the user enters negative number, the program
will display error message and repeat the prompt. When the user enters 0, the program must display the
largest and smallest positive nonzero number entered. A sample run should be as follow:
Enter a positive number: 60
Enter a positive number: 100.62
Enter a positive number: -20
The number you entered is a negative number.
Enter a number: 5
Enter a number: 0
The largest positive number entered was 100.62
The smallest positive nonzero number entered was 5
Exercise 2: do Statement
General syntax:
do statement while(controlling expression);
When a do statement is executed, the loop body is executed first, then the controlling expression is
evaluated. If the value of the expression is nonzero, the loop body is executed again and then the expression
is evaluated once more.
Challenges:
1. Write a program that will print out all even numbers between 1 and n
2. Write a program that will calculate the sum of all odd numbers between 0 and n
3. Write a C program that find the largest in a series of positive numbers entered by the user. The program
must prompt the user to enter numbers one by one. When the user enters negative number, the program
will display error message and repeat the prompt. When the user enters 0, the program must display the
largest and smallest positive nonzero number entered. A sample run should be as follow:
Enter a positive number: 60
Enter a positive number: 100.62
Enter a positive number: -20
The number you entered is a negative number.
Enter a positive number: 5
Enter a positive number: 0
The largest positive number entered was 100.62
The smallest positive nonzero number entered was 5
Exercise 3: for Statement
General syntax:
for (exp1;exp2;exp3) statement
exp1, exp2, and exp3 are expressions.
The for statement is ideal for loops that have a “counting” variable, but it’s versatile enough to be used for
other kinds of loops as well.
Question 1: suppose we replace i-- in the countdown example with --i. Will there be any difference in the
output? Why?
If we use - - i, it will decrease the number first then display it
Notes:
1. Since the first and third expressions in a for statement are executed as statements, their values are
irrelevant—they’re useful only for their side effects.
2. Consequently, these two expressions are usually assignments or increment/decrement expressions
3. The for statement is usually the best choice for loops that “count up” (increment a variable) or “count
down” (decrement a variable).
4. A for statement that counts up or down a total of n times will usually have one of the following forms:
5. In C99, the first expression in a for statement can be replaced by a declaration. This feature allows the
programmer to declare a variable for use by the loop: for (int i = 0; i < n; i++)
6. A variable declared by a for statement can’t be accessed outside the body of the loop (we say that it’s
not visible outside the loop):
Common Errors:
1. Using < instead of > (or vice versa) in the controlling expression. “Counting up” loops should use the <
or <= operator. “Counting down” loops should use > or >=.
2. Using == in the controlling expression instead of <, <=, >, or >=.
3. “Off-by-one” errors such as writing the controlling expression as i <= n instead of i < n.
C allows any or all of the expressions that control a for statement to be omitted.
Example 2: omitting exp3, the loop body is responsible for ensuring that the value of the second expression
eventually becomes false:
for (i = 10; i > 0;)
printf("T minus %d and counting\n", i--);
When the first and third expressions are both omitted, the resulting loop is nothing more than a while
statement in disguise:
#include <stdio.h>
int main(void)
{
int i, n;
Challenges:
1. Write a program that will print out all even numbers between 1 and n
2. Write a program that will calculate the sum of all odd numbers between 0 and n
3. Write a C program that find the largest in a series of positive numbers entered by the user. The program
must prompt the user to enter numbers one by one. When the user enters negative number, the program
will display error message and repeat the prompt. When the user enters 0, the program must display the
largest and smallest positive nonzero number entered. A sample run should be as follow:
Enter a positive number: 60
Enter a positive number: 100.62
Enter a positive number: -20
The number you entered is a negative number.
Enter a number: 5
Enter a number: 0
The largest positive number entered was 100.62
The smallest positive nonzero number entered was 5
For each one of the challenges above, decide which loop statement is more efficient for you to use, and state
your reasons.
Exercise 5: break Statement
1. The normal exit point for a loop is at the beginning (as in a while or for statement) or at the end
(the do statement).
2. Using the break statement, it’s possible to write a loop with an exit point in the middle or a loop
with more than one exit point.
3. The break statement can transfer control out of a switch statement, but it can also be used to jump
out of a while, do, or for loop.
Example 1: checks whether a number is prime. Terminates as soon as a divisor is found
for (d = 2; d < n; d++)
if (n % d == 0)
break;
After the loop has terminated, an if statement can be use to determine whether termination was
premature (hence n isn’t prime) or normal (n is prime):
if (d < n)
printf("%d is divisible by %d\n", n, d);
else
printf("%d is prime\n", n);
4. The break statement is particularly useful for writing loops in which the exit point is in the middle
of the body rather than at the beginning or end.
5. Loops that read user input, terminating when a particular value is entered, often fall into this category
Example 2:
for (;;) {
printf("Enter a number (enter 0 to stop): ");
scanf("%d", &n);
if (n == 0)
break;
printf("%d cubed is %d\n", n, n * n * n);
}
6. A break statement transfers control out of the innermost enclosing while, do, for, or
switch. It will not work with if statements.
7. When these statements are nested, the break statement can escape only one level of nesting.
Example 3:
while (…) {
switch (…) {
…
break;
…
}
}
break transfers control out of the switch statement, but not out of the while loop.
Program 1: balancing checkbook
/* checking.c - Balances a checkbook */
#include <stdio.h>
int main(void)
{
int cmd;
float balance = 0.0f, credit, debit;
printf("*** ACME checkbook-balancing program ***\n");
printf("Commands: 0=clear, 1=credit, 2=debit, ");
printf("3=balance, 4=exit\n\n");
for (;;) {
printf("Enter command: ");
scanf("%d", &cmd);
switch (cmd) {
case 0:
balance = 0.0f;
break;
case 1:
printf("Enter amount of credit: ");
scanf("%f", &credit);
balance += credit;
break;
case 2:
printf("Enter amount of debit: ");
scanf("%f", &debit);
balance -= debit;
break;
case 3:
printf("Current balance: $%.2f\n", balance);
break;
case 4:
return 0;
default:
printf("Commands: 0=clear, 1=credit, 2=debit, ");
printf("3=balance, 4=exit\n\n");
break;
}
}
}
A sample run will be as follow:
*** ACME checkbook-balancing program ***
Commands: 0=clear, 1=credit, 2=debit, 3=balance, 4=exit
Enter command: 1
Enter amount of credit: 1042.56
Enter command: 2
Enter amount of debit: 133.79
Enter command: 1
Enter amount of credit: 1754.32
Enter command: 2
Enter amount of debit: 1400
Enter command: 2
Enter amount of debit: 68
Enter command: 2
Enter amount of debit: 50
Enter command: 3
Current balance: $1145.09
Enter command: 4
#include <stdio.h>
int main () {
int a = 1;
/* do loop execution */
do {
if( a == 4 || a == 13 || a == 14) {
a = a + 1;
continue; /* skip the iteration */
}
} while( a <= 15 );
return 0;
}
1. The goto statement is capable of jumping to any statement in a function, provided that the statement has
a label (identifier).
2. The goto statement is capable of jumping to any statement in a function, provided that the statement has
a label.
3. Executing the statement goto L; transfers control to the statement that follows the label L, which must
be in the same function as the goto statement itself.
4. If C didn’t have a break statement, a goto statement could be used to exit from a loop:
Example 1:
for (d = 2; d < n; d++)
if (n % d == 0)
goto done;
done:
if (d < n)
printf("%d is divisible by %d\n", n, d);
else
printf("%d is prime\n", n);
i = 0; ; j = 1;
3. The Null statement is primarily good for one thing: writing loops whose bodies are empty.
4. Consider the following prime-finding loop:
5. To avoid confusion, C programmers customarily put the Null statement on a line by itself.
6. Accidentally putting a semicolon after the parentheses in an if, while, or for statement creates a Null
statement.
Example 1:
if (d == 0); /*** WRONG ***/
printf("Error: Division by zero\n");
The call of printf isn’t inside the if statement, so it’s performed regardless of whether d is equal to 0.
Example 2:
i = 10;
while (i > 0); /*** WRONG ***/
{
printf("T minus %d and counting\n", i);
--i;
}
The extra semicolon creates an infinite loop
Example 3:
i = 11;
while (--i > 0); /*** WRONG ***/
printf("T minus %d and counting\n", i);