Laboratory: Loops

Gábor Horváth / Zsolt Kohári · 2020.09.24.

Simple programs with loops.

1. Product of numbers

Let the product be 1.
Let n be 10.
As long as n≥2
    Let product be product × n.
    Decrease n by 1.
End of repetition
Print the pruduct.

Create a program that calculates the product of the first 10 numbers (1…10), which is 10 factorial. You may use the given pseudo code. Put an extra line in the loop to print the value of the loop variable and that of the product as well in order to see how the product develops.

2. Sum of divisors

Calculate the sum of divisors for a number entered by the user. (e.g. for 6: 1+2+3+6 = 12.) Modify your algorithm to exclude the number itself from the summation. What should be changed in the program?

Perfect number is an integer that equals to this sum (so the sum of divisors, including 1, excluding the number itself). The first perfect number is 6 as 1+2+3=6. The next two are 28 and 496. Print out if the number entered by the user is a perfect number or not.

Hint: Sum of divisors implies applying summation: a loop, and summing in the accumulator. In our case not all numbers in the loop qualify for being a divisor.

Solution

#include <stdio.h>

int main(void) {
    int number;
    printf("The number: ");
    scanf("%d", &number);

    int divisorsum = 0;
    /* divisor>number/2 can not occur (only the number itself could satisfy it) */
    for (int divisor = 1; divisor <= number / 2; divisor = divisor + 1)
        if (number % divisor == 0)
            divisorsum = divisorsum + divisor;

    if (divisorsum == number)
        printf("This is a perfect number.\n");
    else
        printf("The number is not perfect, %d != %d.\n", number, divisorsum);

    return 0;
}

3. Approximating Euler's number "e" (the base of the natural logarithm)

The natural number can e=2.7182818… can be obtained by the following infinite sum:

    1    1    1    1    1
e = ── + ── + ── + ── + ── + …
    0!   1!   2!   3!   4!

Write a program to compute it with the first 20 terms! Note that the factorial can be a high number, use a double data type to store it!

Hint: if you have used nested loops, try to simplify your solution! A single loop is enough to solve the problem.

Solution

#include <stdio.h>

int main(void) {
    double e = 0;
    double fact = 1;
    for (int i = 1; i < 20; i = i+1) {
        e = e + 1/fact;  /* Add it to the sum */
        fact = fact * i;    /* The factorial is computed in this variable */
    }

    printf("e = %f",e);  /* Print the result */

    return 0;
}

4. Approximating π, method I.

John Wallis, British mathematician developed the following expression to compute the constant π:
π   2·2   4·4   6·6   8·8
─ = ─── · ─── · ─── · ─── · …
2   1·3   3·5   5·7   7·9

Identify the repeating pattern in the formula, and write a program to evaluate it up to the first n factors (n is obtained from the user). Test the program with n=10, n=100 and n=1000 settings!

Solution

#include <stdio.h>

int main(void) {
    double pi = 1;
    for (int i = 2; i<10000; i = i + 2) /* two by two */
        pi = pi * i*i / ((i-1)*(i+1));   /* the next factor */
    pi = pi * 2;                         /* multiply *2 at the end to get pi from pi/2 */

    printf("%f", pi);

    return 0;
}

5. Approximating π, method II.

Leibniz found the expression below to approximate π. The more terms are taken into account, the more accurate the approximation is. Write a program to approximate π with this method!

π       1   1   1
─ = 1 - ─ + ─ - ─ + …
4       3   5   7

There are several potential pitfalls in this task. If the output of the program is not correct, run the debugger, and follow the program execution and the evolution of the variables step-by-step!

Hint: note that the additions and subtractions are alternating. It might be worth to compute the sum such that two terms are computed in each iteration of the loop. This way checking the loop variable whether it is even or odd is not necessary.

Important: use real data types (float or double), since the result is not integer. In C, if two integer numbers are divided, the result will be integer as well. Hence, 1/3, in C, gives 0. However, 1.0/3 gives 0.333333 that is the correct value. We are going to discuss this issue at a later lecture.

Solution

#include <stdio.h>

int main(void) {
    /* Loop computing two terms in each iteration */
    /* in every iteration it adds one term and subtracts an other */
    double pi = 0;
    int i = 1;
    while (i<100000) {
        pi = pi + 1.0/i;  /* Add the inverse of the current number to pi */
        i = i + 2;        /* The current number is increased by 2 */
        pi = pi - 1.0/i;  /* Subtract the inverse of the number */
        i = i + 2;        /* The current number is increased by 2 */
    }

    pi = pi*4;  /* The loop approximates pi/4, hence we have to multiply it by 4 to get pi */

    printf("%f", pi);  /* print result */

    return 0;
}