How can I write in order with for loop or while loop?

In C programming, we can create ordered patterns using for loops or while loops. This example demonstrates how to generate a specific numerical pattern where each line contains repeating digits based on the line number.

Syntax

for(initialization; condition; increment) {
    // loop body
}

while(condition) {
    // loop body
    increment;
}

Method 1: Using For Loop

This approach uses nested for loops to create a pattern where each line displays the line number followed by repeating 0s and 1s −

#include <stdio.h>

int main() {
    int i, j, a = 0, b = 1, n;
    
    printf("Enter the value of n: ");
    scanf("%d", &n);
    printf("\nThe required order is:<br><br>");
    
    for(i = 1; i <= n; i++) {
        if(i == 1) {
            printf("%d. E", i);
        } else {
            printf("%d. ", i);
            
            // Print 0s (i-1 times)
            for(j = 1; j <= i-1; j++) {
                printf("%d", a);
            }
            
            // Print 1s (i-1 times)  
            for(j = 1; j <= i-1; j++) {
                printf("%d", b);
            }
        }
        printf("<br>");
    }
    
    return 0;
}
Enter the value of n: 5

The required order is:

1. E
2. 01
3. 0011
4. 000111
5. 00001111

Method 2: Using While Loop

The same pattern can be achieved using while loops for better understanding of loop control −

#include <stdio.h>

int main() {
    int i = 1, j, a = 0, b = 1, n;
    
    printf("Enter the value of n: ");
    scanf("%d", &n);
    printf("\nThe required order is:<br><br>");
    
    while(i <= n) {
        if(i == 1) {
            printf("%d. E", i);
        } else {
            printf("%d. ", i);
            
            // Print 0s using while loop
            j = 1;
            while(j <= i-1) {
                printf("%d", a);
                j++;
            }
            
            // Print 1s using while loop
            j = 1;
            while(j <= i-1) {
                printf("%d", b);
                j++;
            }
        }
        printf("<br>");
        i++;
    }
    
    return 0;
}
Enter the value of n: 4

The required order is:

1. E
2. 01
3. 0011
4. 000111

How It Works

  • The outer loop controls the line number from 1 to n
  • For line 1, it prints "E" as a special case
  • For other lines, it prints (i-1) zeros followed by (i-1) ones
  • The pattern creates an increasing sequence of 0s and 1s

Conclusion

Both for loops and while loops can effectively create ordered patterns in C. The choice between them depends on preference, though for loops are more concise for counter-based iterations.

Updated on: 2026-03-15T09:49:33+05:30

310 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements