Conditional Loops in C

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to implement conditional loops in C programming. You will start by understanding the fundamentals of while loops, then explore the use of the break and continue directives to control loop execution. Additionally, you will learn how to filter array elements using conditional statements and optimize loop efficiency with various directives. By the end of this lab, you will have a solid understanding of conditional loops and their practical applications in C programming.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("C")) -.-> c/BasicsGroup(["Basics"]) c(("C")) -.-> c/FunctionsGroup(["Functions"]) c(("C")) -.-> c/UserInteractionGroup(["User Interaction"]) c(("C")) -.-> c/ControlFlowGroup(["Control Flow"]) c(("C")) -.-> c/CompoundTypesGroup(["Compound Types"]) c/BasicsGroup -.-> c/operators("Operators") c/ControlFlowGroup -.-> c/if_else("If...Else") c/ControlFlowGroup -.-> c/for_loop("For Loop") c/ControlFlowGroup -.-> c/while_loop("While Loop") c/ControlFlowGroup -.-> c/break_continue("Break/Continue") c/CompoundTypesGroup -.-> c/arrays("Arrays") c/FunctionsGroup -.-> c/math_functions("Math Functions") c/UserInteractionGroup -.-> c/user_input("User Input") c/UserInteractionGroup -.-> c/output("Output") subgraph Lab Skills c/operators -.-> lab-438260{{"Conditional Loops in C"}} c/if_else -.-> lab-438260{{"Conditional Loops in C"}} c/for_loop -.-> lab-438260{{"Conditional Loops in C"}} c/while_loop -.-> lab-438260{{"Conditional Loops in C"}} c/break_continue -.-> lab-438260{{"Conditional Loops in C"}} c/arrays -.-> lab-438260{{"Conditional Loops in C"}} c/math_functions -.-> lab-438260{{"Conditional Loops in C"}} c/user_input -.-> lab-438260{{"Conditional Loops in C"}} c/output -.-> lab-438260{{"Conditional Loops in C"}} end

Understand While Loops

In this step, you'll learn the fundamentals of while loops in C programming. While loops are powerful control structures that allow you to repeat a block of code as long as a specific condition remains true.

Let's create a simple C program to demonstrate the basic syntax of a while loop. Open the VSCode editor and create a new file called while_loop_example.c in the ~/project directory.

cd ~/project
touch while_loop_example.c
#include <stdio.h>

int main() {
    int count = 1;

    while (count <= 5) {
        printf("Current count: %d\n", count);
        count++;
    }

    return 0;
}

Let's break down the code:

  • int count = 1; initializes a counter variable
  • while (count <= 5) creates a loop that continues as long as count is less than or equal to 5
  • printf() displays the current value of count
  • count++ increments the counter in each iteration

Compile and run the program:

gcc while_loop_example.c -o while_loop_example
./while_loop_example

Example output:

Current count: 1
Current count: 2
Current count: 3
Current count: 4
Current count: 5

Here's another example that demonstrates a while loop with user input:

#include <stdio.h>

int main() {
    int number;

    printf("Enter numbers (enter 0 to stop):\n");

    number = 1;  // Initialize to non-zero value
    while (number != 0) {
        printf("Enter a number: ");
        scanf("%d", &number);

        if (number != 0) {
            printf("You entered: %d\n", number);
        }
    }

    printf("Loop ended. Goodbye!\n");

    return 0;
}

This example shows how while loops can be used for interactive input, continuing until a specific condition (entering 0) is met.

Apply Break Directive in While Loops

In this step, you'll learn about the break directive in C programming, which allows you to exit a loop prematurely when a specific condition is met. The break statement provides a way to immediately terminate the current loop and continue execution with the next statement after the loop.

Let's create a new file called break_loop_example.c in the ~/project directory to demonstrate the usage of break:

cd ~/project
touch break_loop_example.c
#include <stdio.h>

int main() {
    int number;

    printf("Enter numbers to find the first multiple of 10:\n");

    while (1) {  // Infinite loop
        printf("Enter a number: ");
        scanf("%d", &number);

        if (number % 10 == 0) {
            printf("Found a multiple of 10: %d\n", number);
            break;  // Exit the loop when a multiple of 10 is found
        }

        printf("Not a multiple of 10. Try again.\n");
    }

    printf("Loop terminated after finding a multiple of 10.\n");

    return 0;
}

Let's break down the code:

  • while (1) creates an infinite loop that will continue until a break statement is encountered
  • When the user enters a number divisible by 10, the break statement immediately exits the loop
  • If the number is not divisible by 10, the loop continues to prompt for input

Here's another example that demonstrates break in a more complex scenario:

#include <stdio.h>

int main() {
    int sum = 0;
    int count = 0;
    int input;

    printf("Enter numbers (enter a negative number to stop):\n");

    while (1) {
        printf("Enter a number: ");
        scanf("%d", &input);

        if (input < 0) {
            break;  // Exit the loop if a negative number is entered
        }

        sum += input;
        count++;
    }

    if (count > 0) {
        printf("Average of entered numbers: %.2f\n", (float)sum / count);
    } else {
        printf("No numbers were entered.\n");
    }

    return 0;
}

This example shows how break can be used to:

  • Stop collecting input when a specific condition is met
  • Calculate an average of entered numbers
  • Provide flexibility in loop termination

Compile and run the programs to see how the break directive works:

gcc break_loop_example.c -o break_loop_example
./break_loop_example

Utilize Continue Directive in While Loops

In this step, you'll learn about the continue directive in C programming, which allows you to skip the current iteration of a loop and move to the next iteration. The continue statement provides a way to selectively execute or skip parts of a loop based on specific conditions.

Let's create a new file called continue_loop_example.c in the ~/project directory to demonstrate the usage of continue:

cd ~/project
touch continue_loop_example.c
#include <stdio.h>

int main() {
    int number;
    int sum_even = 0;
    int count_even = 0;

    printf("Enter 10 numbers to calculate the sum and count of even numbers:\n");

    int i = 0;
    while (i < 10) {
        printf("Enter number %d: ", i + 1);
        scanf("%d", &number);

        // Skip odd numbers
        if (number % 2 != 0) {
            printf("Skipping odd number: %d\n", number);
            continue;  // Move to the next iteration
        }

        sum_even += number;
        count_even++;

        i++;
    }

    if (count_even > 0) {
        printf("Sum of even numbers: %d\n", sum_even);
        printf("Count of even numbers: %d\n", count_even);
        printf("Average of even numbers: %.2f\n", (float)sum_even / count_even);
    } else {
        printf("No even numbers were entered.\n");
    }

    return 0;
}

Let's break down the code:

  • The program asks the user to enter 10 numbers
  • if (number % 2 != 0) checks if the number is odd
  • continue skips the rest of the current iteration for odd numbers
  • Only even numbers are added to the sum and counted

Here's another example that demonstrates continue with more complex conditions:

#include <stdio.h>

int main() {
    int number;
    int positive_count = 0;
    int negative_count = 0;

    printf("Enter numbers (enter 0 to stop):\n");

    while (1) {
        printf("Enter a number: ");
        scanf("%d", &number);

        // Exit the loop if 0 is entered
        if (number == 0) {
            break;
        }

        // Skip zero
        if (number == 0) {
            continue;
        }

        // Count positive and negative numbers
        if (number > 0) {
            positive_count++;
        } else {
            negative_count++;
        }
    }

    printf("Positive numbers count: %d\n", positive_count);
    printf("Negative numbers count: %d\n", negative_count);

    return 0;
}

This example shows how continue can be used to:

  • Skip specific values
  • Selectively process numbers based on conditions
  • Provide more flexible loop control

Compile and run the programs to see how the continue directive works:

gcc continue_loop_example.c -o continue_loop_example
./continue_loop_example

Filter Array Elements with Conditional Statements

In this step, you'll learn how to filter array elements using conditional statements and loops in C programming. Filtering allows you to select specific elements from an array based on certain conditions.

Let's create a new file called array_filtering.c in the ~/project directory to demonstrate array element filtering:

cd ~/project
touch array_filtering.c
#include <stdio.h>

#define MAX_SIZE 10

int main() {
    int numbers[MAX_SIZE];
    int filtered_even[MAX_SIZE];
    int filtered_count = 0;

    // Input array elements
    printf("Enter %d numbers:\n", MAX_SIZE);
    for (int i = 0; i < MAX_SIZE; i++) {
        printf("Enter number %d: ", i + 1);
        scanf("%d", &numbers[i]);
    }

    // Filter even numbers
    printf("\nFiltered Even Numbers:\n");
    for (int i = 0; i < MAX_SIZE; i++) {
        if (numbers[i] % 2 == 0) {
            filtered_even[filtered_count] = numbers[i];
            filtered_count++;
            printf("%d ", numbers[i]);
        }
    }

    printf("\n\nTotal even numbers: %d\n", filtered_count);

    return 0;
}

Let's break down the filtering process:

  • We create two arrays: numbers to store input and filtered_even to store filtered elements
  • The first loop reads 10 numbers from the user
  • The second loop uses a conditional statement to filter even numbers
  • if (numbers[i] % 2 == 0) checks if a number is even
  • Matching elements are stored in filtered_even array

Here's a more complex example with multiple filtering conditions:

#include <stdio.h>

#define MAX_SIZE 10

int main() {
    int numbers[MAX_SIZE];
    int prime_numbers[MAX_SIZE];
    int prime_count = 0;

    // Input array elements
    printf("Enter %d numbers:\n", MAX_SIZE);
    for (int i = 0; i < MAX_SIZE; i++) {
        printf("Enter number %d: ", i + 1);
        scanf("%d", &numbers[i]);
    }

    // Filter prime numbers
    printf("\nFiltered Prime Numbers:\n");
    for (int i = 0; i < MAX_SIZE; i++) {
        // Skip numbers less than 2
        if (numbers[i] < 2) continue;

        int is_prime = 1;
        for (int j = 2; j * j <= numbers[i]; j++) {
            if (numbers[i] % j == 0) {
                is_prime = 0;
                break;
            }
        }

        // Add prime numbers to filtered array
        if (is_prime) {
            prime_numbers[prime_count] = numbers[i];
            prime_count++;
            printf("%d ", numbers[i]);
        }
    }

    printf("\n\nTotal prime numbers: %d\n", prime_count);

    return 0;
}

This example demonstrates:

  • Filtering prime numbers from an input array
  • Nested loops to check primality
  • Storing filtered elements in a separate array

Compile and run the programs:

gcc array_filtering.c -o array_filtering
./array_filtering

Example input and output:

Enter 10 numbers:
Enter number 1: 5
Enter number 2: 12
Enter number 3: 7
Enter number 4: 15
...

Filtered Prime Numbers:
5 7

Total prime numbers: 2

Optimize Loop Efficiency with Directives

In this step, you'll learn techniques to optimize loop efficiency in C programming using various directives and strategies. We'll explore different approaches to improve loop performance and readability.

Let's create a file called loop_optimization.c in the ~/project directory to demonstrate optimization techniques:

cd ~/project
touch loop_optimization.c
#include <stdio.h>
#include <time.h>

#define ARRAY_SIZE 10000

// Function to calculate sum using traditional loop
int traditional_sum(int arr[], int size) {
    int sum = 0;
    for (int i = 0; i < size; i++) {
        sum += arr[i];
    }
    return sum;
}

// Function to calculate sum using optimized loop
int optimized_sum(int arr[], int size) {
    int sum1 = 0, sum2 = 0, sum3 = 0, sum4 = 0;

    // Loop unrolling technique
    int i;
    for (i = 0; i + 4 < size; i += 4) {
        sum1 += arr[i];
        sum2 += arr[i + 1];
        sum3 += arr[i + 2];
        sum4 += arr[i + 3];
    }

    // Handle remaining elements
    for (; i < size; i++) {
        sum1 += arr[i];
    }

    return sum1 + sum2 + sum3 + sum4;
}

int main() {
    int arr[ARRAY_SIZE];
    clock_t start, end;
    double cpu_time_used;

    // Initialize array
    for (int i = 0; i < ARRAY_SIZE; i++) {
        arr[i] = i + 1;
    }

    // Traditional sum
    start = clock();
    int traditional_result = traditional_sum(arr, ARRAY_SIZE);
    end = clock();
    cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
    printf("Traditional Sum: %d\n", traditional_result);
    printf("Traditional Loop Time: %f seconds\n", cpu_time_used);

    // Optimized sum
    start = clock();
    int optimized_result = optimized_sum(arr, ARRAY_SIZE);
    end = clock();
    cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
    printf("Optimized Sum: %d\n", optimized_result);
    printf("Optimized Loop Time: %f seconds\n", cpu_time_used);

    return 0;
}

Here's another example demonstrating multiple optimization techniques:

#include <stdio.h>

#define MAX_SIZE 1000

int main() {
    int numbers[MAX_SIZE];
    int even_sum = 0, odd_sum = 0;

    // Efficient initialization and summation
    for (int i = 0; i < MAX_SIZE; i++) {
        numbers[i] = i + 1;

        // Conditional sum with minimal branching
        even_sum += (numbers[i] % 2 == 0) * numbers[i];
        odd_sum += (numbers[i] % 2 != 0) * numbers[i];
    }

    printf("Sum of Even Numbers: %d\n", even_sum);
    printf("Sum of Odd Numbers: %d\n", odd_sum);

    return 0;
}

Key optimization techniques demonstrated:

  1. Loop unrolling to reduce loop overhead
  2. Minimizing branch predictions
  3. Combining initialization and processing
  4. Using multiplication for conditional summing

Compile and run the programs with optimization flags:

## Compile with basic optimization
gcc -O2 loop_optimization.c -o loop_optimization
./loop_optimization

## Compile with advanced optimization
gcc -O3 loop_optimization.c -o loop_optimization
./loop_optimization

Additional optimization tips:

  • Use -O2 or -O3 compiler flags
  • Minimize function calls inside loops
  • Use appropriate data types
  • Avoid unnecessary computations
  • Consider loop invariant code motion

Summary

In this lab, you will learn the fundamentals of while loops in C programming, including how to use the break and continue directives to control the flow of the loop. You will also explore techniques for filtering array elements using conditional statements and optimizing loop efficiency with various directives. By the end of this lab, you will have a solid understanding of how to implement conditional loops in C to solve a variety of programming problems.