Post

Week 4: Control Statements (Looping & Branching) — Solution

Week 4: Control Statements (Looping & Branching) — Solution

Exercise Solutions

Exercise 1: Sum of even numbers from 2 to 20

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>

int main(void) {
    int sum = 0;
    for (int i = 2; i <= 20; i += 2) {
        sum += i;
    }
    printf("Sum of even numbers from 2 to 20 = %d\n", sum);
    return 0;
}

Example Output:

1
Sum of even numbers from 2 to 20 = 110

Exercise 2: Multiplication table with user-defined size

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>

int main(void) {
    int n;
    printf("Enter the size of the multiplication table: ");
    scanf("%d", &n);

    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            printf("%4d ", i * j);
        }
        printf("\n");
    }
    return 0;
}

Example Output:

1
2
3
4
5
6
Enter the size of the multiplication table: 5
   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

Exercise 3: Pass / Fail check (passing mark = 50)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdio.h>

int main(void) {
    int score;
    printf("Enter exam score: ");
    scanf("%d", &score);

    if (score >= 50) {
        printf("Pass\n");
    } else {
        printf("Fail\n");
    }
    return 0;
}

Example Output:

1
2
Enter exam score: 72
Pass

Exercise 4: Basic calculator using switch

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>

int main(void) {
    double a, b;
    char op;

    printf("Enter expression (e.g. 3 + 4): ");
    scanf("%lf %c %lf", &a, &op, &b);

    switch (op) {
        case '+': printf("Result: %.2f\n", a + b); break;
        case '-': printf("Result: %.2f\n", a - b); break;
        case '*': printf("Result: %.2f\n", a * b); break;
        case '/':
            if (b != 0) printf("Result: %.2f\n", a / b);
            else        printf("Error: division by zero\n");
            break;
        default:
            printf("Unknown operator: %c\n", op);
    }
    return 0;
}

Example Output:

1
2
Enter expression (e.g. 3 + 4): 12 * 5
Result: 60.00

Exercise 5: Largest of two numbers using the conditional operator

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>

int main(void) {
    int a, b;
    printf("Enter two numbers: ");
    scanf("%d %d", &a, &b);

    int max = (a > b) ? a : b;
    printf("Largest: %d\n", max);
    return 0;
}

Example Output:

1
2
Enter two numbers: 17 42
Largest: 42

Bonus Challenge: Right-angled triangle pattern

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>

int main(void) {
    int n;
    printf("Enter number of rows: ");
    scanf("%d", &n);

    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++) {
            printf("* ");
        }
        printf("\n");
    }
    return 0;
}

Example Output (n = 5):

1
2
3
4
5
*
* *
* * *
* * * *
* * * * *
This post is licensed under CC BY 4.0 by the author.