Dr. Roger Ianjamasimanana

C while loop with practical examples in Astronomy

By Dr. Roger Ianjamasimanana

In this guide, we’ll learn how to use the while loop in C programming. We’ll go over different examples to help you understand the syntax and logic behind this fundamental control flow structure. By the end, you'll be able to write your own loops for various scenarios, and we’ll apply our knowledge to a basic Astronomy problem.

1. What is the C while loop?

The while loop is one of the most essential looping structures in C. It repeats a block of code as long as a specified condition evaluates to true. It's ideal when you don’t know in advance how many iterations you’ll need, but you know the condition to stop.

2. While loop syntax in C

Here’s the general while loop syntax in C:


while (condition) {
    // code to be executed
}

In the above syntax, the condition is checked before each iteration. If it evaluates to true, the code inside the block is executed. If it evaluates to false, the loop terminates.

3. While loop examples

3.1 Counting from 1 to 5

Let's see a basic example of how a while loop works:


#include <stdio.h>

int main() {
    int i = 1;

    while (i <= 5) {
        printf("%d\n", i);  // prints the value of i
        i++;  // increments i by 1
    }

    return 0;
}

This program uses a while loop to print the numbers from 1 to 5. Here's what’s happening:

  • The condition i <= 5 checks if i is less than or equal to 5.
  • If the condition is true, the program enters the loop and prints the value of i.
  • The value of i is incremented by 1 each time.
  • This repeats until i becomes 6, at which point the loop exits.

3.2 Calculating factorial using a while loop

Now, let's look at a slightly more complex example: calculating the factorial of a number using a while loop. The factorial of a number n is the product of all positive integers less than or equal to n:


#include <stdio.h>
int main() {
    int number = 3;  // Calculate the factorial of 5
    int factorial = 1;
    int original_number = number; // Store the original value of the number
    while (number > 1) {
        factorial *= number;
        number--;
    }   

    printf("The factorial of %d is: %d\n", original_number, factorial);
    return 0;
}            

Here’s what happens in this example:

  • The initial value of factorial is set to 1.
  • While number is greater than 1, the loop continues multiplying factorial by the current value of number and then decreases number by 1.
  • Once the number reaches 1, the loop exits, and the factorial of 5 is displayed.

3.3 Using a while loop to find prime numbers

We can use the while loop to find prime numbers within a given range. A prime number is a number greater than 1 that is divisible only by 1 and itself.


#include <stdio.h>
int main() {
    int number = 2; 
    while (number <= 100) {
        int divisor = 2;
        int is_prime = 1;

        while (divisor < number) { 
            if (number % divisor == 0) {
                is_prime = 0;
                break;      
            }           
            divisor++;  
        }

        if (is_prime) {
            printf("%d is a prime number \n", number);
        }
        number++;   
    }

    return 0;   
} 
        

This code checks for prime numbers between 2 and 100. Here’s a breakdown:

  • The outer while loop iterates through numbers from 2 to 100.
  • The inner while loop checks if the current number is divisible by any number other than 1 and itself.
  • If a divisor is found, is_prime is set to 0, and the inner loop breaks.
  • If no divisors are found, the number is printed as a prime number.

3.4 A practical example in Astronomy: calculating the mass of planets

Let’s take a practical example in Astronomy to use the C while loop.

To calculate the mass of planets, we use Kepler’s third law of planetary motion. The law relates the orbital period \( T \) and the semi-major axis \( a \) of a satellite (like Io) to the planet’s mass \( M \).

The formula for Kepler’s third law is:

$$ T^2 = \frac{4 \pi^2 a^3}{G M} $$

Rearranging this equation to solve for \( M \), we get:

$$ M = \frac{4 \pi^2 a^3}{G T^2} $$

Where:

  • \( T \) = Orbital period of the satellite (in seconds)
  • \( a \) = Distance (semi-major axis) between the satellite and the center of the planet (in meters)
  • \( G \) = Gravitational constant (\( 6.67430 \times 10^{-11} \, \text{m}^3 \, \text{kg}^{-1} \, \text{s}^{-2} \))
  • \( M \) = In our case, it's the mass of the planet (what we are trying to calculate)

For this calculation, we use data from the following moons and their planets:

  • Jupiter — Moon: Io (\( T = 1.769 \, \text{days} \), \( a = 4.22 \times 10^8 \, \text{m} \))
  • Saturn — Moon: Titan (\( T = 15.945 \, \text{days} \), \( a = 1.22 \times 10^9 \, \text{m} \))
  • Earth — Moon: The Moon (\( T = 27.322 \, \text{days} \), \( a = 3.84 \times 10^8 \, \text{m} \))
 
#include <stdio.h>
#include <math.h>

int main() {
    // Gravitational constant (m^3 kg^-1 s^-2)
    double G = 6.67430e-11; 

    // Data of each planet's moon
    double orbital_periods[] = {1.769 * 24 * 60 * 60, 15.945 * 24 * 60 * 60, 27.322 * 24 * 60 * 60}; 
    double distances[] = {4.22e8, 1.22e9, 3.84e8}; 
    char *planet_names[] = {"Jupiter", "Saturn", "Earth"}; 

    // Loop variables
    double numerator, denominator, mass;
    int i = 0;

    printf("Mass of planets using Kepler's third law:\n\n");

    while (i < 3) {
        numerator = 4 * M_PI * M_PI * pow(distances[i], 3); 
        denominator = G * pow(orbital_periods[i], 2); 
        mass = numerator / denominator; 

        printf("Planet: %s\n", planet_names[i]);
        printf("Mass of %s: %.2e kg\n\n", planet_names[i], mass);

        i++; // Increment the loop counter
    }

    return 0;
}                 

            

Explanation of the code:

  • We define the G constant, which is the gravitational constant.
  • For each planet, we store the orbital period \(T\) (in seconds) and distance \(a\) (in meters) of its moon. We also store the names of the planets.
  • We use a for loop to calculate the mass for each planet. The formula used for each iteration is: \( M = \frac{4 \pi^2 a^3}{G T^2} \)
  • After calculating the mass, it is printed in scientific notation using the %.2e format.

After running the program, you will see the following output:

Mass of planets using Kepler's third law:

Planet: Jupiter
Mass of Jupiter: 1.90e+27 kg

Planet: Saturn
Mass of Saturn: 5.68e+26 kg

Planet: Earth
Mass of Earth: 5.97e+24 kg
            

These values are consistent with the known masses of Jupiter, Saturn, and Earth. Learn more about the mass of planets in the NASA website.

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