Week 3 Programming Questions

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

Filter:
Sort:

Question 1

Write a C program that prompts the user to input grades for Arithmetic, Algebra, Geometry, and Data Analysis. The program should compute the Total Grade, finding the area with the Lowest Grade.

Example:

Enter Arithmetic grade: 85
Enter Algebra grade: 90
Enter Geometry grade: 78
Enter Data Analysis grade: 88
Total Grade: 341.00
Lowest grade is: 78.00 in Geometry
Solution
#include <stdio.h>

int main() {
    float arithmetic, algebra, geometry, analysis;
    float total, min_grade;

    printf("Enter Arithmetic grade: ");
    scanf("%f", &arithmetic);
    printf("Enter Algebra grade: ");
    scanf("%f", &algebra);
    printf("Enter Geometry grade: ");
    scanf("%f", &geometry);
    printf("Enter Data Analysis grade: ");
    scanf("%f", &analysis);

    total = arithmetic + algebra + geometry + analysis;
    printf("Total Grade: %.2f\n", total);

    min_grade = arithmetic;
    
    if (algebra < min_grade) 
        min_grade = algebra;
    if (geometry < min_grade) 
        min_grade = geometry;
    if (analysis < min_grade) 
        min_grade = analysis;

    printf("Lowest grade is: %.2f in ", min_grade);

    if (min_grade == arithmetic) 
        printf("Arithmetic\n");
    else if (min_grade == algebra) 
        printf("Algebra\n");
    else if (min_grade == geometry) 
        printf("Geometry\n");
    else 
        printf("Data Analysis\n");

    return 0;
}

                        
#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    float arithmetic, algebra, geometry, analysis;
    float total, min_grade;

    cout << "Enter Arithmetic grade: ";
    cin >> arithmetic;
    cout << "Enter Algebra grade: ";
    cin >> algebra;
    cout << "Enter Geometry grade: ";
    cin >> geometry;
    cout << "Enter Data Analysis grade: ";
    cin >> analysis;

    total = arithmetic + algebra + geometry + analysis;
    cout << "Total Grade: " << fixed << setprecision(2) << total << "\n";

    min_grade = arithmetic;
    
    if (algebra < min_grade) 
        min_grade = algebra;
    if (geometry < min_grade) 
        min_grade = geometry;
    if (analysis < min_grade) 
        min_grade = analysis;

    cout << "Lowest grade is: " << fixed << setprecision(2) << min_grade << " in ";

    if (min_grade == arithmetic) 
        cout<<"Arithmetic\n";
    else if (min_grade == algebra)
        cout<<"Algebra\n";
    else if (min_grade == geometry) 
        cout<<"Geometry\n";
    else 
        cout<<"Data Analysis\n";

    return 0;
}

                        

Question 2

Write a function named `LeapYear` that receives a year (integer) and displays whether it is a Leap Year or not.

Example:
Enter year: 2024
2024 is a Leap Year
Leap Year Logic
Solution
#include <stdio.h>

void LeapYear(int year) {
    if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
        printf("%d is a Leap Year\n", year);
    } else {
        printf("%d is not a Leap Year\n", year);
    }
}

int main() {
    int y;
    printf("Enter year: ");
    scanf("%d", &y);
    LeapYear(y);
    return 0;
}

                        
#include <iostream>

using namespace std;

void LeapYear(int year) {
    if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
        cout << year << " is a Leap Year\n";
    } else {
        cout << year << " is not a Leap Year\n";
    }
}

int main() {
    int y;
    cout << "Enter year: ";
    cin >> y;
    LeapYear(y);
    return 0;
}

                        

Question 3

Write a function named WeatherState that receives temperature (°C) and displays a message based on the status:

  • Temp < 0: Freezing weather
  • Temp 0 - 10: Very Cold weather
  • Temp 10 - 20: Cold weather
  • Temp 20 - 30: Normal in Temp
  • Temp 30 - 40: It’s Hot
  • Temp >= 40: It’s Very Hot

Example:

Enter temperature: 15
Cold weather
Solution
#include <stdio.h>

void WeatherState(int temp) {
    if (temp < 0) {
        printf("Freezing weather\n");
    } else if (temp >= 0 && temp < 10) {
        printf("Very Cold weather\n");
    } else if (temp >= 10 && temp < 20) {
        printf("Cold weather\n");
    } else if (temp >= 20 && temp < 30) {
        printf("Normal in Temp\n");
    } else if (temp >= 30 && temp < 40) {
        printf("It's Hot\n");
    } else {
        printf("It's Very Hot\n");
    }
}

int main() {
    int t;
    printf("Enter temperature: ");
    scanf("%d", &t);
    WeatherState(t);
    return 0;
}

                        
#include <iostream>

using namespace std;

void WeatherState(int temp) {
    if (temp < 0) {
        cout << "Freezing weather\n";
    } else if (temp >= 0 && temp < 10) {
        cout << "Very Cold weather\n";
    } else if (temp >= 10 && temp < 20) {
        cout << "Cold weather\n";
    } else if (temp >= 20 && temp < 30) {
        cout << "Normal in Temp\n";
    } else if (temp >= 30 && temp < 40) {
        cout << "It's Hot\n";
    } else {
        cout << "It's Very Hot\n";
    }
}

int main() {
    int t;
    cout << "Enter temperature: ";
    cin >> t;
    WeatherState(t);
    return 0;
}

                        

Question 4

Write a function TriangleType that receives 3 integer edges and checks if the triangle is:

  • Equilateral: All sides equal.
  • Isosceles: Two sides equal.
  • Scalene: All sides different.

Example:

Enter 3 edges: 5 5 5
Equilateral
Solution
#include <stdio.h>

void TriangleType(int a, int b, int c) {
    if (a == b && b == c) {
        printf("Equilateral\n");
    } else if (a == b || b == c || a == c) {
        printf("Isosceles\n");
    } else {
        printf("Scalene\n");
    }
}

int main() {
    int s1, s2, s3;
    printf("Enter 3 edges: ");
    scanf("%d %d %d", &s1, &s2, &s3);
    TriangleType(s1, s2, s3);
    return 0;
}

                        
#include <iostream>

using namespace std;

void TriangleType(int a, int b, int c) {
    if (a == b && b == c) {
        cout << "Equilateral\n";
    } else if (a == b || b == c || a == c) {
        cout << "Isosceles\n";
    } else {
        cout << "Scalene\n";
    }
}

int main() {
    int s1, s2, s3;
    cout << "Enter 3 edges: ";
    cin >> s1 >> s2 >> s3;
    TriangleType(s1, s2, s3);
    return 0;
}

                        

Question 5

Write a function VowelTest that checks if an input character is a Vowel (a, e, i, o, u) or Consonant.

Example:

Enter a character: e
e is a Vowel
Solution
#include <stdio.h>

void VowelTest(char c) {
    if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ||
        c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') {
        printf("%c is a Vowel\n", c);
    } else {
        printf("%c is a Consonant\n", c);
    }
}

int main() {
    char ch;
    printf("Enter a character: ");
    scanf(" %c", &ch);
    VowelTest(ch);
    return 0;
}

                        
#include <iostream>

using namespace std;

void VowelTest(char c) {
    if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ||
        c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') {
        cout << c << " is a Vowel\n";
    } else {
        cout << c << " is a Consonant\n";
    }
}

int main() {
    char ch;
    cout << "Enter a character: ";
    cin >> ch;
    VowelTest(ch);
    return 0;
}

                        

Question 6

Write a function CharTest that checks if an input is:

  • Alphabet (A-Z, a-z)
  • Digit (0-9)
  • Special Character (others)

Example:

Enter character: $
Special Character
Solution
#include <stdio.h>

void CharTest(char c) {
    if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
        printf("Alphabet\n");
    } else if (c >= '0' && c <= '9') {
        printf("Digit\n");
    } else {
        printf("Special Character\n");
    }
}

int main() {
    char ch;
    printf("Enter character: ");
    scanf(" %c", &ch);
    CharTest(ch);
    return 0;
}

                        
#include <iostream>

using namespace std;

void CharTest(char c) {
    if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
        cout << "Alphabet\n";
    } else if (c >= '0' && c <= '9') {
        cout << "Digit\n";
    } else {
        cout << "Special Character\n";
    }
}

int main() {
    char ch;
    cout << "Enter character: ";
    cin >> ch;
    CharTest(ch);
    return 0;
}

                        

Question 7

Write a void function printAscending that receives 3 integers and prints them from smallest to largest.

Example:

Enter 3 numbers: 15 3 29
Numbers in Ascending Order: 3 15 29
Solution
#include <stdio.h>

void printAscending(int a, int b, int c) {
    if (a <= b && a <= c) {
        if (b <= c)
            printf("Numbers in Ascending Order: %d %d %d\n", a, b, c);
        else
            printf("Numbers in Ascending Order: %d %d %d\n", a, c, b);
    }
    else if (b <= a && b <= c) {
        if (a <= c)
            printf("Numbers in Ascending Order: %d %d %d\n", b, a, c);
        else
            printf("Numbers in Ascending Order: %d %d %d\n", b, c, a);
    }
    else { 
        if (a <= b)
            printf("Numbers in Ascending Order: %d %d %d\n", c, a, b);
        else
            printf("Numbers in Ascending Order: %d %d %d\n", c, b, a);
    }
}

int main() {
    int a, b, c;

    printf("Enter 3 numbers: ");
    scanf("%d %d %d", &a, &b, &c);

    printAscending(a, b, c);

    return 0;
}

                        
#include <iostream>

using namespace std;

void printAscending(int a, int b, int c) {
    if (a <= b && a <= c) {
        if (b <= c)
            cout << "Numbers in Ascending Order: " << a << " " << b << " " << c << endl;
        else
            cout << "Numbers in Ascending Order: " << a << " " << c << " " << b << endl;
    }
    else if (b <= a && b <= c) {
        if (a <= c)
            cout << "Numbers in Ascending Order: " << b << " " << a << " " << c << endl;
        else
            cout << "Numbers in Ascending Order: " << b << " " << c << " " << a << endl;
    }
    else { 
        if (a <= b)
            cout << "Numbers in Ascending Order: " << c << " " << a << " " << b << endl;
        else
            cout << "Numbers in Ascending Order: " << c << " " << b << " " << a << endl;
    }
}

int main() {
    int a, b, c;

    cout << "Enter 3 numbers: ";
    cin >> a >> b >> c;

    printAscending(a, b, c);

    return 0;
}

                        

Question 8

Write a menu-driven program to compute perimeter:
  • 1. Circle (circle_per(r))
  • 2. Rectangle (rect_per(a, b))
  • 3. Triangle (tri_per(a, b, c))
Example:
1. Circle
2. Rectangle
3. Triangle
Enter choice: 1
Enter radius: 5
Perimeter: 31.42
Perimeter Formulas
Solution
#include <stdio.h>

const double PI = 3.14159;

double circle_per(double r) {
    return 2 * PI * r;
}

double rect_per(double a, double b) {
    return 2 * (a + b);
}

double tri_per(double a, double b, double c) {
    return a + b + c;
}

int main() {
    int choice;
    double val1, val2, val3;

    printf("1. Circle\n");
    printf("2. Rectangle\n");
    printf("3. Triangle\n");
    printf("Enter choice: ");
    scanf("%d", &choice);

    switch(choice) {
        case 1:
            printf("Enter radius: ");
            scanf("%lf", &val1);
            printf("Perimeter: %.2lf\n", circle_per(val1));
            break;
        case 2:
            printf("Enter length and width: ");
            scanf("%lf %lf", &val1, &val2);
            printf("Perimeter: %.2lf\n", rect_per(val1, val2));
            break;
        case 3:
            printf("Enter 3 sides: ");
            scanf("%lf %lf %lf", &val1, &val2, &val3);
            printf("Perimeter: %.2lf\n", tri_per(val1, val2, val3));
            break;
        default:
            printf("Invalid choice.\n");
    }

    return 0;
}

                        
#include <iostream>
#include <iomanip>

using namespace std;
const double PI = 3.14159;

double circle_per(double r) {
    return 2 * PI * r;
}

double rect_per(double a, double b) {
    return 2 * (a + b);
}

double tri_per(double a, double b, double c) {
    return a + b + c;
}

int main() {
    int choice;
    double val1, val2, val3;

    cout << "1. Circle\n";
    cout << "2. Rectangle\n";
    cout << "3. Triangle\n";
    cout << "Enter choice: ";
    cin >> choice;

    switch(choice) {
        case 1:
            cout << "Enter radius: ";
            cin >> val1;
            cout << "Perimeter: " << fixed << setprecision(2) << circle_per(val1) << endl;
            break;
        case 2:
            cout << "Enter length and width: ";
            cin >> val1 >> val2;
            cout << "Perimeter: " << fixed << setprecision(2) << rect_per(val1, val2) << endl;
            break;
        case 3:
            cout << "Enter 3 sides: ";
            cin >> val1 >> val2 >> val3;
            cout << "Perimeter: " << fixed << setprecision(2) << tri_per(val1, val2, val3) << endl;
            break;
        default:
            cout << "Invalid choice.\n";
    }

    return 0;
}

                        

Question 9

Trace the following program options to find which expression evaluates to true when $x = 5$ and $y = 10$:

A) x > y
B) x == y
C) x != y && x > 0
D) x >= 5 && y < 10

Solution
C

                        
C

                        

Question 10

Trace the following program and determine the printed output:

int number = 0;

if (number = 0) {
    printf("The number is zero.");
} else {
    printf("The number is not zero.");
}

Warning: Note the operator used inside the if statement condition.

Solution
// Uses assignment (=) instead of comparison (==) inside if statement and invalid print;
// correct to if (number == 0)

                        
// Uses assignment (=) instead of comparison (==) inside if statement and invalid print;
// correct to if (number == 0)

                        

Question 11

Write a function IsValidDate() that takes day, month, and year as integer inputs and returns 1 (true) if the date is valid or 0 (false) if it is invalid. You must account for different month lengths and leap years (February has 29 days in a leap year).

In main(), prompt the user for the day, month, and year, pass them to the function, and print whether the date is valid or invalid.

Example:

Enter day, month, year: 29 2 2023
Date is Invalid
Solution
#include <stdio.h>

int IsValidDate(int day, int month, int year);

int main() {
    int day, month, year;

    printf("Enter day, month, year: ");
    scanf("%d %d %d", &day, &month, &year);

    if (IsValidDate(day, month, year)) {
        printf("Date is Valid\n");
    } else {
        printf("Date is Invalid\n");
    }

    return 0;
}   

int IsValidDate(int day, int month, int year) {
    if (year <= 0 || month < 1 || month > 12 || day < 1) {
        return 0;
    }

    int maxDays = 31;

    if (month == 4 || month == 6 || month == 9 || month == 11) {
        maxDays = 30;
    } else if (month == 2) {
        int isLeap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
        maxDays = isLeap ? 29 : 28;
    }

    return day <= maxDays;
}

                        
#include <iostream>
using namespace std;

bool IsValidDate(int day, int month, int year);

int main() {
    int day, month, year;

    cout << "Enter day, month, year: ";
    cin >> day >> month >> year;

    if (IsValidDate(day, month, year)) {
        cout << "Date is Valid" << endl;
    } else {
        cout << "Date is Invalid" << endl;
    }

    return 0;
}

bool IsValidDate(int day, int month, int year) {
    if (year <= 0 || month < 1 || month > 12 || day < 1) {
        return false;
    }

    int maxDays = 31;

    if (month == 4 || month == 6 || month == 9 || month == 11) {
        maxDays = 30;
    } else if (month == 2) {
        bool isLeap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
        maxDays = isLeap ? 29 : 28;
    }

    return day <= maxDays;
}

                        

Question 12

Write a function PlayRPS() that takes the player’s choice as a character ('R', 'P', or 'S') and generates a random computer choice. Print both choices and determine the winner (Player wins, Computer wins, or Tie).

In main(), prompt the user for their choice, call the function, and let the game play out.

Example:

Enter choice (R = Rock, P = Paper, S = Scissors): R
Computer chose: Scissors
Player wins!
Solution
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void PlayRPS(char playerChoice);

int main() {
    srand(time(NULL));
    char choice;

    printf("Enter choice (R = Rock, P = Paper, S = Scissors): ");
    scanf(" %c", &choice);

    PlayRPS(choice);

    return 0;
}

void PlayRPS(char playerChoice) {
    int randNum = rand() % 3;
    char compChoice;

    if (randNum == 0) {
        compChoice = 'R';
    } else if (randNum == 1) {
        compChoice = 'P';
    } else {
        compChoice = 'S';
    }

    if (compChoice == 'R') {
        printf("Computer chose: Rock\n");
    } else if (compChoice == 'P') {
        printf("Computer chose: Paper\n");
    } else {
        printf("Computer chose: Scissors\n");
    }

    if (playerChoice == compChoice) {
        printf("It's a tie!\n");
    } else if ((playerChoice == 'R' && compChoice == 'S') ||
               (playerChoice == 'P' && compChoice == 'R') ||
               (playerChoice == 'S' && compChoice == 'P')) {
        printf("Player wins!\n");
    } else {
        printf("Computer wins!\n");
    }
}

                        
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

void PlayRPS(char playerChoice);

int main() {
    srand(time(NULL));
    char choice;

    cout << "Enter choice (R = Rock, P = Paper, S = Scissors): ";
    cin >> choice;

    PlayRPS(choice);

    return 0;
}

void PlayRPS(char playerChoice) {
    int randNum = rand() % 3;
    char compChoice;

    if (randNum == 0) {
        compChoice = 'R';
    } else if (randNum == 1) {
        compChoice = 'P';
    } else {
        compChoice = 'S';
    }

    if (compChoice == 'R') {
        cout << "Computer chose: Rock" << endl;
    } else if (compChoice == 'P') {
        cout << "Computer chose: Paper" << endl;
    } else {
        cout << "Computer chose: Scissors" << endl;
    }

    if (playerChoice == compChoice) {
        cout << "It's a tie!" << endl;
    } else if ((playerChoice == 'R' && compChoice == 'S') ||
               (playerChoice == 'P' && compChoice == 'R') ||
               (playerChoice == 'S' && compChoice == 'P')) {
        cout << "Player wins!" << endl;
    } else {
        cout << "Computer wins!" << endl;
    }
}

                        

Question 13

Trace the following program and determine the printed output values of $x$, $y$, and $z$:

int x = 5;
int y = 0;
int z = 10;

if (x > 3 || ++y > 0) {
    z += 5;
}
if (x < 3 && ++y > 0) {
    z += 10;
}
printf("x = %d, y = %d, z = %d\n", x, y, z);

Note: Pay attention to short-circuit evaluation rules for conditional operators || and &&.

Solution
// Output: x = 5, y = 0, z = 15
// Explanation: In both if statements, the first condition determines the outcome, so short-circuiting skips evaluating ++y.

                        
// Output: x = 5, y = 0, z = 15
// Explanation: In both if statements, the first condition determines the outcome, so short-circuiting skips evaluating ++y.