-
Notifications
You must be signed in to change notification settings - Fork 0
section5_loops
Loops are useful to repeat a specific block of code until some condition is reached. There are different types of loops, as you will see.
This loop is a good choice when the number of repetitions is known, or can be supplied by the user.
for(initialization statement; test expression; update statement)
{
// do something
}
- The
initialization statement
only runs once, when the loop starts. - The
test expression
is evaluated at the beginning of every loop cycle. If it evaluates true (1), the statements of thefor
body are executed. Otherwise, the loop ends. - At the end of each loop cycle, the
update statement
it's executed.
Let's see an example. Imagine you want to print numbers from 1 all the way to 10. Instead of doing it manually, you can use a for
loop.
#include "stdio.h"
int main()
{
int i;
for(i = 1; i <= 10; i++)
{
printf("%d ", i);
}
}
// OUTPUT: 1 2 3 4 5 6 7 8 9 10
- The variable
i
is initialized with the number 1. This is the initialization statement. -
- Now the test expression
i <= 10
is evaluated. 1 is less/equal than 10, so the expression is true. Therefore, thefor
body statements will run and the number 1 is displayed on the console. - Next, the update statement is executed.
i++
is the same asi = i + 1
. So, now thei
value is 2. The first loop cycle is completed.
- Now the test expression
-
- This is the second loop. The text expression is evaluated again. 2 is less/equal than 10, so the
for
body statements are executed. - The update statement is executed once more and
i
value becomes 3.
- This is the second loop. The text expression is evaluated again. 2 is less/equal than 10, so the
Note: Before C99 it was not possible to declare variables inside the for
statement. That's why in the example above the variable i
is declared before and initialized inside. If you compiling code for C99 or C11 you are allowed to use for(int i = 0; ...)
.
On the last loop, i
is 10, the test statement is true and the printf
is executed. After the update statement i
becomes 11. Next, the test expression evaluates to false, because 11 is NOT less/equal than 10. Therefore, the for
loop ends.
A while loop is a mechanism for repeating a set of statements as long as a specified logical expression evaluates to true. The while loop syntax in general is:
while(test expression)
{
// do something
}
The test expression is evaluated at the beginning of every loop cycle. If it evaluates true (1), the statements of the while
body are executed. Otherwise, the loop ends.
Note: There's no explicit update expression like in for
loop. So, depending on your test expression, don't forget to update variables inside the while
body. Otherwise, you will end up with a infinite loop. Notice in the example below, the variable a
is initialized with the value 10 which is higher than 0, thus the expression is a > 0
is true. The variable is not changed inside the loop body, thus it will never end.
int a = 10;
while(a > 0) {
printf("hello darkness my old friend\n");
}
#include "stdio.h"
int main()
{
unsigned int num, i_num = 0;
printf("Insert a number ? ");
scanf("%u", &num);
while(num > 0)
{
i_num = i_num*10 + num%10;
num /= 10;
}
printf("i_num = %u", i_num);
}
//OUTPUT
//Insert a number ? 123456
//i_num = 654321
The above code asks the user for a number and will output the same number but inverted. If the input is 123, num
is initialized with 123.
-
123 > 0
is true, so thewhile
body statements are executed.i_num
was initialized with 0, before the while loop. With the first statement,i_num = i_num*10 + num%10
=>i_num = 0*10 + 123%10
=>i_num = 3
. The second statement changes thenum
value, which is used as test statement for thewhile
loop.num
becomes 12 (integer division). The first loop is completed. - The test statement is evaluated.
12 > 0
is true! The statements inside thewhile
are executed.i_num = 3*10 + 12%10
=>i_num = 30 + 2
=>i_num = 32
. The second statement updatesnum
, which now is 1. - Third loop. The test statement is still true, because 1 is higher than 0. After the two statements inside
while
,i_num
becomes 321, andnum
is 0. - This time, the test statement is evaluated to false. Hence, the loop ends.
The do ... while
loop is similar to while
. The difference is that do ... while
loops always run at least once. First, the statements inside do
body are executed, and then test expression inside while
is evaluated before the next loop. In a pure while
loop, the test statement is evaluated first, therefore the statements inside while
might never run.
do {
// statements
} while (test_expression); // notice the semicolon
#include "stdio.h"
int main()
{
int sum = 0, n;
printf("Insert numbers to sum (insert 0 to show the result)\n");
do
{
printf("Enter a number: ");
scanf("%d", &n);
sum += n;
} while(n != 0);
printf("Total: %d", sum);
}
/*
OUTPUT
Insert numbers to sum (insert 0 to show the result)
Enter a number: 2
Enter a number: 3
Enter a number: 5
Enter a number: 0
Total: 10
*/
This example asks the user to insert numbers and adds them until the user enters a 0, as a way for the user to tell he doesn't pretend to insert further numbers. We will always ask the user for input at least once, so using a do...while
loop is more suitable than using while
, altough this program is possible using any loop. It's a matter of knowing what suits best for the task. Inside the do
body, we show a message, read user input and add the new input to sum
variable. Then, the variable n
, the latest user input, is tested and checked if it's different from 0. If it is, a new loop is started. Otherwise, the loop stops and the result is shown with the printf
statement following the do...while
.
There's an important note about do...while
loops related with variable scoopes. Variables declared inside the do
body are only visible inside the do
body and can't be used in the test expression. Below is an example equal to the above, but the auxiliar variable n
is declared inside the do
body. Compiling the code will result in an error, reporting the variable n
is not declared for the while(n != 0)
expression.
#include "stdio.h"
int main()
{
int sum = 0;
printf("Insert numbers to sum (insert 0 to show the result)\n");
do {
int n;
printf("Enter a number: ");
scanf("%d", &n);
sum += n;
} while(n != 0);
printf("Total: %d", sum);
}
- Write a program that reads a number and displays the sum of its digits. For example, for the number 123 the program should display 6 (1+2+3).
Insert a number ? 1234500
Sum of digits: 15
- Write a program that asks a number and prints its factors. Consider the simplest way to calculate the factors. Start with numbers higher than 1 until numbers less than the inserted number.
Number ? 25830
Factors : 2 3 3 5 7 41
- Write a program that calculates the average grade of students in a class. The program must ask the number of students and then request each grade.
Number of students ? 5
Grade ? 17
Grade ? 15
Grade ? 6
Grade ? 6
Grade ? 10
Average grade is 10.800000
Soon...