Lab-5: Loops in C Programming

Experiment 3.2: Advanced Loop Applications

Dr. Mohsin Dar | Assistant Professor | Cloud & Software Operations Cluster | SOCS | UPES

📚 Theory: Understanding Loops

What are Loops?

Loops are programming constructs that allow us to execute a block of code repeatedly based on a condition. In C programming, we have three main types of loops:

Loop Type Syntax When to Use
for loop for(init; condition; increment) When number of iterations is known
while loop while(condition) When condition is checked before execution
do-while loop do { } while(condition) When block must execute at least once
🧪 Experiment 1: Number Classification Counter
Objective: Write a program to enter numbers till the user wants. At the end, display the count of positive, negative, and zero numbers entered.

Algorithm:

  1. Initialize counters for positive, negative, and zero numbers
  2. Use a loop to continuously input numbers
  3. For each number, classify and increment appropriate counter
  4. Ask user if they want to continue
  5. Display final counts
// Program to count positive, negative, and zero numbers
#include <stdio.h>

int main() {
    int num, positive = 0, negative = 0, zeros = 0;
    char choice;
    
    printf("=== Number Classification Program ===\n");
    
    do {
        printf("Enter a number: ");
        scanf("%d", &num);
        
        // Classify the number
        if (num > 0) {
            positive++;
            printf("Positive number detected!\n");
        } else if (num < 0) {
            negative++;
            printf("Negative number detected!\n");
        } else {
            zeros++;
            printf("Zero detected!\n");
        }
        
        printf("Do you want to enter another number? (y/n): ");
        scanf(" %c", &choice);
        
    } while (choice == 'y' || choice == 'Y');
    
    // Display results
    printf("\n=== FINAL RESULTS ===\n");
    printf("Total Positive numbers: %d\n", positive);
    printf("Total Negative numbers: %d\n", negative);
    printf("Total Zeros entered: %d\n", zeros);
    printf("Total numbers entered: %d\n", positive + negative + zeros);
    
    return 0;
}
Sample Output:
=== Number Classification Program ===
Enter a number: 5
Positive number detected!
Do you want to enter another number? (y/n): y
Enter a number: -3
Negative number detected!
Do you want to enter another number? (y/n): y
Enter a number: 0
Zero detected!
Do you want to enter another number? (y/n): n

=== FINAL RESULTS ===
Total Positive numbers: 1
Total Negative numbers: 1
Total Zeros entered: 1
Total numbers entered: 3
🧪 Experiment 2: Multiplication Table Generator
Objective: Write a program to print the multiplication table of a number with proper formatting (Num * 1 = Result).
// Program to generate multiplication table
#include <stdio.h>

int main() {
    int num, range;
    
    printf("=== Multiplication Table Generator ===\n");
    printf("Enter the number for multiplication table: ");
    scanf("%d", &num);
    
    printf("Enter the range (how many multiples): ");
    scanf("%d", &range);
    
    printf("\n=== Multiplication Table of %d ===\n", num);
    printf("================================\n");
    
    // Generate multiplication table using for loop
    for (int i = 1; i <= range; i++) {
        printf("%2d * %2d = %3d\n", num, i, num * i);
    }
    
    printf("================================\n");
    
    return 0;
}
Sample Output:
=== Multiplication Table Generator ===
Enter the number for multiplication table: 7
Enter the range (how many multiples): 10

=== Multiplication Table of 7 ===
================================
 7 *  1 =   7
 7 *  2 =  14
 7 *  3 =  21
 7 *  4 =  28
 7 *  5 =  35
 7 *  6 =  42
 7 *  7 =  49
 7 *  8 =  56
 7 *  9 =  63
 7 * 10 =  70
================================
🧪 Experiment 3: Pattern Generation
Objective: Generate two different numerical patterns using nested loops.

Pattern A: Number Triangle

1 2 3 4 5 6 7 8 9 10
// Program for Pattern A: Number Triangle
#include <stdio.h>

int main() {
    int i, j, space, rows;
    int num = 1;

    printf("Enter number of rows: ");
    scanf("%d", &rows);

    for (i = 1; i <= rows; i++) {
        // Print leading spaces
        for (space = 1; space <= rows - i; space++) {
            printf(" ");
        }
        // Print numbers in each row
        for (j = 1; j <= i; j++) {
            printf("%d ", num);
            num++;
        }
        printf("\n");
    }

    return 0;
}

Pattern B: Pascal's Triangle

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
// Program for Pattern B: Pascal's Triangle
#include <stdio.h>

int main() {
    int rows;
    
    printf("Enter number of rows for Pascal's Triangle: ");
    scanf("%d", &rows);
    
    printf("\nPattern B: Pascal's Triangle\n");
    printf("============================\n");
    
    for (int i = 0; i < rows; i++) {
        int coeff = 1;
        
        // Print spaces for proper alignment
        for (int space = 1; space < rows - i; space++) {
            printf(" ");
        }
        
        // Print Pascal's triangle coefficients
        for (int j = 0; j <= i; j++) {
            if (j == 0 || i == 0) {
                coeff = 1;
            } else {
                coeff = coeff * (i - j + 1) / j;
            }
            printf("%d ", coeff);
        }
        printf("\n");
    }
    
    return 0;
}
🧪 Experiment 4: Population Growth Calculator
Objective: Calculate population growth over the last decade with a 10% annual increase, starting from 100,000.
Mathematical Formula: New Population = Previous Population × (1 + growth_rate)
Where growth_rate = 10% = 0.10
// Program to calculate population growth
#include <stdio.h>

int main() {
    double population = 100000.0;  // Initial population
    double growth_rate = 0.10;      // 10% growth rate
    int years = 10;
    
    printf("=== Population Growth Analysis ===\n");
    printf("Initial Population: %.0f\n", population);
    printf("Annual Growth Rate: %.1f%%\n", growth_rate * 100);
    printf("Time Period: %d years\n\n", years);
    
    printf("Year\t\tPopulation\t\tIncrease\n");
    printf("====================================================\n");
    
    // Display initial population
    printf("Start (Year 0)\t%.0f\t\t\t-\n", population);
    
    // Calculate population for each year
    for (int year = 1; year <= years; year++) {
        double previous_population = population;
        population = population * (1 + growth_rate);
        double increase = population - previous_population;
        
        printf("Year %-10d%.0f\t\t\t+%.0f\n", year, population, increase);
    }
    
    printf("====================================================\n");
    printf("Total Growth: %.0f (%.1f%% increase)\n", 
           population - 100000, ((population - 100000) / 100000) * 100);
    
    return 0;
}
Sample Output:
=== Population Growth Analysis ===
Initial Population: 100000
Annual Growth Rate: 10.0%
Time Period: 10 years

Year		Population		Increase
====================================================
Start (Year 0)	100000			-
Year 1         	110000			+10000
Year 2         	121000			+11000
Year 3         	133100			+12100
Year 4         	146410			+13310
Year 5         	161051			+14641
Year 6         	177156			+16105
Year 7         	194872			+17716
Year 8         	214359			+19487
Year 9         	235795			+21436
Year 10        	259374			+23579
====================================================
Total Growth: 159374 (159.4% increase)
🧪 Experiment 5: Ramanujan Numbers
Objective: Find all Ramanujan numbers up to a given limit. A Ramanujan number can be expressed as the sum of two cubes in two different ways.
Example: 1729 = 1³ + 12³ = 9³ + 10³
This makes 1729 a Ramanujan number (also known as Hardy-Ramanujan number).

Algorithm:

  1. Set a reasonable upper limit for search
  2. For each number, find all possible ways to express it as sum of two cubes
  3. If a number can be expressed in at least 2 different ways, it's a Ramanujan number
  4. Display all such numbers with their cube combinations
// Program to find Ramanujan Numbers
#include <stdio.h>
#include <math.h>

int main() {
    int limit;
    int found = 0;
    
    printf("=== Ramanujan Number Finder ===\n");
    printf("Enter the limit to search for Ramanujan numbers: ");
    scanf("%d", &limit);
    
    printf("\nSearching for Ramanujan numbers up to %d...\n\n", limit);
    
    // Check each number up to the limit
    for (int n = 1; n <= limit; n++) {
        int ways = 0;
        int pairs[10][2];  // Store up to 10 pairs
        
        // Find all ways to express n as sum of two cubes
        for (int i = 1; i * i * i < n; i++) {
            for (int j = i; i * i * i + j * j * j <= n; j++) {
                if (i * i * i + j * j * j == n) {
                    pairs[ways][0] = i;
                    pairs[ways][1] = j;
                    ways++;
                    if (ways >= 10) break; // Prevent overflow
                }
            }
            if (ways >= 10) break;
        }
        
        // If number can be expressed in 2 or more ways, it's Ramanujan
        if (ways >= 2) {
            found++;
            printf("Ramanujan Number #%d: %d\n", found, n);
            
            for (int k = 0; k < ways; k++) {
                int a = pairs[k][0], b = pairs[k][1];
                printf("  %d³ + %d³ = %d + %d = %d\n", 
                       a, b, a*a*a, b*b*b, n);
            }
            printf("\n");
        }
    }
    
    if (found == 0) {
        printf("No Ramanujan numbers found up to %d.\n", limit);
        printf("Try increasing the limit to at least 2000.\n");
    } else {
        printf("Total Ramanujan numbers found: %d\n", found);
    }
    
    return 0;
}
Sample Output (with limit 2000):
=== Ramanujan Number Finder ===
Enter the limit to search for Ramanujan numbers: 2000

Searching for Ramanujan numbers up to 2000...

Ramanujan Number #1: 1729
  1³ + 12³ = 1 + 1728 = 1729
  9³ + 10³ = 729 + 1000 = 1729

Total Ramanujan numbers found: 1
📋 Lab Summary & Key Concepts

Key Programming Concepts Covered:

  • Loop Control Structures: for, while, do-while loops
  • Nested Loops: Using loops within loops for pattern generation
  • Counter Variables: Tracking and counting different categories
  • Mathematical Calculations: Population growth, cube calculations
  • Pattern Recognition: Number sequences and mathematical patterns
  • Algorithm Design: Breaking complex problems into steps
  • Input Validation: Handling user choices and continuous input

Loop Selection Guidelines:

  • Use FOR loops when you know the exact number of iterations
  • Use WHILE loops when the condition is checked before execution
  • Use DO-WHILE loops when the code block must execute at least once

Common Loop Patterns:

Pattern Type Application Example
Counter Loop Counting occurrences Positive/Negative number counter
Accumulator Loop Building sums or products Population growth calculation
Nested Loop 2D patterns, tables Pascal's triangle, multiplication table
Search Loop Finding specific values Ramanujan number detection

Performance Considerations:

Time Complexity Analysis:

  • Single Loop: O(n) - Linear time complexity
  • Nested Loops: O(n²) - Quadratic time complexity
  • Triple Nested: O(n³) - Cubic time complexity (Ramanujan search)

Optimization Tips:

  • Minimize unnecessary iterations by using break statements
  • Use appropriate loop bounds to avoid redundant calculations
  • Consider mathematical optimizations (like cube root limits)
💪 Additional Practice Exercises

Level 1: Basic Loop Practice

  1. Write a program to find the sum of first n natural numbers
  2. Create a program to print all even numbers between 1 and 100
  3. Write a program to calculate factorial of a number
  4. Create a program to reverse a number using loops

Level 2: Intermediate Challenges

  1. Print the Fibonacci series up to n terms
  2. Check if a number is prime using loops
  3. Create a program to find GCD of two numbers using Euclidean algorithm
  4. Generate patterns like diamond, pyramid, and inverted triangle

Level 3: Advanced Applications

  1. Find all perfect numbers within a given range
  2. Implement a simple calculator with menu-driven loop
  3. Create a number guessing game with attempts counter
  4. Find all Armstrong numbers in a given range
🐛 Common Loop Errors & Debugging Tips

Infinite Loop Prevention:

// WRONG: Infinite loop
int i = 1;
while (i <= 10) {
    printf("%d ", i);
    // Missing i++; causes infinite loop
}

// CORRECT: Proper increment
int i = 1;
while (i <= 10) {
    printf("%d ", i);
    i++;  // Don't forget the increment!
}

Off-by-One Errors:

// WRONG: Misses last iteration
for (int i = 1; i < 10; i++) {  // Only goes 1-9
    printf("%d ", i);
}

// CORRECT: Includes all desired iterations
for (int i = 1; i <= 10; i++) {  // Goes 1-10
    printf("%d ", i);
}

Nested Loop Index Confusion:

// WRONG: Using same variable name
for (int i = 1; i <= 3; i++) {
    for (int i = 1; i <= 3; i++) {  // Shadows outer i
        printf("%d ", i);
    }
}

// CORRECT: Use different variable names
for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        printf("%d,%d ", i, j);
    }
}
📝 Lab Assignment & Evaluation

Submission Requirements:

Complete all 5 experiments and submit:
  • Source code (.c files) for each experiment
  • Screenshots of program execution with sample inputs/outputs
  • Brief explanation of the algorithm used for each experiment
  • Analysis of time complexity for nested loop programs

Evaluation Criteria:

Criteria Points Description
Code Correctness 40% Program produces correct output for given inputs
Code Quality 25% Proper indentation, meaningful variable names, comments
Algorithm Efficiency 20% Optimal loop structure and minimal redundancy
Documentation 15% Clear explanation and analysis of approach

Bonus Challenges:

Optional (5 bonus points each):
  • Modify the Ramanujan program to find numbers expressible as sum of cubes in 3 different ways
  • Create an animated population growth visualization using text-based charts
  • Implement error handling for all user inputs in the experiments
📚 References & Further Reading

Recommended Books:

  • "The C Programming Language" by Brian Kernighan and Dennis Ritchie
  • "C Programming: A Modern Approach" by K.N. King
  • "Programming in C" by Stephen Kochan

Online Resources:

  • C Reference Documentation: cppreference.com
  • Practice Problems: hackerrank.com, leetcode.com
  • Video Tutorials: GeeksforGeeks C Programming

Mathematical Concepts:

  • Pascal's Triangle: Mathematical properties and applications
  • Hardy-Ramanujan Numbers: Number theory and cube sums
  • Compound Growth: Exponential growth calculations