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

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago

Binary Search Tree (BST)

A Binary Search Tree (BST) is a type of binary tree that satisfies the following…

1 year ago