Lesson 6 - Loops in the C language
In the previous exercise, Solved tasks for C lessons 4-5, we've practiced our knowledge from previous lessons.
Lesson highlights
Are you looking for a quick reference on the
for
, while
and do
-while
loops in C instead of a thorough-full lesson? Here it is:
Using a for
loop to execute
code 3
times:
{C_CONSOLE}
int i;
for (i = 0; i < 3; i++) // runs 3 times in total
{
printf("Knock \n");
}
printf("Penny! \n");
{/C_CONSOLE}
Accessing the loop control variable each iteration:
{C_CONSOLE}
int i;
for (i = 1; i <= 10; i++)
printf("%d ", i); // prints the current value of the loop control variable
{/C_CONSOLE}
Nesting loops to work with tabular data:
{C_CONSOLE}
printf("Here's a simple multiplication table using nested loops: \n");
int i, j;
for (j = 1; j <= 10; j++)
{
for (i = 1; i <= 10; i++)
printf("%d ", i * j);
printf("\n");
}
{/C_CONSOLE}
Using a while
loop when we don't know
how many times the code is going to repeat:
double a; double b; int option; double result = 0.0; char goOn = 1; printf("Welcome to our calculator \n"); while (goOn == 1) { printf("Enter the first number: \n"); scanf("%lf", &a); printf("Enter the second number: \n"); scanf("%lf", &b); printf("Choose one of the following operations: \n"); printf("1 - addition \n"); printf("2 - subtraction \n"); printf("3 - multiplication \n"); printf("4 - division \n"); scanf("%d", &option); switch (option) { case 1: result = a + b; break; case 2: result = a - b; break; case 3: result = a * b; break; case 4: result = a / b; break; } if ((option > 0) && (option < 5)) printf("Result: %lf\n", result); else printf("Invalid option \n"); printf("Would you like to make another calculation? [1/0]"); scanf("%d", &goOn); } printf("Thank you for using our calculator. Press any key to end the program. \n");
Using the do
-while
loop when the code is always
executed at least once:
int a; do { scanf("%d", &a); // executed once and then only when the condition remains true } while (a <= 2); // ends once the user enters 3 or larger
Would you like to learn more? A complete lesson on this topic follows.
In the previous tutorial, Solved tasks for C lessons 4-5, we learned about conditions in the C language. In today's lesson, we're going to introduce you all to loops. After today's lesson, we'll have almost covered all of the basic constructs to be able to create reasonable applications.
Loops
The word loop suggests that something is going to repeat. When we want a program to do something 100 times, certainly we'll not write the same code 100x. Instead, we'll put it in a loop. There are several types of loops. We'll explain how to use them, and of course, make practical examples.
The for
loop
This loop has a determined fixed number of steps and
contains a control variable, typically an integer, which changes values
gradually during the loop. The for
loop syntax is the
following:
for (variable; condition; command)
variable
is the control variable which is set to an initial value (usually0
, because in programming, everything starts from zero, never from one). For example:i = 0
. In the C language, we have to prepare the variablei
somewhere before the loop.condition
is the condition for executing the next step of the loop. Once it becomes false, the whole loop is terminated. The condition may be for examplei < 10
.command
tells us what will happen to our variable on every step i.e. whether it should be increased or decreased. We use special++
and--
operators for this. Of course, you can use these operators outside the loop as well, they decrease or increase a variable by1
.
Let's create a simple example, most of us certainly know Sheldon from The Big Bang Theory. For those who don't, we'll simulate a situation where a guy knocks on his neighbor's door. He always knocks 3 times and then yells: "Penny!". Our code, without a loop, would look like this:
{C_CONSOLE}
printf("Knock \n");
printf("Knock \n");
printf("Knock \n");
printf("Penny! \n");
{/C_CONSOLE}
However, using loops, we no longer have to copy the same code over and over:
{C_CONSOLE}
int i;
for (i = 0; i < 3; i++)
{
printf("Knock \n");
}
printf("Penny! \n");
{/C_CONSOLE}
Console application
Knock
Knock
Knock
Penny!
The loop will run through 3 times. At the very beginning, i
is
set to zero, the loop then prints "Knock" and increases i
by one.
It continues in the same way with values one and two. Once i
hits
three, the condition i < 3
is no longer true and the loop
terminates. Loops have the same rules for omitting curly brackets as conditions.
In this case, they may be omitted since the loop contains only one command. Now,
we can simply change value 3
to 10
in the loop
declaration. The command will execute 10x without writing anything extra. Surely
you can see that loops are a very powerful tool.
Now let's put the variable incrementation to use. We'll print the numbers from one to ten and separate them by spaces:
{C_CONSOLE}
int i;
for (i = 1; i <= 10; i++)
printf("%d ", i);
{/C_CONSOLE}
We can see that the control variable has a different value after each
iteration (iteration is one step of the loop). Notice that this time, the loop
doesn't start from zero because we want the initial value to be 1
and the last one to be 10
. Just keep in mind that in programming,
almost everything starts from zero, we'll find out why later.
Now let's print a simple multiplication table that contains multiples of
numbers from 1
to 10
. All we need to do is to declare
a loop from 1
to 10
and multiply the control variable
with the current multiplier. It might look like this:
{C_CONSOLE}
int i;
printf("Here's a simple multiplication table using loops: \n");
for (i = 1; i <= 10; i++)
printf("%d ", i);
printf("\n");
for (i = 1; i <= 10; i++)
printf("%d ", i * 2);
printf("\n");
for (i = 1; i <= 10; i++)
printf("%d ", i * 3);
printf("\n");
for (i = 1; i <= 10; i++)
printf("%d ", i * 4);
printf("\n");
for (i = 1; i <= 10; i++)
printf("%d ", i * 5);
printf("\n");
for (i = 1; i <= 10; i++)
printf("%d ", i * 6);
printf("\n");
for (i = 1; i <= 10; i++)
printf("%d ", i * 7);
printf("\n");
for (i = 1; i <= 10; i++)
printf("%d ", i * 8);
printf("\n");
for (i = 1; i <= 10; i++)
printf("%d ", i * 9);
printf("\n");
for (i = 1; i <= 10; i++)
printf("%d ", i * 10);
printf("\n");
{/C_CONSOLE}
Console application
Simple multiplication table using loops:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
The program works nicely, but we still wrote a lot. Honestly, we could break it down even more since all it does is repeat 10 times while increasing the multiplier. What we'll do is nest the loops (put one inside the other):
{C_CONSOLE}
int j;
int i;
printf("Here's a simple multiplication table using nested loops: \n");
for (j = 1; j <= 10; j++)
{
for (i = 1; i <= 10; i++)
printf("%d ", i * j);
printf("\n");
}
{/C_CONSOLE}
Makes a big difference, doesn't it? Obviously, we can't use i
in
both loops since they are nested and would interfere with themselves. The
variable j
of the outer loop gains the values from 1
to 10
. During each iteration of the loop, another inner loop with
the variable i
is executed. We already know that it'll write the
multiples, in this case, it multiplies by the variable j
. After
each time the inner loop terminates it's necessary to break the line, it is done
by printf("\n")
.
Let's make one more program where we'll practice working with an outer variable. The application will be able to calculate an arbitrary power of an arbitrary number:
{C_CONSOLE}
int i;
int a;
int n;
int result;
printf("Exponent calculator \n");
printf("=================== \n");
printf("Enter the base: \n");
scanf("%d", &a);
printf("Enter the exponent: \n");
scanf("%d", &n);
result = a;
for (i = 0; i < (n - 1); i++)
result = result * a;
printf("Result: %d\n", result);
printf("Thank you for using our exponent calculator \n");
{/C_CONSOLE}
I'm sure we all know how powers (exponents) work. But just to be sure, let me
remind you that, e.g. 2^3 = 2 * 2 * 2
. So, we compute
a^n
by multiplying the number a
by the number
a
n-1
times. Of course, the result must be stored in a
variable. Initially, it'll have a value of a
and this value will be
gradually multiplied during the loop. We can see that our variable
result
in the loop body is accessible. If, however, we create a
variable in a loop body, this variable will no longer be accessible after the
loop terminates.
Console application
Exponent calculator
==========================
Enter the base:
2
Enter the exponent:
3
Result: 8
Thank you for using our exponent calculator
Now, we know what some practical uses of the for
loop are.
Remember that it has a fixed amount of iterations. We shouldn't
modify the control variable from inside the loop since the program could get
stuck in an infinite loop. Here's the last example of what you should not
do:
{C_CONSOLE}
// this code is wrong
int i;
for (i = 1; i <= 10; i++)
i = 1;
{/C_CONSOLE}
Ouch, we can see that the program is stuck. The loop always increments the
variable i
, but it is always set back to 1
. Meaning
that it never reaches values > 10
and the loop never ends. We'll
stop the program using the "Stop" button next to the console window.
The while
loop
The while
loop works differently, it simply repeats the commands
in the block while the condition is true. The syntax of the loop is the
following:
while (condition) { // commands }
If you realized that the for
loop can be simulated using the
while
loop, you are right FOR
is actually a special case of the while
loop. However, the while
loop is used for slightly different
things. Typically, we call some method returning the logical
true
/false
value, in the while loop parentheses. We
could rewrite the original for
-loop example to use the while loop
like this:
{C_CONSOLE}
int i = 1;
while (i <= 10)
{
printf("%d ", i);
i++;
}
{/C_CONSOLE}
However, this is not an ideal example of using the while
loop.
Let's take our calculator from previous lessons and improve it a little bit.
We'll add an ability to enter more math problems. The program will not end
immediately, but it'll ask the user whether he wishes to calculate another math
problem. Let's remind the original version of the code (this is the version with
switch
, but feel free to use the if
-else
version, it depends on you):
{C_CONSOLE}
double a;
double b;
int option;
double result = 0.0;
printf("Welcome to our calculator \n");
printf("Enter the first number: \n");
scanf("%lf", &a);
printf("Enter the second number: \n");
scanf("%lf", &b);
printf("Choose one of the following operations: \n");
printf("1 - addition \n");
printf("2 - subtraction \n");
printf("3 - multiplication \n");
printf("4 - division \n");
scanf("%d", &option);
switch (option)
{
case 1:
result = a + b;
break;
case 2:
result = a - b;
break;
case 3:
result = a * b;
break;
case 4:
result = a / b;
break;
}
if ((option > 0) && (option < 5))
printf("Result: %lf \n", result);
else
printf("Invalid option \n");
printf("Thank you for using our calculator. Press any key to end the program. \n");
{/C_CONSOLE}
Now, we'll put almost all of the code into a while
loop. Our
condition will be that the user enters "1"
, and we'll check the
content of the variable goOn
. This variable is set to
"1"
in the beginning because the program has to begin somehow, then
we assign the user's choice to it:
double a; double b; int option; double result = 0.0; char goOn = 1; printf("Welcome to our calculator \n"); while (goOn == 1) { printf("Enter the first number: \n"); scanf("%lf", &a); printf("Enter the second number: \n"); scanf("%lf", &b); printf("Choose one of the following operations: \n"); printf("1 - addition \n"); printf("2 - subtraction \n"); printf("3 - multiplication \n"); printf("4 - division \n"); scanf("%d", &option); switch (option) { case 1: result = a + b; break; case 2: result = a - b; break; case 3: result = a * b; break; case 4: result = a / b; break; } if ((option > 0) && (option < 5)) printf("Result: %lf\n", result); else printf("Invalid option \n"); printf("Would you like to make another calculation? [1/0]"); scanf("%d", &goOn); } printf("Thank you for using our calculator. Press any key to end the program. \n");
Console application
Welcome to our calculator
Enter the first number:
12
Enter the second number:
128
Choose one of the following operations:
1 - addition
2 - subtraction
3 - multiplication
4 - division
1
Result: 140.000000
Would you like to make another calculation? [1/0]
1
Enter the first number
-10.5
Enter the second number:
The do
-while
loop
The last loop type is do-while
. It's almost identical to
while
, however, the control condition is placed at the end of the
loop. Certainly, this sort of loop will be executed at least once. As an
example, we'll alter our calculator once more to use the do-while
loop. Notice that it's no longer necessary to initialize the value of the
goOn
variable before the loop since the variable is set in the
loop.
double a; double b; int option; double result = 0.0; char goOn = 1; printf("Welcome to our calculator \n"); do { printf("Enter the first number: \n"); scanf("%lf", &a); printf("Enter the second number: \n"); scanf("%lf", &b); printf("Choose one of the following operations: \n"); printf("1 - addition \n"); printf("2 - subtraction \n"); printf("3 - multiplication \n"); printf("4 - division \n"); scanf("%d", &option); switch (option) { case 1: result = a + b; break; case 2: result = a - b; break; case 3: result = a * b; break; case 4: result = a / b; break; } if ((option > 0) && (option < 5)) printf("Result: %lf\n", result); else printf("Invalid option \n"); printf("Would you like to make another calculation? [1/0]"); scanf("%d", &goOn); } while (goOn == 1); printf("Thank you for using our calculator. Press any key to end the program. \n");
The do
-while
loop is not as common as the 2 loops
mentioned before, but it's more handy in certain situations.
Our application can now be used multiple times and is almost complete. Note: this is one of the few codes that cannot be run online since our user bot would have to repeat inputs.
There are a few more things we can do with loops and you'll learn about them further in the course. We don't think it's a good idea to overload you with so much syntax right at the start.
In the next lesson, Solved tasks for C lesson 6, we'll show you how to work with arrays. You've already learned quite a lot! Nothing better than a little noggin exercise, right?
In the following exercise, Solved tasks for C lesson 6, we're gonna practice our knowledge from previous lessons.
Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.
Download
By downloading the following file, you agree to the license terms
Downloaded 2x (217.39 kB)
Application includes source codes in language C