Categories: C

Loops in C

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

Share
Published by
Rabecca Fatima

Recent Posts

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

4 days ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

2 weeks ago

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

3 weeks ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

1 month ago

Longest Substring with K Distinct Characters

Given an integer k and a string s, write a function to determine the length…

1 month ago

Staircase Climbing Ways

There is a staircase with N steps, and you can ascend either 1 step or…

1 month ago