Dr. Roger Ianjamasimanana

C for loop with practical examples

By Dr. Roger Ianjamasimanana

1. What is a for loop?

A for loop in C is used to execute a statement or a block of statements multiple times. It repeats a certain portion of code a specified number of times. The for loop is often used when the number of iterations is known beforehand.

2. For loop syntax in C

The basic syntax of a for loop in C is:

for(initialization; condition; increment/decrement) {
    // Code to be executed
}
  • Initialization: This part is executed only once at the start of the loop. It is used to initialize a counter variable.
  • Condition: This is evaluated before each iteration. The loop continues as long as the condition evaluates to true.
  • Increment/Decrement: After each iteration, the counter variable is updated (incremented or decremented).
  • Code to be executed: The body of the loop, which contains the statements to be executed in each iteration.

3. For loop examples

Let’s start with a simple example that prints numbers from 1 to 5 using a for loop:

#include <stdio.h>

int main() {
    // Loop to print numbers 1 to 5
    for (int i = 1; i <= 5; i++) {
        printf("%d\n", i);
    }
    return 0;
}

Explanation:

  • int i = 1: Initializes the loop counter i to 1.
  • i <= 5: The condition that the loop will check before each iteration. The loop will continue as long as i is less than or equal to 5.
  • i++: After each iteration, the value of i is incremented by 1.

Output:

1
2
3
4
5

3.2 For loop to calculate the sum of numbers

Here’s an example where we use a for loop to calculate the sum of the first 10 natural numbers:

#include <stdio.h>

int main() {
    int sum = 0;

    for (int i = 1; i <= 10; i++) {
        sum += i;  // Add i to sum
    }

    printf("The sum of numbers from 1 to 10 is: %d\n", sum);
    return 0;
}

Explanation:

  • The loop adds each number from 1 to 10 to the variable sum.
  • The result is printed after the loop finishes.

Output:

The sum of numbers from 1 to 10 is: 55

3.3 Nested for loops for a multiplication table

Nested for loops are often used when you need to work with multi-dimensional data. Let's use two nested for loops to print a multiplication table:

#include <stdio.h>

int main() {
    int rows = 5;
    int columns = 5;

    // Outer loop for rows
    for (int i = 1; i <= rows; i++) {
        // Inner loop for columns
        for (int j = 1; j <= columns; j++) {
            printf("%d\t", i * j);
        }
        printf("\n");
    }

    return 0;
}

Explanation:

  • The outer loop controls the rows, and the inner loop controls the columns.
  • The product of i and j is printed, creating a multiplication table.

Output:

1	2	3	4	5	
2	4	6	8	10	
3	6	9	12	15	
4	8	12	16	20	
5	10	15	20	25

3.4 Decrementing loop

The for loop can also be used to decrement a variable. Here’s an example that prints numbers from 10 to 1 in descending order:

#include <stdio.h>

int main() {
    // Loop to print numbers from 10 to 1
    for (int i = 10; i >= 1; i--) {
        printf("%d\n", i);
    }
    return 0;
}

Explanation:

  • i = 10: The loop starts at 10.
  • i >= 1: The loop runs as long as i is greater than or equal to 1.
  • i--: The value of i is decremented after each iteration.

Output:

10
9
8
7
6
5
4
3
2
1

3.5 Using for loops with an array

for loops are also commonly used to iterate over arrays. Here's an example that prints the elements of an array:

#include <stdio.h>

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int length = sizeof(arr) / sizeof(arr[0]); // Calculate array length

    // Loop to print elements of the array
    for (int i = 0; i < length; i++) {
        printf("Element at index %d: %d\n", i, arr[i]);
    }

    return 0;
}

Explanation:

  • We calculate the length of the array using sizeof(arr) / sizeof(arr[0]).
  • The loop iterates over the array, printing each element.

Output:

Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50

3.6 Practical examples in Astronomy

3.6.1 Calculating the orbital periods of planets

Using for loops to perform basic astronomy calculations can be an excellent way to practice programming and understand some core concepts in astronomy, such as orbital periods, distances, and celestial mechanics. Below are a few basic calculations in Astronomy that can be done using for loops in C.

Kepler's Third Law states that the orbital period (T) of a planet around the Sun is related to its average distance (r) from the Sun by the equation:


\[ T^2 = \frac{4 \pi^2}{G M} r^3, \]

where

  • \(T\) is the orbital period in seconds,
  • \(r\) is the average distance (semi-major axis) in meters,
  • \(G\) is the gravitational constant (\( 6.67430 \times 10^{-11}~m^3~kg^-1~s^{-2} \)),
  • \(M\) is the mass of the Sun.

We'll calculate the orbital period for several planets based on their average distance from the Sun.

#include <stdio.h>
#include <math.h>

#define G 6.67430e-11   // Gravitational constant in m^3 kg^-1 s^-2
#define M 1.989e30       // Mass of the Sun in kg

// Function to calculate the orbital period (Kepler's third law)
double calculate_orbital_period(double distance) {
    return 2 * M_PI * sqrt(pow(distance, 3) / (G * M));  // In seconds
}

int main() {
    // Average distances from the Sun for planets in meters
    double distances[] = {57.9e9, 108.2e9, 149.6e9, 227.9e9, 778.5e9, 1433.5e9, 2872.5e9, 4495.1e9}; // distances in meters (Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune)
    char* planets[] = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"};

    // Using a for loop to calculate and display orbital periods for each planet
    for (int i = 0; i < 8; i++) {
        double period_seconds = calculate_orbital_period(distances[i]);
        double period_years = period_seconds / (60 * 60 * 24 * 365.25);  // Convert from seconds to years
        printf("The orbital period of %s is %.2f years.\n", planets[i], period_years);
    }

    return 0;
}

To run the above code, save the code above in a file, e.g., orbital_period.c, then issue the following command in your terminal:

gcc orbital_period.c -o orbital_period
./orbital_period

If you have undefined reference to `sqrt' or undefined reference to `pow' then append -lm at the end of the command as follows:

gcc orbital_period.c -o orbital_period -lm
./orbital_period

Explanation:

  • The gravitational constant (G) and mass of the Sun (M) are constants defined at the beginning.
  • calculate_orbital_period() is a function that uses Kepler’s Third Law to calculate the orbital period of a planet based on its average distance from the Sun.
  • The distances array holds the average distances of the eight planets from the Sun in meters.
  • The planets array holds the names of the planets.
  • The for loop goes through each planet, calculates the orbital period in seconds, converts it to years, and prints the result.
  • Example outputs:

    The orbital period of Mercury is 0.24 years.
    The orbital period of Venus is 0.61 years.
    The orbital period of Earth is 1.00 years.
    The orbital period of Mars is 1.88 years.
    The orbital period of Jupiter is 11.86 years.
    The orbital period of Saturn is 29.46 years.
    The orbital period of Uranus is 84.01 years.
    The orbital period of Neptune is 164.79 years.
    

    3.6.2 Calculate the gravitational force between the Earth and Mercury

    The gravitational force between two objects is calculated using the universal law of gravitation:

    \[ F = \frac{G \cdot m_1 \cdot m_2}{d^2} \]

    Where:

    • \(F\) is the gravitational force (in N),
    • \(G\) is the gravitational constant: \( G = 6.67 \times 10^{-11} \, \text{N m}^2 \, \text{kg}^{-2} \),
    • \(m_1\) is the mass of the Earth: \( 5.972 \times 10^{24} \, \text{kg} \),
    • \(m_2\) is the mass of Mercury: \( 3.285 \times 10^{23} \, \text{kg} \),
    • \(d\) is the average distance between the Earth and Mercury: \( 149.6 \times 10^6 \, \text{km} = 149.6 \times 10^6 \times 10^3 \, \text{m} \).
    #include <stdio.h>
    #include <math.h>
    
    #define G 6.67e-11  // Gravitational constant
    #define M1 5.972e24  // Mass of the Earth in kg
    #define M2 3.285e23  // Mass of Mercury in kg
    #define D 149.6e6 * 1e3  // Distance in meters (converted from km)
    
    int main() {
        double force;
        
        // Loop to simulate multiple calculations (For example, computing force at different distances)
        for (double distance = D; distance <= D + 300e9; distance += 10e9) {
            force = (G * M1 * M2) / pow(distance, 2);  // Gravitational force calculation
            printf("Gravitational force at distance %.2e meters: %.2e N\n", distance, force);
        }
        return 0;
    }

    Explanation:

    The C program calculates the gravitational force between the Earth and Mercury based on the universal gravitation formula using a for loop. The distance starts at the average distance and increases in steps. Observe how the gravitational force changes as the distance increases.

    4. Important notes

    • Initialization: The starting point of your loop. This is usually where you declare and initialize the loop counter.
    • Condition: The condition that must be true for the loop to continue executing. Once this condition becomes false, the loop stops.
    • Increment/Decrement: This is used to update the counter after each iteration (either incrementing or decrementing).

    5. Summary

    The for loop is a powerful tool for automating repetitive tasks and working with data in C programming. When you understand for loop syntax, you can write more efficient and clean code. Some example use case include iterating over numbers, performing calculations, or working with arrays. Feel free to experiment with the examples provided and start creating your own loops to practice.

feature-top
Readers’ comment
feature-top
Log in to add a comment
🔐 Access