Loop in c programming

Loops are the heart and soul of programming, serving as the backbone for performing repetitive tasks and iterating through data. In C programming, loops enable developers to streamline their code, enhance efficiency, and bring versatility to their programs. In this guide, we’ll delve into the world of loops in C programming, exploring different types of loops, their syntax, use cases, and best practices. By the end of this journey, you’ll have a solid grasp of how to harness the power of loops to create elegant and efficient programs.

Loops provide a mechanism for executing a block of code multiple times, offering efficiency and reducing redundancy in programming tasks. In C programming, three primary loop types are at your disposal: for, while, and do-while.

A loop consists of three essential components: initialization, condition, and iteration. These components work together to control the repetition of a code block.

for loop in c

The for loop is a versatile and fundamental construct in the realm of programming. It empowers developers to perform repetitive tasks with elegance and efficiency, allowing code to be executed multiple times while maintaining readability and simplicity. The for loop is a foundational programming construct that facilitates the repetition of a specific block of code a predetermined number of times. Its structure is concise and powerful, making it a staple in various programming tasks.

Structure of for loop in c

A for loop consists of three primary components: initialization, condition, and iteration. These components collaborate harmoniously to control the flow of execution and ensure the loop performs as desired.

Initialization: –

The initialization step defines the starting point of the loop. It sets the initial value of the loop counter or variable that will be used to track the number of iterations.

Condition: –

The loop condition is the gatekeeper of the loop’s execution. It specifies the condition that must be true for the loop to continue running. Once this condition evaluates to false, the loop terminates.

Iteration (increment or decrement):

The increment or decrement step dictates how the loop counter is modified after each iteration. This step ensures that the loop counter changes, moving closer to the termination condition.

Working of for loop in c: –

A for loop follows a sequential execution pattern. It begins with the initialization step, proceeds to evaluate the loop condition, executes the loop’s body if the condition is true, performs the iteration step, and then repeats the process until the loop condition becomes false.

for loop in c

Syntax: –

for (//Initialization, condition, increment or decrement)

 {

    //block of code//

 }

Common Use Cases for the for Loop: –
  •  Generating Number Sequences
    The for loop is ideal for generating sequences of numbers, whether for indexing, calculations, or display purposes.
  • Iterating Through Arrays
    When working with arrays, the for loop simplifies the process of accessing and manipulating array elements.
  • Data Processing and Analysis
    For processing large datasets, performing calculations, or aggregating results, the for loop is a powerful tool.

Write a program to print numbers in a sequence by using for loop in c: –

#include <stdio.h>
#include <conio.h>

void main() {
    clrscr();
	int i;
    // Print numbers from 1 to 10 using a for loop
    for (i = 1; i <= 10; i++) {
        printf("%d ", i);
    }

    getch();
}

Output: -
1 2 3 4 5 6 7 8 9 10

[program terminated]

Write a program to find factorial of a number by for loop in c: –

#include <stdio.h>
#include <conio.h>

void main() {
    int num, factorial = 1;
    clrscr();
    printf("Enter a number: ");
    scanf("%d", &num);

    // Calculate factorial using a for loop
    for (int i = 1; i <= num; i++) {
        factorial *= i;
    }

    printf("Factorial of %d is %d\n", num, factorial);

    getch();
}
Output: -
Enter a number: 5
Factorial of 5 is 120

[program terminated]

Write a program to print table of a given number by for loop in c: –

#include <stdio.h>
#include <conio.h>

void main() {
    int num;
    clrscr();

    printf("Enter a number: ");
    scanf("%d", &num);

    // Print multiplication table using a for loop
    for (int i = 1; i <= 10; i++) {
        printf("%d x %d = %d\n", num, i, num * i);
    }

    getch();
}
Output: -
Enter a number: 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

[program terminated]

Nested for loop in c

Nested for loops are loops within loops, where one loop is placed inside another. This programming technique is used to perform repetitive tasks with multiple levels of iteration. Nested loops are particularly useful for working with multi-dimensional data structures, creating patterns, and performing complex operations. Here’s a detailed explanation of nested for loops:

Structure of nested for loop in c

The structure of a nested for loop consists of one or more outer loops and one or more inner loops. Each loop operates independently, but they are executed in a specific order, creating a multi-level iteration process.

for (outer_initialization; outer_condition; outer_increment) {

    for (inner_initialization; inner_condition; inner_increment) {

        // Code to be executed in the inner loop

    }

    // Code to be executed after the inner loop

}

Working of nested for loop: –
  • The outer loop’s initialization, condition, and increment are evaluated.
  • If the outer loop’s condition is true, the inner loop is entered.
  • The inner loop’s initialization, condition, and increment are evaluated.
  • If the inner loop’s condition is true, the code within the inner loop is executed.
  • Once the inner loop completes its iterations, the inner loop’s increment is executed.
  • The inner loop’s condition is checked again, and the process repeats until the condition becomes false.
  • After the inner loop finishes, the outer loop’s increment is executed.
  • The outer loop’s condition is checked again, and the process repeats until the condition becomes false.
Use Cases for Nested for Loops: –
  • Patterns:
    Nested loops can be used to print patterns of characters, numbers, or symbols, like triangles, rectangles, and pyramids.
  • Multi-dimensional Arrays:
     When working with multi-dimensional arrays (arrays within arrays), nested loops are used to access and manipulate individual elements efficiently.
  • Matrix Operations:
     Nested loops can perform operations like matrix multiplication, finding the transpose, or calculating the sum of elements in a matrix.
  • Data Processing:
     For data analysis tasks, nested loops are used to iterate through rows and columns of data to perform calculations or aggregations.

Write a program to print right angled triangle pattern by using nested for loop in c: –

#include <stdio.h>
#include <conio.h>

void main() {
    int rows = 5;
    clrscr();
    // Outer loop controls the number of rows
    for (int i = 1; i <= rows; i++) {
        // Inner loop prints '*' characters for each row
        for (int j = 1; j <= i; j++) {
            printf("* ");
        }
        printf("\n");
    }

    getch();
}
Output: -
*
* *
* * *
* * * *
* * * * *

[program terminated]

Write a program to print inverted right angled triangle pattern by using nested for loop in c: –

#include <stdio.h>
#include <conio.h>

void main() {
    int rows = 5;
    clrscr();
    // Outer loop controls the number of rows
    for (int i = row; i >= 1; i--) {
        // Inner loop prints '*' characters for each row
        for (int j = 1; j <= i; j++) {
            printf("* ");
        }
        printf("\n");
    }

    getch();
}
Output: -
* * * * *
* * * *
* * *
* * 
* 

[program terminated]

Write a program to print pyramid pattern by using nested for loop in c: –

#include <stdio.h>
#include <conio.h>

void main() {
    int rows = 5, spaces;
    clrscr();
    // Outer loop controls the number of rows
    for (int i = 1; i <= rows; i++) {
        // Print spaces before the '*' characters
        for (spaces = 1; spaces <= rows - i; spaces++) {
            printf("  ");
        }

        // Inner loop prints '*' characters for each row
        for (int j = 1; j <= 2 * i - 1; j++) {
            printf("* ");
        }

        printf("\n");
    }

    getch();
}
Output: -
         * 
      * * * 
    * * * * * 
  * * * * * * * 
* * * * * * * * *

[program terminated]

While loop in c

The while loop is a fundamental control structure in C programming that allows you to repeatedly execute a block of code as long as a specified condition remains true. This loop is particularly useful when the number of iterations is not known in advance or when you want to perform tasks until a certain condition is met.

while loop in c

Structure of a while Loop in c: –

The structure of a while loop consists of a loop condition and a block of code. The loop condition is checked before each iteration. If the condition is true, the code within the loop is executed. If the condition is false, the loop is terminated, and program control moves to the next statement after the loop.

while (condition) {

    // Code to be executed while the condition is true

}

Working of while Loop in c: –
  • The loop condition is evaluated initially. If it’s true, the code block inside the loop is executed.
  • After the code block executes, the loop condition is evaluated again.
  • If the condition remains true, the code block executes again, and this process continues.
  • If the condition becomes false, the loop terminates, and the program control moves to the next statement after the loop.
Use Cases for the while Loop in c: –
  1. Input Validation:
    Use a while loop to repeatedly prompt the user for input until valid data is provided.
  2. Dynamic Iteration:
     When the number of iterations is determined by user input or data conditions, the while loop is suitable.
  3. Tasks with Unknown Iteration:
     If the exact number of iterations isn’t known in advance, the while loop allows you to perform tasks until a certain condition is satisfied.
#include <stdio.h>
#include <conio.h>

void main() {
    int num = 1;
    clrscr();

    // Print numbers from 1 to 5 using a while loop
    while (num <= 5) {
        printf("%d ", num);
        num++;
    }

    getch();
}
Output: -
1 2 3 4 5
[program terminated]

In this example, the loop condition num <= 5 is checked before each iteration. As long as the condition remains true, the loop continues to print numbers and increment the num variable.

Write a program to print even number by using while loop in c: –

#include <stdio.h>
#include <conio.h>

void main() {
    int num = 2;
    clrscr();
    // Print even numbers from 2 to 20 using a while loop
    while (num <= 20) {
        printf("%d ", num);
        num += 2;
    }

    getch();
}
Output: -
 2 4 6 8 10 12 14 16 18 20

[program terminated]

Write a program to calculate sum of digits by using while loop in c: –

#include <stdio.h>
#include <conio.h>

void main() {
    int num, originalNum, sum = 0;
    clrscr();
    printf("Enter a positive integer: ");
    scanf("%d", &num);
    originalNum = num;

    // Calculate the sum of digits using a while loop
    while (num > 0) {
        int digit = num % 10;
        sum += digit;
        num /= 10;
    }

    printf("\nSum of digits of %d is %d\n", originalNum, sum);

    getch();
}
Output: -
Enter a positive integer: 4323
Sum of digits of 4323 is 12
[program terminated]

Difference between for loop and while loop in c

Following are the difference between for loop and while loop
Aspectfor Loop while loop
StructureExplicitly defines initialization, condition, andOnly requires a loop condition, and the initial
increment/decrement steps within the loop header.value is initialized outside the loop.
Use CaseIdeal when the number of iterations is knownSuitable when the exact number of iterations is
beforehand.not known in advance.
Iteration ControlMore control over initialization, condition, andDirectly controlled by the loop condition, which
increment/decrement steps.is checked before each iteration.
ExamplesPrinting numbers, iterating through arrays,Input validation, reading data until a certain
calculating sums.condition is met.
FlexibilityMay be more concise and suitable for tasks withHighly flexible for tasks that require dynamic
well-defined iteration steps.iterations or custom iteration logic.
InitializationRequires initialization of loop control variableLoop control variable is initialized before the
within the loop header.loop, outside the loop.
Increment/DecrementIncrement or decrement steps are defined withinIncrement or decrement steps are usually
Stepsthe loop header.defined within the loop block.
Condition CheckingCondition is checked before each iteration.Condition is checked before each iteration.
Visibility ofLoop control variable is typically visible onlyLoop control variable is usually more visible,
Loop Controlwithin the loop header.and its scope extends beyond the loop.

do while loop in c

The do-while loop in c is a looping construct in C programming that allows you to repeatedly execute a block of code at least once and then continue to execute it as long as a specified condition remains true. This loop is particularly useful when you want to ensure that the code block is executed at least once, regardless of the initial condition.

Structure of a do-while Loop in c

The structure of a do-while loop consists of a loop body, a condition, and the do keyword. The loop body is executed first, and then the loop condition is checked. If the condition is true, the loop body is executed again. If the condition is false, the loop terminates, and program control moves to the next statement after the loop.

do {

    // Code to be executed at least once

} while (condition);

do while loop in c
Working of do-while Loop: –
  1. The code block within the do is executed first.
  2. After the code block executes, the loop condition is evaluated.
  3. If the condition is true, the loop body is executed again, and this process continues.
  4. If the condition becomes false, the loop terminates, and the program control moves to the next statement after the loop.
Use Cases for the do-while Loop: –
  1. Menu-Driven Programs:
    When building interactive programs with menus, the do-while loop ensures that the menu is displayed at least once, allowing users to make choices repeatedly.
  2. Input Validation:
    Use a do-while loop to repeatedly prompt the user for input until valid data is provided.
  3. Dynamic Iteration:
    When you want to perform a task multiple times based on user input or conditions, the do-while loop is suitable.

Write a program to print Fibonacci series of number by using do while loop in c: –

#include <stdio.h>
#include <conio.h>

void main() {
    int n, first = 0, second = 1, next;
    clrscr();
    printf("Enter the number of terms in the Fibonacci series: ");
    scanf("%d", &n);

    printf("\nFibonacci Series: %d, %d, ", first, second);

    int count = 2;
    do {
        next = first + second;
        printf("%d, ", next);
        first = second;
        second = next;
        count++;
    } while (count < n);

    getch();
}
Output: -
Enter the number of terms in the Fibonacci series: 10
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
[program terminated]

Write a program to swap two number by using do while loop in c: –

#include <stdio.h>
#include <conio.h>

void main() {
    int num1=23, num2=54, temp;
    clrscr();

    printf("Enter the first number: ");
    scanf("%d", &num1);

    printf("\nEnter the second number: ");
    scanf("%d", &num2);

    // Swapping using a do-while loop
    do {
        temp = num1;
        num1 = num2;
        num2 = temp;
    } while (0);

    printf("\nAfter swapping:\n");
    printf("First number: %d\n", num1);
    printf("Second number: %d\n", num2);

    getch();
}
Output: -
Enter the first number: 24
Enter the second number: 54
After swapping:
First number: 54
Second number: 24
[program terminated]

Frequently Asked Questions (FAQ) guide on loop in C programming!

Q1: What are loop in C programming?
Loops are control structures that allow you to repeat a certain block of code multiple times. They’re used to automate repetitive tasks in your program.

Q2: What types of loops are available in C?
C provides three types of loops: for, while, and do-while.

Q3: How does the for loop work?
The for loop has three components: initialization, condition, and increment/decrement. It repeatedly executes the code block as long as the condition is true.

Q4: What’s the purpose of the while loop in c?
The while loop repeatedly executes a block of code as long as the given condition remains true. Unlike the for loop, it only requires the condition.

Q5: What is the do-while loop in c?
The do-while loop is similar to the while loop, but the condition is evaluated after the code block is executed. This ensures that the block executes at least once.

Q6: Can I use nested loop in C?
Absolutely! You can have loops within loops. This is useful for handling complex patterns or working with multi-dimensional arrays.

Q7: What’s the break statement’s role in loops?
The break statement immediately exits the loop, regardless of whether the loop’s condition is satisfied.

Q8: How does the continue statement work?
The continue statement skips the rest of the current iteration and jumps to the next iteration of the loop.

Q9: Are there any common mistakes to watch out for with loops?
Sure, a common mistake is forgetting to update the loop control variable within the loop body, which might lead to infinite loops. Also, ensure your loop conditions are appropriately defined to avoid unintended behaviors.

Q10: Is there a limit to loop nesting?
Technically, there’s no hard limit, but excessive nesting can make your code difficult to read and maintain. It’s generally recommended to keep nesting levels reasonable.


Read more about c programming: –
Data type and Operator in C programming: – https://xcoode.co.in/c_programming/data-type-and-operators-in-c/
if-else statements in C programming: – https://xcoode.co.in/c_programming/if-else-statement-in-c/

Follow us on: –
Facebook page: –https://www.facebook.com/groups/294849166389180
Quora: – https://xcoode404.quora.com/

By Admin

2 thoughts on “Loop in C”

Leave a Reply

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