Week 4 & 5 Programming Exercises

Note: Try to solve these Exercises on your own before checking the solutions.


Filter:
Sort:

Exercise 1: Divisors

Write a CC++ program that reads in a positive integer and prints all the divisors of the integer in decreasing order.

  • Input: A single positive integer.
  • Output: All divisors separated by spaces.

Example:

Enter a positive integer: 12
Divisors of 12 in decreasing order: 12 6 4 3 2 1 
Solution
#include <stdio.h>

int main() {
    int n, i;

    printf("Enter a positive integer: ");
    scanf("%d", &n);

    printf("Divisors of %d in decreasing order: ", n);
    for(i = n; i >= 1; i--) {
        if(n % i == 0) {
            printf("%d ", i);
        }
    }
    printf("\n");

    return 0;
}
                        
#include <iostream>
using namespace std;

int main() {
    int n;

    cout << "Enter a positive integer: ";
    cin >> n;

    cout << "Divisors of " << n << " in decreasing order: ";
    for (int i = n; i >= 1; i--) {
        if (n % i == 0) {
            cout << i << " ";
        }
    }
    cout << "\n";

    return 0;
}

                        

Exercise 2: Power Calculation

Write a CC++ program that reads in two positive integers base and exp and prints the result of:

\[result = base^{exp}\]

In main(), you need to input the values for base and exp, calculate the power using a loop, and print the result.

Example:

Enter base and exponent: 2 5
2^5 = 32
Solution
#include <stdio.h>

int main() {
    int base, exp;
    long long result = 1;

    printf("Enter base and exponent: ");
    scanf("%d %d", &base, &exp);

    for(int i = 0; i < exp; i++) {
        result *= base;
    }

    printf("%d^%d = %lld\n", base, exp, result);

    return 0;
}
                        
#include <iostream>
using namespace std;

int main() {
    int base, exp;
    long long result = 1;

    cout << "Enter base and exponent: ";
    cin >> base >> exp;

    for (int i = 0; i < exp; i++) {
        result *= base;
    }

    cout << base << "^" << exp << " = " << result << "\n";

    return 0;
}

                        

Exercise 3: Factorial

Write a CC++ program that reads in a positive integer n and prints the result of n! (Factorial), where:

\[n! = 1 \times 2 \times \dots \times n\]

In main(), check if the number is negative (factorial doesn’t exist), otherwise calculate and print the factorial.

Example:

Enter a positive integer: 5
5! = 120
Solution
#include <stdio.h>

int main() {
    int n;
    int fact = 1;

    printf("Enter a positive integer: ");
    scanf("%d", &n);

    for(int i = 1; i <= n; i++) {
        fact *= i;
    }

    printf("%d! = %d\n", n, fact);

    return 0;
}
                        
#include <iostream>
using namespace std;

int main() {
    int n;
    int fact = 1;

    cout << "Enter a positive integer: ";
    cin >> n;

    for (int i = 1; i <= n; i++) {
        fact *= i;
    }

    cout << n << "! = " << fact << "\n";

    return 0;
}

                        

Exercise 4: Prime Check

Write a CC++ program that reads in an integer and checks whether the given number is Prime or not.

A Prime Number is a natural number greater than 1 that has no positive divisors other than 1 and itself.

In main(), read the number and use a flag or counter to determine if it has any divisors other than 1 and itself.

Example 1:

Enter an integer: 7
7 is a Prime number.

Example 2:

Enter an integer: 10
10 is not a Prime number.
Solution
#include <stdio.h>

int main() {
    int n, i, isPrime = 1;

    printf("Enter an integer: ");
    scanf("%d", &n);

    if (n <= 1) {
        isPrime = 0;
    } else {
        for(i = 2; i <= n / 2; i++) {
            if(n % i == 0) {
                isPrime = 0;
                break;
            }
        }
    }

    if(isPrime) {
        printf("%d is a Prime number.\n", n);
    } else {
        printf("%d is not a Prime number.\n", n);
    }

    return 0;
}
                        
#include <iostream>
using namespace std;

int main() {
    int n, i, isPrime = 1;

    cout << "Enter an integer: ";
    cin >> n;

    if (n <= 1) {
        isPrime = 0;
    } else {
        for (i = 2; i <= n / 2; i++) {
            if (n % i == 0) {
                isPrime = 0;
                break;
            }
        }
    }

    if (isPrime) {
        cout << n << " is a Prime number.\n";
    } else {
        cout << n << " is not a Prime number.\n";
    }

    return 0;
}

                        

Exercise 5: Reverse Number

Write a CC++ program that reads a positive integer number and prints the number with its digits reversed.

Example:

Enter a number: 5892
Reversed number: 2985

Note: Your program should work for any number of digits.

Solution
#include <stdio.h>

int main() {
    int n, reversed = 0, remainder;

    printf("Enter a number: ");
    scanf("%d", &n);

    while(n != 0) {
        remainder = n % 10;
        reversed = reversed * 10 + remainder;
        n /= 10;
    }

    printf("Reversed number: %d\n", reversed);

    return 0;
}
                        
#include <iostream>
using namespace std;

int main() {
    int n, reversed = 0, remainder;

    cout << "Enter a number: ";
    cin >> n;

    while (n != 0) {
        remainder = n % 10;
        reversed = reversed * 10 + remainder;
        n /= 10;
    }

    cout << "Reversed number: " << reversed << "\n";

    return 0;
}

                        

Exercise 6: Sum of Digits

Write a program that reads an integer number and prints the sum of its digits.

Example:

Enter an integer: 467
Sum of digits: 17

(Calculation: \(4 + 6 + 7 = 17\))

Solution
#include <stdio.h>

int main() {
    int n, sum = 0, remainder;

    printf("Enter an integer: ");
    scanf("%d", &n);

    if(n < 0) n = -n;

    while(n > 0) {
        remainder = n % 10;
        sum += remainder;
        n /= 10;
    }

    printf("Sum of digits: %d\n", sum);

    return 0;
}
                        
#include <iostream>
using namespace std;

int main() {
    int n, sum = 0, remainder;

    cout << "Enter an integer: ";
    cin >> n;

    if (n < 0) n = -n;

    while (n > 0) {
        remainder = n % 10;
        sum += remainder;
        n /= 10;
    }

    cout << "Sum of digits: " << sum << "\n";

    return 0;
}

                        

Exercise 7: Range Printer

Write a function printRange(int m, int n) that prints all numbers from m to n.

  • The function should print an error message if \(m > n\).
  • Challenge: Try implementing this using for, while, and do-while loops.

In main(), input two integers from the keyboard and pass them to your function.

Example:

Enter m and n: 3 7
Expected output: 3 4 5 6 7 
Solution
#include <stdio.h>

void printRange(int m, int n) {
    if (m > n) {
        printf("Error: m is greater than n.\n");
        return;
    }

    printf("Range: ");
    for (int i = m; i <= n; i++) {
        printf("%d ", i);
    }
    printf("\n");
}

int main() {
    int m, n;

    printf("Enter m and n: ");
    scanf("%d %d", &m, &n);

    printRange(m, n);

    return 0;
}
                        
#include <iostream>
using namespace std;

void printRange(int m, int n) {
    if (m > n) {
        cout << "Error: m is greater than n.\n";
        return;
    }

    cout << "Range: ";
    for (int i = m; i <= n; i++) {
        cout << i << " ";
    }
    cout << "\n";
}

int main() {
    int m, n;

    cout << "Enter m and n: ";
    cin >> m >> n;

    printRange(m, n);

    return 0;
}

                        

Exercise 8: Modular Functions

Write the following functions and call them from main(). Do not use the math.h library.

  1. Power(float N, int M): Computes and returns \(N^M\).
  2. DigitsNum(int N): Returns the number of digits in N.
  3. DigitsAvg(int N): Returns the average of the digits of N.
  4. IsPrimeEfficient(int N): Returns 1 if N is prime, and 0 otherwise.

In main(), you need to input values, call these functions, and print the results demonstrating they work.

Example:

Enter a float base and integer exponent for Power(): 2.5 3
Result: 15.62

Enter a positive integer for Digit operations and Prime check: 12345
Number of digits: 5
Average of digits: 3.00
12345 is Not Prime
Solution
#include <stdio.h>

double Power(float N, int M) {
    double result = 1.0;
    for(int i = 0; i < M; i++) {
        result *= N;
    }
    return result;
}

int DigitsNum(int N) {
    int count = 0;
    if (N == 0) return 1;
    while(N != 0) {
        N /= 10;
        count++;
    }
    return count;
}

double DigitsAvg(int N) {
    int sum = 0, count = 0, digit;
    int tempN = N;
    
    if (N == 0) return 0.0;

    while(tempN != 0) {
        digit = tempN % 10;
        sum += digit;
        tempN /= 10;
        count++;
    }
    return (double)sum / count;
}

int IsPrimeEfficient(int N) {
    if (N <= 1) return 0;
    for(int i = 2; i * i <= N; i++) {
        if (N % i == 0) return 0;
    }
    return 1;
}

int main() {
    float fNum;
    int intNum, powerExp;

    printf("Enter a float base and integer exponent for Power(): ");
    scanf("%f %d", &fNum, &powerExp);
    printf("Result: %.2f\n\n", Power(fNum, powerExp));

    printf("Enter a positive integer for Digit operations and Prime check: ");
    scanf("%d", &intNum);

    printf("Number of digits: %d\n", DigitsNum(intNum));
    printf("Average of digits: %.2f\n", DigitsAvg(intNum));

    if(IsPrimeEfficient(intNum)) {
        printf("%d is Prime\n", intNum);
    } else {
        printf("%d is Not Prime\n", intNum);
    }

    return 0;
}
                        
#include <iostream>
#include <iomanip>
using namespace std;

double Power(float N, int M) {
    double result = 1.0;
    for (int i = 0; i < M; i++) {
        result *= N;
    }
    return result;
}

int DigitsNum(int N) {
    int count = 0;
    if (N == 0) return 1;
    while (N != 0) {
        N /= 10;
        count++;
    }
    return count;
}

double DigitsAvg(int N) {
    int sum = 0, count = 0, digit;
    int tempN = N;

    if (N == 0) return 0.0;

    while (tempN != 0) {
        digit = tempN % 10;
        sum += digit;
        tempN /= 10;
        count++;
    }
    return (double)sum / count;
}

int IsPrimeEfficient(int N) {
    if (N <= 1) return 0;
    for (int i = 2; i * i <= N; i++) {
        if (N % i == 0) return 0;
    }
    return 1;
}

int main() {
    float fNum;
    int intNum, powerExp;

    cout << "Enter a float base and integer exponent for Power(): ";
    cin >> fNum >> powerExp;
    cout << "Result: " << fixed << setprecision(2) << Power(fNum, powerExp) << "\n\n";

    cout << "Enter a positive integer for Digit operations and Prime check: ";
    cin >> intNum;

    cout << "Number of digits: " << DigitsNum(intNum) << "\n";
    cout << "Average of digits: " << fixed << setprecision(2) << DigitsAvg(intNum) << "\n";

    if (IsPrimeEfficient(intNum)) {
        cout << intNum << " is Prime\n";
    } else {
        cout << intNum << " is Not Prime\n";
    }

    return 0;
}

                        

Exercise 9

What is the output of the following code?

#include<stdio.h>
int main() {
    int myList[] = {0, 1, 2, 3, 4, 5};
    for (int i = 4; i >= 0; i--) {
        myList[i + 1] = myList[i];
    }
    for (int i = 0; i < 6; i++)
        printf("%d ", myList[i]);
    return 0;
}
#include<iostream>
using namespace std;
int main() {
    int myList[] = {0, 1, 2, 3, 4, 5};
    for (int i = 4; i >= 0; i--) {
        myList[i + 1] = myList[i];
    }
    for (int i = 0; i < 6; i++)
        cout << myList[i] << " ";
    return 0;
}
Solution
0 0 1 2 3 4 
                        
0 0 1 2 3 4 
                        

Exercise 10

What is the value of indexOfMax after executing the following code?

#include<stdio.h>
int main() {
    int myList[] = {1, 5, 5, 5, 5, 1};
    int max = myList[0];
    int indexOfMax = 0;
    for (int i = 1; i < 6; i++) {
        if (myList[i] > max) {
            max = myList[i];
            indexOfMax = i;
        }
    }
    printf("%d", indexOfMax);
    return 0;
}
#include<iostream>
using namespace std;
int main() {
    int myList[] = {1, 5, 5, 5, 5, 1};
    int max = myList[0];
    int indexOfMax = 0;
    for (int i = 1; i < 6; i++) {
        if (myList[i] > max) {
            max = myList[i];
            indexOfMax = i;
        }
    }
    cout << indexOfMax;
    return 0;
}

Think: What would be the value of indexOfMax if the condition was myList[i] >= max?

Solution
1

// Answer to Think:
// If the condition was >=, the answer would be 4.
                        
1
                        

Exercise 11

Which of the following code segments produces the following output: 1 4 9 16 25?

a.

int i = 0; 
while (i < 5) { 
    i = i + 1;
    printf("%d ", i * i);
}

b.

int i = 0; 
while (i <= 5) {
    i = i + 1;
    printf("%d ", i * i);
}

c.

int i = 0; 
while (i <= 5) {
    printf("%d ", i * i);
    i = i + 1;
}

d.

int i = 0; 
while (i < 5) {
    printf("%d ", i * i);
    i = i + 1;
}

a.

int i = 0; 
while (i < 5) { 
    i = i + 1;
    cout << i * i << " ";
}

b.

int i = 0; 
while (i <= 5) {
    i = i + 1;
    cout << i * i << " ";
}

c.

int i = 0; 
while (i <= 5) {
    cout << i * i << " ";
    i = i + 1;
}

d.

int i = 0; 
while (i < 5) {
    cout << i * i << " ";
    i = i + 1;
}
Solution
A
                        
A

                        

Exercise 12

Which of the following code segments will not finish (go to infinite loop)?

a.

int i = 1;
int j = 0;
while (i != 10) {
    j = i * 5;
    printf("%d", j);
    i = i + 1;
}

b.

int i = 1;
int j = 0;
while (i != 10) {
    j = i * 5;
    printf("%d", j);
    i = i + 2;
}

c.

int i = 1;
int j = 0;
while (i <= 10) {
    j = i * 3;
    printf("%d", j);
    i = i + 2;
}

d.

int i = 1;
int j = 0;
while (i <= 10) {
    j = i * 3;
    printf("%d", j);
    i = i + 5;
}

a.

int i = 1;
int j = 0;
while (i != 10) {
    j = i * 5;
    cout << j;
    i = i + 1;
}

b.

int i = 1;
int j = 0;
while (i != 10) {
    j = i * 5;
    cout << j;
    i = i + 2;
}

c.

int i = 1;
int j = 0;
while (i <= 10) {
    j = i * 3;
    cout << j;
    i = i + 2;
}

d.

int i = 1;
int j = 0;
while (i <= 10) {
    j = i * 3;
    cout << j;
    i = i + 5;
}
Solution
B
                        
B

                        

Exercise 13

What is the output of the following code? And what is the purpose of this code?

#include <stdio.h>

int main() {
    int a = 5, b = 10;
    a = a + b;
    b = a - b;
    a = a - b;
    printf("new values: a = %d, b = %d\n", a, b);

    return 0;
}
#include <iostream>
using namespace std;

int main() {
    int a = 5, b = 10;
    a = a + b;
    b = a - b;
    a = a - b;
    cout << "new values: a = " << a << ", b = " << b << "\n";

    return 0;
}
Solution
new values: a = 10, b = 5

// Swap two variables without using a temporary variable.
                        
new values: a = 10, b = 5

// Swap two variables without using a temporary variable.