Loops in C

  • February 24, 2022
  • C
Matrix multiplication

The programs that we have created so far were of limited nature, because on execution, they always perform the same series of actions, in the same way exactly once. Therefore, for times when we need repetitive action, then we make use of loops.

Loops in C:

In C programming language the repetitive operation is done through loop control instruction. There are three methods by which we can repeat a part of a program. They are:

  • for statement
  • while statement
  • do-while statement
The for loop:

The for loop allows us to specify three things about a loop in a single line:

  • Initialization: A loop counter to an initial value.
  • Condition: Testing the loop counter to determine whether its value has reached the number of repetitions desired.
  • Updation: Increasing the value of the loop counter each time the program segment within the loop has been executed.
Syntax:
for(initilization ; condition ; updation)
{ 
    //statement1
    //statement2
}
Flowchart for the for loop:
Example: Table of 5
//Table of 5 
int main() {
    int n=5,i=1;
    for(i=1;i<=10;i++)
    {
        printf("\n%d * %d = %d",n,i,(n*i));
    }
    
    return 0;
}
Output:
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50

In the above example we used a for loop to calculate the table of 5, which is much more efficient by repeating the print statement inside the loop with initialization as 1, condition as ‘i’ should be less than or equal to 10 and updating as increment by 1.

Note: also read about  Format specifiers in C & Decision-Making in C

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Leave a Reply

Your email address will not be published. Required fields are marked *