Loops in C

The Concept of Loops

One of the most critical structures in programming—regardless of the language—is loops. Loops can be thought of as blocks of code that perform a task a specified number of times. In a program that prints "Hello World" 10 times, the code to print "Hello World" is written just once, and the loop comes into play to repeat the code the desired number of times.

What makes loops so critical is that if not written and optimized properly, they can unnecessarily consume your computer's processing power and increase the time spent executing the program. Conversely, a well-written loop will make your program run faster.

All loops can be summarized in two basic stages. One stage is the logical query part where it is decided whether the loop should continue or not. For example, if you are printing "Hello World" 10 times on the screen, you check how many times the task has been done in the condition part. The other stage is the task the loop will perform, i.e., printing "Hello World" to the screen.

If you mistakenly set up the logical test in the stage that determines whether the loop should continue, either your program won’t run at all, or it might run indefinitely.

Some common loops in the C programming language include the while, do while, and for loops. Although goto can also be used as a looping element, it is generally not recommended.

while Loop

The while loop is the most basic type of loop. In this loop, a control expression is used to check whether the loop should continue. The code block inside (i.e., within the curly braces) is executed for the specified number of iterations.

Here’s the general structure and flowchart of the while loop:

while Structure

while (condition) {
    statement(s);
}

Let’s revisit the example of printing "Hello World" 10 times. We’ll use a while loop to write the program:

/*
Prints "Hello World" 10 times
*/
#include<stdio.h>
int main(void) {
    int i = 0; // Set the initial value of i
    while (i++ < 10) { // Check if i is less than 10, then increment it
        printf("%2d: Hello World\n", i); // Print the message
    }
    return 0;
}

The program is quite simple. We start by assigning the value 0 to i. Then, we begin the while loop. The condition (i.e., whether i is less than 10) is checked, and if it’s true, the code inside the loop is executed. Before executing the loop code, i is incremented (this is called post-increment). This process repeats 10 times, and when i reaches 10, the loop terminates.

Sum Operation Example

Let’s now write a program that calculates the sum of the squares of numbers up to n (where n is entered by the user):

#include<stdio.h>
int main(void) {
    int i = 0, sum = 0;
    int n;
    printf("Please enter the value of n: ");
    scanf("%d", &n);
    while (i <= n) {
        sum += i * i; // Add the square of i to the sum
        i++; // Increment i
    }
    printf("Result: %d\n", sum);
    return 0;
}

do while Loop

The second type of loop we will discuss is the do while loop. It performs the same task as the while loop, but with an important difference.

In while loops, the condition is checked before the loop executes, meaning that if the condition is not met, the loop might not run at all. In contrast, in do while loops, the condition is checked after the loop executes, so the loop will always run at least once.

Some situations require that the code inside the loop executes at least once, and in these cases, a do while loop is appropriate.

Here’s the general structure and flowchart of the do while loop:

do while Structure

do {
    statement(s);
} while (condition);

Let’s start with a "Hello World" example again using the do while loop:

#include<stdio.h>
int main(void) {
    int i = 0;
    do {
        printf("%2d: Hello World\n", ++i); // First increment, then print
    } while (i < 10); // Continue as long as i is less than 10
    return 0;
}

As you can see, this structure is very similar to the previous example, with the main difference being that the loop will execute at least once, regardless of the value of i.

Now let’s look at a scenario where do while makes more sense. We will create a program that asks the user for two numbers, adds them, and asks if they want to continue. If the user enters 'E' or 'e', the program continues; otherwise, it ends.

#include<stdio.h>
int main(void) {
    int num1, num2;
    char continue_choice;
    do {
        printf("Enter the first number: ");
        scanf("%d", &num1);
        printf("Enter the second number: ");
        scanf("%d", &num2);
        printf("%d + %d = %d\n", num1, num2, num1 + num2);
        printf("Do you want to continue? ");
        do {
            scanf("%c", &continue_choice); // Handle newline character
        } while (continue_choice == '\n');
        printf("\n");
    } while (continue_choice == 'E' || continue_choice == 'e');

    return 0;
}

In this example, the program asks the user for two numbers, calculates their sum, and then asks whether they want to continue. The loop continues until the user presses something other than 'E' or 'e'.

for Loop

The third type of loop is the for loop. Unlike the while and do while loops, the for loop is better suited for iterative tasks, such as numeric calculations. The for loop is not just efficient in terms of performance, but also more convenient in terms of syntax for repetitive tasks, especially when working with arrays.

Here’s the general structure and flowchart for the for loop:

for Structure

for (initialization; condition; increment/decrement) {
    statement(s);
}

Let’s start by writing a program that prints "Hello World" 10 times using the for loop:

#include<stdio.h>
int main(void) {
    int i;
    for (i = 0; i < 10; i++) {
        printf("%2d: Hello World\n", i + 1);
    }
    return 0;
}

As you can see, the for loop is simpler and more readable. You only need to specify the initialization, condition, and increment in a single line, making it very concise.

You can also leave out the initialization and increment in the for loop, as shown below:

#include<stdio.h>
int main(void) {
    int i = 0;
    for (; i < 10;) {
        printf("%2d: Hello World\n", i + 1);
        i++; // Increment inside the loop
    }
    return 0;
}

break Command

Sometimes, we may want to terminate a loop abruptly. This can be done using the break command, which is also used in switch case structures. The break command can be used in any type of loop.

Here’s an example program that generates random numbers between 0 and 99 and breaks the loop when it generates the number 61:

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

int main(void) {
    int i, random_number;
    int attempt_count = 0;
    srand(time(NULL)); // Seed for random number generation
    while (1) {
        random_number = rand() % 100; // Generate a random number between 0 and 99
        attempt_count++; // Increment attempt count
        if (random_number == 61) break; // If the number is 61, break the loop
    }
    printf("Total attempts: %d\n", attempt_count);
    return 0;
}

This program will keep generating random numbers until it finds 61, and it will print how many attempts it took to find that number.

continue Command

The continue command is used when we want to skip the current iteration of the loop and move to the next one.

Here’s an example program that prints only odd numbers between 0 and 10:

#include<stdio.h>
int main(void) {
    int i;
    for (i = 0; i < 10; i++) {
        if (i % 2 == 0) continue; // Skip even numbers
        printf("%2d\n", i); // Print odd numbers
    }
    return 0;
}

In this example, the program checks whether i is even, and if it is, the continue command is used to skip the rest of the loop and move on to the next iteration.

goto Statement

In C programming, there is another construct

called goto, which is used to jump from one part of the code to another. However, the use of goto is generally discouraged because it can make your code difficult to follow and maintain.


Yorumlar

Bu blogdaki popüler yayınlar

Arithmetic Operators and Expressions

Functions

What is a Variable? How is it Defined?