Scripting

Loops in C Language with Examples

In any programming language, loops are part of most of the functions and code that the programmer uses. For example, many text input and output functions consist of repeating loops that read or write the character after the character using basic C functions such as getchar() or putchar(). The C language provides three types of loops, each with properties suited to a particular purpose.

In this Linux Ways article, you will learn everything about loops in C. We will show you each loop, its syntax, and explain how they work. Then, we will put them into practice with code and pictures using the “while”, “do-while”, and “for” statements. We’ll also show you how to create infinite loops for applications and how to use the escape and iteration forced statements.

“While” Loop in C Language

The “while” loop repeats the code that is enclosed in curly braces while the escape condition returns a true result. The escape condition is determined by the result of a relational operation between two or more variables or by a constant and one or more variables and is analyzed at the beginning of each new cycle. When the relational operation returns a result that equals to false, the process is released from the loop. We will see the syntax of the while loop in the following:

while (expresion)

  {

  //code

  }

How to Use the “While” Loop in C Language

In this example, we declare the integer “a” and assign it with the value of 0. This variable has two uses: it is the escape condition and the cycle counter.

Then, we open a “while” loop in which the escape condition is that “a” equals 10. The following expression shows the relational operation which is the escape condition for this example:

while (a != 10)

Inside the loop, we use the printf() function to output the “Cycles elapsed” message, followed by the value of “a”. Using the sleep() function, we set a delay of 1 second and then increment the variable “a” by 1. This cycle is repeated until the variable “a” reaches the value of 10. Lets’ see the following code for this example:

#include <stdio.h>
#include <unistd.h>

void main (){
int a =0;

while (a !=10)
   {
   printf ("Elapsed cycles %i\n", a);
   sleep(1);
   a++;
   }

}

Lets’ see the compilation and execution of this code with the messages issued in each cycle:

“Do-While” Loops in C Language

In certain cases where we use a “while” loop, the escape condition may occur before the program reaches it, preventing an entry into and the execution of the code within. However, there are cases where it is necessary for the code in a loop to execute at least once.

The “do-while” loop analyzes the escape condition at the end of each loop, while the “while” loop does so at the beginning. This guarantees that the program will execute the contained code at least once, whether the escape condition is given or not. Let’s see the following syntax of the “do-while” statement:

do{

//code

}while (expresión);

How to Use the “Do-While” Loop in the C Language

In this example, we’ll show you what actions do the “while” and “do-while” loops perform when the escape condition is specified before entering the loop, so we can compare their effects.

To do this, we create the variable “a”, assign it with the value of 0, and set the relational operation of “a!=0” as the escape condition. Then, we create a “while” loop and a “do-while” loop where we use the printf() function to print a message indicating which loop the program is in. Let’s see the code for this example:

#include <stdio.h>
#include <unistd.h>

void main (){
int a =0;

while (a !=0)
  {
  printf ("Inside the while loop\n");
  }

do {

  printf ("Inside the do-while loop\n");

  }while (a !=0);

}

As we can see in the following image that shows the execution of this code, the given escape condition prevented the program from entering the “while” loop, while it did so in the “do-while” statement and executed the code in it once:

“For” Loop in the C Language

The for” loop works similarly to “while” loop in which its escape condition is determined by the false result of a relational operation and the iteration occurs at the beginning of the loop. Their main feature is that you can declare and initialize a variable in the same statement, perform the relational escape operation, and then operate on the same variable. This makes it very useful when we need to implement a simple loop that does not operate on already declared variables such as timeouts, counters, etc. Let’s see the following syntax for this loop:

for (variable; relational operation; variable operation)

{

//code

}

The first field of this statement can take an already declared variable or declare a variable of any type and assign it with a value. The second field is the relational operation that determines the escape, and the third field performs an operation on the variable. The operation that the “for” loop performs in the third field can be incremental, addition, subtraction, or any other type that is accepted in C. You can also call a function from there to operate on the variable.

How to Use the “For” Loop in the C Language

In this example, we will show you how to use the “for” loop. The characteristics of the loop that we will create are the same as the example that we saw in the “while” statement in which it repeats the code 10 times. Let’s see the following code for this example:

#include <stdio.h>
#include <unistd.h>

void main (){
for (int a =0; a!=10; a++)
  {
    printf ("Elapsed for cycles %i\n", a);
    sleep(1);
  }

}

As we can see in the code, the function that is executed by the loop is the same as the “while” example, except that this statement allows us to create a more organized and reduced code. Let’s see the following image that shows the execution of this code:

The “for” statement also takes a variable and a previously declared value in the first field:

#include <stdio.h>
#include <unistd.h>

int a = 5;
void main (){

for ( a; a!=10; a++)
  {
   printf ("Elapsed for cycles %i\n", a);
   sleep(1);
  }

}

As we can see in the figure, the “for” statement took a variable and an already declared value and thus behaved similarly to the “while” statement.

Nested Loops in the C Language

In the C language, the “while”, “do-while”, and “for” statements can be nested within each other. Let’s see an example with the nesting of two “while” statements with three cycles each. The result is three cycles of the main statement and nine of the nested statement.

#include <stdio.h>
#include <unistd.h>

void main (){
int a =0;
int b;
 
while (a !=3)
    {
        printf ("Elapsed main cycles %i\n", a);
        sleep(1);
        a++;
     b =0;
     while (b !=3)
          {
               printf ("Elapsed nested cycles %i\n", b);
               sleep(1);
               b++;
          }
    }
}

Let’s see the following image with the execution of this nested loop code:

Infinite Loops in the C Language

Most of the user applications that we use on a daily basis consist of code that is wrapped in an infinite loop. This type of loop is usually executed with the “while” statement which uses an operation in the escape expression that always results in true such as (1==1) or simply while(1).

In this way, an infinite loop is created in which the program is not released until the user closes the application with the “Ctrl+c” shortcut key or via the graphical interface.

How to Use Infinite Loops to Create Applications in the C Language

In this example, we will create a simple console application that calculates the sine and cosine of a variable. This application will be enclosed in an infinite loop while(1) and will perform its calculations by having the user input the operation and the variable to be processed via the scanf() function, perform the calculation, and return the result to the screen with printf() function. This cycle repeats infinitely until the user exits the program.

#include <stdio.h>
#include <unistd.h>
#include <math.h>

void main (){
int a;
float b =0;

while (1){
    printf ("Enter the operation you want to perform\nsine  [1]\ncosine  [2]\n");
    scanf("%i", &a);
    printf ("Enter the angle in radians\n");
    scanf("%i", &a);
    if (a == 1)
        printf("The sine is: %f\n\n", sin(b));
    else if (a == 2)
                printf("The cosine is: %f\n\n", cos(b));

    }
}

Let’s see the compilation of this code which calls the mathematical library (-lm) and the execution of this application to calculate the sine and cosine, wrapped in an infinite loop:

Escape Sentence Break in C Conditional Loops

When we use a loop in programming, there are cases where we need to exit it even though the escape condition has not yet been met. This can happen for various reasons such as we no longer need the task that is performed by the loop or we have already obtained the desired result. It may also happen that the escape condition cannot occur for some reason, so the program continues to run indefinitely in the loop.

For these cases, the C language provides the break statement which forces the exit of the loop and can be supplemented with an “if” condition to generate an escape.

How to Use the Break Statement to Force Exit from a Loop in the C Language

In this example, we will see how to use the break statement to force exit from a loop. To do this, we use the code from the previous example and add an “if” condition after the last line of the code inside the loop.

The input condition in this if” condition is also the variable “a” that performs a relational equality operation with a value of 12. In this “if” condition, we open the curly braces and print the “Forced exit” message in it using the printf() function. Then, we execute the break statement and close the curly brace. Let’s see the code for this example:

#include <stdio.h>

#include <unistd.h>

void main (){
int a =0;
 
while (a !=10)
    {
        printf ("Elapsed cycles %i\n", a);
        sleep(1);
        a++;
     if (a == 12)
        {
         printf("Forced exit\n");
         break;
        }
    }
}

The following image shows the execution of this code. As we can see, the forced exit condition was not given because its condition is a=12, while the loop exit condition is a=10:

Now, let’s see what happens when we replace the value of 12 with 6 in the relational operation of the “if” condition:

As we can see in the figure, the forced exit condition occurred before the escape condition of the “while” loop.

Continue Statement in Loops of the C Language

The “continue” statement causes the loop code to iterate from the point at which it is called. When the program encounters this statement, it jumps to the beginning of the loop, analyzes the escape condition, and executes the code again. Let’s see an example where a “while” loop iterates in cases where “a” is less than 3:

#include <stdio.h>

#include <unistd.h>

void main (){
int a =0;
 
while (a !=10)
     {
     a++;
     sleep(1);
     if (a<=3)
        {
        printf ("continue statement: %i\n", a);
        continue;
        }
     printf ("Elapsed cycle: %i\n", a);
     }
}

The following image shows the execution of this code. As we can see, the program jumps to the beginning of the loop when it finds the “continue” statement:

Conclusion

In this complete Linux Ways article, we showed you each of the three conditional loops that the C language provides. We’ve seen a description of each of these statements, showing their syntax, how they work, their properties, and a usage example. We also included two sections that explains how to use the optional forced escape and iteration statements so that you have a complete mastery in the use of these sentences.

Similar Posts