Sunday, March 09, 2025

Efficient Code Repetition, Using Loops in C Programming

Loops can be described as key elements in programming, enabling the repetition of certain blocks of code while a condition is met. Most modern programmers couldn't imagine coding without loops. However, if you were to go back to 1972, in the earliest versions of the BASIC language, loops as we know them today did not exist in a structured form, and programmers relied on commands like GOTO or jump to control the program flow, including simulating loops. This was characteristic of the first iterations of BASIC, which was designed in 1964 by John Kemeny and Thomas Kurtz at Dartmouth College, with the goal of being simple for beginners.

However, was the GOTO command alone sufficient? Theoretically, the GOTO command is sufficient to simulate any loop because it is a Turing-complete mechanism – any control structure can be expressed with jumps and conditions. However, in practice, it was inefficient and prone to errors. That's why loops were introduced as a response to criticism, including Edsger Dijkstra's famous 1968 article, 'Go To Statement Considered Harmful,' which pointed out the problems of unstructured code.

In the C programming language, the loops: for, while, and do-while, existed from the very beginning, that is, from its creation in 1972, when Dennis Ritchie developed it at Bell Labs. The C programming language was designed as a successor to the B programming language, which itself was a simplified version of BCPL, and one of the goals was to provide a higher level of program flow control compared to its predecessors, while maintaining closeness to machine code.

Loops have always existed in the C programming language

Loops have always existed in the C programming language

Loops were an integral part of that design, so there was no moment in the history of the standard C programming language where they were absent. Unlike BASIC, which initially relied only on GOTO, the C programming language was designed with loops as a standard tool, inspired by higher-level languages like ALGOL, but adapted for low-level efficiency.

for: For iterations with a known number of repetitions.

while: For conditional loops where the condition is checked before execution.

do-while: For conditional loops where the condition is checked after execution.

In early versions, variable declaration within the for loop header was not allowed; variables had to be declared outside the loop. This changed with the C99 standard, which introduced block scope. With the ANSI C standard in 1989, known as C89/C90, loops were formally defined and have not undergone significant changes in later standards C99, C11, C17, and C23. All three loops have remained consistent in syntax and semantics, showing that Ritchie's design was robust from the very start.

Why Doesn't the C Programming Language Have a 'foreach' Loop, While C++ Has an Alternative?

A foreach loop is a type of loop that allows iteration through the elements of a collection, such as an array, list, or set, without explicitly using indices or counters. Instead of the programmer manually managing the iteration as in a for loop with a counter, foreach automatically goes through all elements, often making the code more readable and less prone to errors. This construct is particularly popular in higher-level languages that have built-in support for collections. One of the first languages to popularize the foreach loop was Perl, a programming language that uses foreach to iterate through lists or arrays. This was a significant step towards simpler handling of collections. Java introduced the "enhanced for" loop in version 5, in 2004, although the language existed earlier without it. This was a response to the need for more readable code compared to the classic for loop with indices. From the very beginning, the C# programming language had foreach as part of its design, inspired by an object-oriented approach, while the Python programming language, although it does not use the keyword foreach, Python's for loop functions as a foreach from its inception in 1991.

The C programming language does not have a foreach loop

The C programming language does not have a foreach loop

Thus, foreach appeared during the 1980s and 1990s as part of a trend towards abstraction and simplicity in higher-level languages. The C programming language is designed as a language close to hardware, with a focus on explicit control and performance. Introducing foreach would require additional abstraction that C avoids. In the C programming language, arrays are simple pointers to memory, without built-in metadata about the size or type of the collection. A foreach loop would require the language to know the boundaries of the array or support more complex data structures, which is not part of its design. Programmers can write macros or functions to simulate foreach-like syntax, but it is not part of the standard. For example:

#include <stdio.h>

#define FOREACH(array, size, var) for (int i = 0, var = array[0]; i < size; var = array[++i])

int main() {

    int niz[] = {1, 2, 3};

    FOREACH(niz, 3, x) {

        printf("%d\n", x);

    }

}

As for the C++ programming language, it introduced the equivalent of the foreach loop later in its evolution, called the range-based for loop. This functionality was added in the C++11 standard in 2011.

A Practical Approach to Loops in the C Programming Language

For Loop

The for loop is most commonly used when we know in advance how many times the repetition needs to be executed. Its syntax looks like this:

for (initialization; condition; increment/decrement) {

// Block of code that repeats

}

Open your terminal and type the following code.

manuel@manuel-virtual-machine:~$ sudo apt-get update

manuel@manuel-virtual-machine:~$ sudo apt-get upgrade

manuel@manuel-virtual-machine:~$ clear

manuel@manuel-virtual-machine:~$ ls

manuel@manuel-virtual-machine:~$ cd tutorials

manuel@manuel-virtual-machine:/tutorials$ ls

manuel@manuel-virtual-machine:/tutorials$ cd c_tutorial

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ ls

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ mkdir for_loop

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ cd for_loop

manuel@manuel-virtual-machine:/tutorials/c_tutorial/for_loop$ code .

Create a file and name it forloop.c, then type the following code.

#include <stdio.h> 

int main() {

    int number; // Variable to store the user's input

    unsigned long long factorial = 1; // Using a large type to handle bigger factorials

    // Prompt the user for input

    printf("Enter a positive integer (up to 20) to calculate its factorial: ");

    scanf("%d", &number);

 

    // Input validation, ensure the number is positive and not too large

    if (number < 0) {

        printf("Error: Factorial is not defined for negative numbers!\n");

        return 1; // Exit with an error code

 

    } else if (number > 20) {

        printf("Error: Number too large, result my overflow!\n");

        return 1; // Exit to avoid overflow

    }

 

    // Calculate factorial using a for loop

    for (int i = 1; i <= number; i++) {

        factorial *= i; // Multiply factorial by each integer up to number

    }

     // Display the result

    printf("The factorial of %d (written as %d!) is %llu.\n", number, number, factorial);

     return 0; // Successful execution

}

When you execute the given code, you will get similar following result.

manue@DESKTOP-E2QR9K9 MINGW64 /d/tutorials/c_tutorials/for_loop

$ gcc forloop.c -o forloop

 

manue@DESKTOP-E2QR9K9 MINGW64 /d/tutorials/c_tutorials/for_loop

$ ./forloop

Enter a positive integer (up to 20) to calculate its factorial: 18

The factorial of 18 (written as 18!) is 6402373705728000.

You can also watch a video of how the program is coded.


C Tutorial – 18. How to Use the For Loop in C Programming Language?

While Loop

The while loop is used when we do not know in advance how many times the loop will be executed, as it depends on some external condition. Its syntax looks like this:

while (condition) {

  // Block of code that repeats

}

Open your terminal and type the following code.

manuel@manuel-virtual-machine:~$ sudo apt-get update

manuel@manuel-virtual-machine:~$ sudo apt-get upgrade

manuel@manuel-virtual-machine:~$ clear

manuel@manuel-virtual-machine:~$ ls

manuel@manuel-virtual-machine:~$ cd tutorials

manuel@manuel-virtual-machine:/tutorials$ ls

manuel@manuel-virtual-machine:/tutorials$ cd c_tutorial

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ ls

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ mkdir while_loop

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ cd while_loop

manuel@manuel-virtual-machine:/tutorials/c_tutorial/while_loop$ code .

Create a file and name it whileloop.c, then type the following code.

#include <stdio.h>

#include <stdlib.h> // For rand() and srand()

#include <time.h>   // For time()

int main() {

    int secret_number, user_guess, attempts = 0;

    const int MAX_ATTEMPTS = 10; // Limit the number of guesses

 

    // Seed the random number generator with the current time

    srand(time(NULL));

    // Generate a random number between 1 and 100

    secret_number = (rand() % 100) + 1;

 

    printf("Welcome to the Number Guessing Game!\n");

    printf("I’ve picked a number between 1 and 100. You have up to %d attempts.\n", MAX_ATTEMPTS);

    printf("Start guessing!\n");

 

    // Main game loop using while

    while (attempts < MAX_ATTEMPTS) {

        // Get user input

        printf("Enter your guess: ");

        if (scanf("%d", &user_guess) != 1) { // Check if input is valid

            printf("Invalid input! Please enter a number.\n");

            while (getchar() != '\n'); // Clear input buffer

            continue; // Skip to the next iteration

 

        }

 

        attempts++; // Increment attempt counter

 

        // Check the guess and provide feedback

        if (user_guess < 1 || user_guess > 100) {

            printf("Please guess a number between 1 and 100!\n");

 

        } else if (user_guess < secret_number) {

            printf("Too low! Try again. Attempts left: %d\n", MAX_ATTEMPTS - attempts);

 

        } else if (user_guess > secret_number) {

            printf("Too high! Try again. Attempts left: %d\n", MAX_ATTEMPTS - attempts);

 

        } else {

            printf("Congratulations! You guessed the number %d in %d attempts!\n", secret_number, attempts);

            break; // Exit the loop on a correct guess

        }

    }

 

    // If the user runs out of attempts

    if (attempts >= MAX_ATTEMPTS) {

        printf("Game over! You’ve run out of attempts. The number was %d.\n", secret_number);

    } 

    return 0;

}

When you execute the given code, you will get similar following result.

manue@DESKTOP-E2QR9K9 MINGW64 /d/tutorials/c_tutorials/while_loop

$ gcc whileloop.c -o whileloop

 

manue@DESKTOP-E2QR9K9 MINGW64 /d/tutorials/c_tutorials/while_loop

$ ./whileloop

Welcome to the Number Guessing Game!

IΓÇÖve picked a number between 1 and 100. You have up to 10 attempts.

Start guessing!

Enter your guess: 18

Too low! Try again. Attempts left: 9

Enter your guess: 58

Too high! Try again. Attempts left: 8

Enter your guess: 40

Too high! Try again. Attempts left: 7

Enter your guess: 35

Too high! Try again. Attempts left: 6

Enter your guess: 24

Too high! Try again. Attempts left: 5

Enter your guess: 27

Too high! Try again. Attempts left: 4

Enter your guess: 25

Too high! Try again. Attempts left: 3

Enter your guess: 23

Congratulations! You guessed the number 23 in 8 attempts!

When it comes to this example, you're probably surprised that we created a Number Guessing Game. We think that the code of this game provides a lot, especially when it comes to the while loop. But besides it, pay attention that we use the constant MAX_ATTEMPTS. In the C programming language, as well as in most others, a constant is a value that cannot be changed during program execution. This means that once a constant is defined, its value remains fixed until the end of the program. We will learn about constants in the next blog post.

But also, regarding the novelties in the code that you haven't learned, there are two generators, srand and rand. These functions are used for generating random numbers and are used to simulate unpredictability. However, most computers use pseudo-random generators, which means that the numbers are not truly random, but are generated using algorithms. In the C programming language, to generate a random number, you need two generators, unlike most other programming languages. In this example, srand(time(NULL)) ensures that the random number generator is initialized with a different "seed" value each time the program is run. As a result, rand() will generate a different sequence of numbers each time.

The C programming language has many useful functions that you will often use in your programs. So, always be prepared to code something new and different that you didn't know. You can also watch a video of how the program is coded.


C Tutorial – 19. How to Use the While Loop in C Programming Language?

Do-While Loop

This loop is similar to the while loop, with the difference that the code in the loop body is executed at least once, regardless of the condition. Its syntax looks like this:

do {

    // Block of code that repeats

} while (condition);

Open your terminal and type the following code.

manuel@manuel-virtual-machine:~$ sudo apt-get update

manuel@manuel-virtual-machine:~$ sudo apt-get upgrade

manuel@manuel-virtual-machine:~$ clear

manuel@manuel-virtual-machine:~$ ls

manuel@manuel-virtual-machine:~$ cd tutorials

manuel@manuel-virtual-machine:/tutorials$ ls

manuel@manuel-virtual-machine:/tutorials$ cd c_tutorial

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ ls

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ mkdir do_while_loop

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ cd do_while_loop

manuel@manuel-virtual-machine:/tutorials/c_tutorial/do_while_loop$ code .

Create a file and name it dowhileloop.c, then type the following code.

#include <stdio.h>

#include <string.h> // For string handling

int main() {

    char sentence[100]; // Buffer for the sentence up to 99 characters + null terminator

    int count, i = 1;

 

    // Input sentence from the user

    printf("Enter a sentence, up to 99 characters: ");

    fgets(sentence, sizeof(sentence), stdin); // Safer way to input a string

    sentence[strcspn(sentence, "\n")] = 0; // Removes the newline added by fgets

 

    // Input the number of repetitions

    printf("Enter number between 1 and 20 to repeat the sentence: ");

    scanf("%d", &count);

 

    // Input validation

    if (count < 1 || count > 20) {

        printf("Error: Number must be between 1 and 20!\n");

        return 1;

 

    }

 

    // Repeat the setence using do-while

    do {

        printf("%d: %s\n", i, sentence); // Prints iteration number and the sentence

        i++;

    } while (i <= count);

     printf("End of loop\n");

     return 0;

 }

When you execute the given code, you will get similar following result.

manue@DESKTOP-E2QR9K9 MINGW64 /d/tutorials/c_tutorials/do_while_loop

$ gcc dowhileloop.c -o dowhileloop

 

manue@DESKTOP-E2QR9K9 MINGW64 /d/tutorials/c_tutorials/do_while_loop

$ ./dowhileloop

Enter a sentence, up to 99 characters: Manuel, you are a genius! :D

Enter number between 1 and 20 to repeat the sentence: 18

1: Manuel, you are a genius! :D

2: Manuel, you are a genius! :D

3: Manuel, you are a genius! :D

4: Manuel, you are a genius! :D

5: Manuel, you are a genius! :D

6: Manuel, you are a genius! :D

7: Manuel, you are a genius! :D

8: Manuel, you are a genius! :D

9: Manuel, you are a genius! :D

10: Manuel, you are a genius! :D

11: Manuel, you are a genius! :D

12: Manuel, you are a genius! :D

13: Manuel, you are a genius! :D

14: Manuel, you are a genius! :D

15: Manuel, you are a genius! :D

16: Manuel, you are a genius! :D

17: Manuel, you are a genius! :D

18: Manuel, you are a genius! :D

End of loop.

You can also watch a video of how the program is coded.

C Tutorial – 20. How to Use the Do-While Loop in C Programming Language?


 

 

 

 

 

 

 

 

 

No comments:

Post a Comment