C Programs

C Programming – Conditional Statements


1. Maximum and Minimum of Three Numbers


Problem Statement

Write a C program to find the maximum and minimum among three numbers.

Algorithm
  1. Start
  2. Read three numbers a, b and c
  3. Assume a is the current maximum and minimum
  4. Compare b and c with the current maximum to find the largest value
  5. Compare b and c with the current minimum to find the smallest value
  6. Display the maximum and minimum values
  7. Stop
C Program

                        #include <stdio.h>

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

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

                            // Assume a is both maximum and minimum at the beginning
                            max = a;
                            min = a;

                            // Update maximum if a bigger value is found
                            if (b > max) max = b;
                            if (c > max) max = c;

                            // Update minimum if a smaller value is found
                            if (b < min) min = b;
                            if (c < min) min = c;

                            printf("Maximum = %d\n", max);
                            printf("Minimum = %d\n", min);

                            return 0;
                        }
                            
Sample Output

                        Enter three numbers:
                        12 5 20
                        Maximum = 20
                        Minimum = 5
                            
Explanation

The program first assumes that a is both the maximum and minimum value, then uses if conditions to compare b and c with the current max and min. Whenever a bigger or smaller value is found, the corresponding variable is updated.

This step-by-step comparison avoids using complex expressions and makes the logic easier to follow, especially when introducing conditional statements for the first time.

2. Leap Year Check


Problem Statement

Write a C program to check whether a given year is a leap year or not.

Algorithm
  1. Start
  2. Read a year
  3. Check if the year is divisible by 400
  4. If not, check if it is divisible by 4 but not by 100
  5. If any of the above conditions is true, it is a leap year; otherwise, it is not
  6. Display the result
  7. Stop
C Program

                        #include <stdio.h>

                        int main() {
                            int year;

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

                            // 1. Divisible by 400  -> Leap year
                            // 2. Else, divisible by 4 but not by 100 -> Leap year
                            if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
                                printf("Leap Year\n");
                            else
                                printf("Not a Leap Year\n");

                            return 0;
                        }
                            
Sample Output

                        Enter a year:
                        2000
                        Leap Year
                            
Explanation

A year is a leap year if it is exactly divisible by 400, or if it is divisible by 4 but not divisible by 100. These conditions are combined in a single if statement using logical operators && (AND) and || (OR).

This rule ensures that years like 2000 and 2400 are leap years, while years like 1900 and 2100 are not, even though they are divisible by 4, because they are also divisible by 100 but not by 400.

3. Roots of a Quadratic Equation


Problem Statement

Write a C program to find the roots of a quadratic equation of the form \(ax^2+bx+c = 0 \) .

Algorithm
  1. Start
  2. Read coefficients a, b and c
  3. Compute the discriminant d = b*b - 4*a*c
  4. If d > 0, roots are real and distinct
  5. If d == 0, roots are real and equal
  6. If d < 0, roots are imaginary (no real roots)
  7. Use the appropriate formula to compute and display the roots
  8. Stop
C Program

                        #include <stdio.h>
                        #include <math.h>

                        int main() {
                            float a, b, c, d, r1, r2;

                            printf("Enter coefficients a, b and c:\n");
                            scanf("%f %f %f", &a, &b, &c);

                            d = b * b - 4 * a * c;  // Discriminant

                            if (d > 0) {
                                // Two distinct real roots
                                r1 = (-b + sqrt(d)) / (2 * a);
                                r2 = (-b - sqrt(d)) / (2 * a);
                                printf("Roots are real and distinct\n");
                                printf("Root1 = %.2f\nRoot2 = %.2f\n", r1, r2);
                            } else if (d == 0) {
                                // Two equal real roots
                                r1 = -b / (2 * a);
                                printf("Roots are real and equal\n");
                                printf("Root1 = %.2f\nRoot2 = %.2f\n", r1, r1);
                            } else {
                                // d < 0: no real roots
                                printf("Roots are imaginary (no real roots)\n");
                            }

                            return 0;
                        }
                            
Sample Output

                        Enter coefficients a, b and c:
                        1 5 6
                        Roots are real and distinct
                        Root1 = -2.00
                        Root2 = -3.00
                            
Explanation

The nature of the roots of a quadratic equation depends on the discriminant d = b*b - 4*a*c. A positive discriminant gives two different real roots, zero gives two equal real roots, and a negative discriminant means there are no real roots.

The sqrt() function from math.h is used to compute the square root of the discriminant. The corresponding formulas are applied inside the if, else if and else blocks to compute and display the correct type of roots based on the value of d.

4. Check Whether a Number is Power of 2 using Bitwise Operators


Problem Statement

Write a C program to check whether the given number is a power of 2 using bitwise operators.

Algorithm
  1. Start
  2. Read an integer number n
  3. If n <= 0, it is not a power of 2
  4. Otherwise, check the condition (n & (n - 1)) == 0
  5. If the condition is true, display "Power of 2"
  6. Else, display "Not a Power of 2"
  7. Stop
C Program

                        #include <stdio.h>

                        int main() {
                            int n;

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

                            // A positive number n is a power of 2
                            // if and only if n & (n - 1) is 0
                            if (n > 0 && (n & (n - 1)) == 0)
                                printf("The number is a Power of 2\n");
                            else
                                printf("The number is NOT a Power of 2\n");

                            return 0;
                        }
                            
Sample Output

                        Enter a number:
                        16
                        The number is a Power of 2
                            
Explanation

A number that is a power of 2 has exactly one bit set to 1 in its binary representation (for example, 1, 2, 4, 8, 16). The expression n & (n - 1) clears the lowest set bit of n; for powers of 2 this makes the result 0, while for other numbers it does not.

The additional check n > 0 ensures that zero and negative numbers are correctly rejected, because they are not considered powers of 2 in this context.

5. Student Grade Calculation Based on Percentage


Problem Statement

Write a C program to read marks of three subjects, calculate the percentage, and display the grade of a student.

Algorithm
  1. Start
  2. Read marks of three subjects m1, m2 and m3
  3. Compute the total and then the percentage using average of three marks
  4. Use an if–else ladder to decide the grade based on the percentage
  5. Display the percentage and the grade
  6. Stop
C Program

                        #include <stdio.h>

                        int main() {
                            int m1, m2, m3;
                            float percentage;

                            printf("Enter marks of three subjects:\n");
                            scanf("%d %d %d", &m1, &m2, &m3);

                            // Average of three subjects gives the percentage (assuming each is out of the same maximum marks)
                            percentage = (m1 + m2 + m3) / 3.0f;

                            printf("Percentage = %.2f\n", percentage);

                            if (percentage >= 90)
                                printf("Grade: A\n");
                            else if (percentage >= 75)
                                printf("Grade: B\n");
                            else if (percentage >= 60)
                                printf("Grade: C\n");
                            else
                                printf("Grade: Fail\n");

                            return 0;
                        }
                            
Sample Output

                        Enter marks of three subjects:
                        85 90 80
                        Percentage = 85.00
                        Grade: B
                            
Explanation

The program first computes the average of the three subject marks by dividing their sum by 3.0f, which forces floating-point division and preserves decimal accuracy in the percentage value. The formatted output %.2f prints the percentage with two digits after the decimal point, which is standard in academic reports.

An if–else ladder then checks the percentage from highest range to lowest, assigning grades A, B, C or Fail. Because the conditions are checked in order, a student who satisfies a higher range is not rechecked for lower ranges, which keeps the logic clear and unambiguous.

6. Arithmetic Operations using Switch Statement


Problem Statement

Write a C program to perform basic arithmetic operations on two integers using a switch statement.

Algorithm
  1. Start
  2. Read two integer numbers a and b
  3. Display a menu of arithmetic operations
  4. Read the user’s choice
  5. Use a switch statement to perform the selected operation
  6. Check for division by zero in case of division
  7. Display the result or an appropriate error message
  8. Stop
C Program

                        #include <stdio.h>

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

                            printf("Enter two numbers:\n");
                            scanf("%d %d", &a, &b);

                            printf("1. Add\n");
                            printf("2. Subtract\n");
                            printf("3. Multiply\n");
                            printf("4. Divide\n");
                            printf("Enter your choice:\n");
                            scanf("%d", &choice);

                            switch (choice) {
                                case 1:
                                    printf("Sum = %d\n", a + b);
                                    break;
                                case 2:
                                    printf("Difference = %d\n", a - b);
                                    break;
                                case 3:
                                    printf("Product = %d\n", a * b);
                                    break;
                                case 4:
                                    if (b != 0)
                                        printf("Quotient = %d\n", a / b);
                                    else
                                        printf("Division by zero not allowed\n");
                                    break;
                                default:
                                    printf("Invalid choice\n");
                            }

                            return 0;
                        }
                            
Sample Output

                        Enter two numbers:
                        20 4
                        1. Add
                        2. Subtract
                        3. Multiply
                        4. Divide
                        Enter your choice:
                        4
                        Quotient = 5
                            
Explanation

The switch statement selects one block of code to execute based on the value of choice, which is entered by the user. Each case corresponds to a specific arithmetic operation, and the break statements prevent execution from falling through to the next case.

Before performing division, the program checks whether b is zero to avoid a division-by-zero error. The default case handles invalid menu choices, making the program more robust and user-friendly.