C All Exercises & Assignments

Write a C program to check whether a number is even or odd

Description: Take a number as input. Print if it is even or odd.

Hint:

  • A number is even when the remainder of the division by 2 is zero.

C program to check even or odd

#include <stdio.h>

int main(void) {
    int n;

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

    if (n % 2 == 0) {
        printf("%d is even\n", n);
    } else {
        printf("%d is odd\n", n);
    }
    return 0;
}

Output:

Output of the above program is

Enter a number: 27
27 is odd

How it works

  • 27 % 2 gives 1, so the number is odd.
  • For negative numbers it also works, because -4 % 2 is 0.

Write a C program to swap the values of two variables using a third variable

Description: Take two numbers as input and swap their values using a third variable.

Hint:

  • Save the first value in a temporary variable, then copy the second into the first, and last put the temporary value in the second.

C program to swap two numbers using a third variable

#include <stdio.h>

int main(void) {
    int a, b, temp;

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

    temp = a;
    a = b;
    b = temp;

    printf("After swapping: a = %d, b = %d\n", a, b);
    return 0;
}

Output:

Output of the above program is

Enter two numbers: 10 20
After swapping: a = 20, b = 10

How it works

  • temp = a saves 10, a = b makes a = 20, and b = temp makes b = 10.
  • Without temp the first value would be lost.

Write a C program to check whether a user is eligible to vote or not

Description: Take the age of a person as input. If the age is 18 or more, print that the person can vote.

Hint:

  • Use the >= operator with if else.

C program to check the voting eligibility

#include <stdio.h>

int main(void) {
    int age;

    printf("Enter your age: ");
    scanf("%d", &age);

    if (age >= 18) {
        printf("You are eligible to vote\n");
    } else {
        printf("You are not eligible to vote\n");
    }
    return 0;
}

Output:

Output of the above program is

Enter your age: 17
You are not eligible to vote

How it works

  • The condition age >= 18 is false for 17, so the else block runs.

Read C If Else Statement.

Write a C program to check whether an alphabet is vowel or consonant

Description: Take an alphabet as input. Print if it is a vowel or a consonant.

Hint:

  • The vowels are a, e, i, o, u (in small and capital letters). Convert the letter to lower case with tolower() to keep the code short.

C program to check vowel or consonant

#include <stdio.h>
#include <ctype.h>

int main(void) {
    char ch;

    printf("Enter an alphabet: ");
    scanf(" %c", &ch);

    switch (tolower(ch)) {
        case 'a': case 'e': case 'i': case 'o': case 'u':
            printf("%c is a vowel\n", ch);
            break;
        default:
            if (isalpha(ch)) {
                printf("%c is a consonant\n", ch);
            } else {
                printf("%c is not an alphabet\n", ch);
            }
    }
    return 0;
}

Output:

Output of the above program is

Enter an alphabet: E
E is a vowel

How it works

  • tolower('E') gives 'e', which matches a vowel case.
  • The space before %c in scanf(" %c") skips the white spaces, like the Enter key.
  • isalpha() checks that the input is a letter.

Read C Switch Statement.

Write a C program to find the maximum number between three numbers

Description: Take three numbers as input and print the largest one.

Hint:

  • Compare the numbers using the >= and && operators.

C program to find the largest of three numbers

#include <stdio.h>

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

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

    if (a >= b && a >= c) {
        max = a;
    } else if (b >= a && b >= c) {
        max = b;
    } else {
        max = c;
    }
    printf("Largest = %d\n", max);
    return 0;
}

Output:

Output of the above program is

Enter three numbers: 12 45 30
Largest = 45

How it works

  • We check if a is greater than or equal to both others. If not, we check b, and otherwise c must be the largest.
  • Using >= also works when two numbers are equal.

Write a C program to check whether a number is positive, negative or zero

Description: Take a number as input. Print if it is positive, negative or zero.

Hint:

  • Compare the number with 0 using > and <.

C program to check positive, negative or zero

#include <stdio.h>

int main(void) {
    int n;

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

    if (n > 0) {
        printf("Positive number\n");
    } else if (n < 0) {
        printf("Negative number\n");
    } else {
        printf("Zero\n");
    }
    return 0;
}

Output:

Output of the above program is

Enter a number: -8
Negative number

How it works

  • The first condition n > 0 is false for -8, the second n < 0 is true, so “Negative number” is printed.

Read Else If Ladder.

Write a C program to calculate an electricity bill

Description: Take the units of electricity used as input and calculate the bill with these rates:

  • First 100 units: Rs 5 per unit
  • Next 100 units (101 to 200): Rs 7 per unit
  • Above 200 units: Rs 10 per unit

C program to calculate the electricity bill

#include <stdio.h>

int main(void) {
    int units;
    float bill;

    printf("Enter units used: ");
    scanf("%d", &units);

    if (units <= 100) {
        bill = units * 5;
    } else if (units <= 200) {
        bill = 100 * 5 + (units - 100) * 7;
    } else {
        bill = 100 * 5 + 100 * 7 + (units - 200) * 10;
    }
    printf("Electricity bill = Rs %.2f\n", bill);
    return 0;
}

Output:

Output of the above program is

Enter units used: 250
Electricity bill = Rs 1700.00

How it works

  • For 250 units: first 100 units cost 500, the next 100 units cost 700, and the last 50 units cost 500.
  • Total is 500 + 700 + 500 = 1700.

Read Else If Ladder.

Write a C program to print 1 to 10 numbers using a while loop

Description: Print the numbers from 1 to 10 using a while loop.

Hint:

  • Start with a counter of 1, and increase it in each round until it is more than 10.

C program to print 1 to 10 using a while loop

#include <stdio.h>

int main(void) {
    int i = 1;

    while (i <= 10) {
        printf("%d ", i);
        i++;
    }
    printf("\n");
    return 0;
}

Output:

Output of the above program is

1 2 3 4 5 6 7 8 9 10

How it works

  • The counter i starts at 1.
  • The loop runs while i <= 10, prints the value and then increases it with i++.
  • When i becomes 11, the condition is false and the loop stops.

Read C While Loop.

Write a C program to print words using spacing and new line characters

Description: Print the words Learn, C and Programming in a new line each, and then in one line with tab spaces.

Hint:

  • Use \n for a new line and \t for a tab space.

C program to print words with escape sequences

#include <stdio.h>

int main(void) {
    printf("Learn\nC\nProgramming\n");
    printf("Learn\tC\tProgramming\n");
    return 0;
}

Output:

Output of the above program is

Learn
C
Programming
Learn C Programming

How it works

  • One printf() can print many lines. We only write \n where the new line is needed.
  • \t adds a horizontal tab between the words.

Read C Escape Sequences.

Write a C program to print a right triangle star pattern

Description: Print a right triangle of stars with 5 rows. The first row has one star, the second has two, and so on.

Hint:

  • Use two loops. The outer loop is for rows and the inner loop is for stars in that row.

C program to print a right triangle of stars

#include <stdio.h>

int main(void) {
    int rows = 5;

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

Output:

Output of the above program is

*
* *
* * *
* * * *
* * * * *

How it works

  • The outer loop variable i is the row number.
  • The inner loop prints i stars in row i.
  • printf("\n") moves to the next row.

Read C Nested Loops.

Write a C program to get the salary from the user and print it

Description: Ask the user to enter a salary. Store it in a variable and print it on the screen.

Hint:

  • Use a float variable and the %f format specifier.

C program to read and print the salary

#include <stdio.h>

int main(void) {
    float salary;

    printf("Enter the salary: ");
    scanf("%f", &salary);
    printf("Your salary is %.2f\n", salary);
    return 0;
}

Output:

Output of the above program is

Enter the salary: 45000.50
Your salary is 45000.50

How it works

  • scanf() reads the number typed by the user and stores it at the address of salary (&salary).
  • %.2f prints the value with two digits after the decimal point.

Read C printf and scanf.

Write a C program to find the size of int, float, long, double and char

Description: Print the size (in bytes) of the basic data types of C.

Hint:

  • Use the sizeof operator and the %zu format specifier.

C program to find the size of data types

#include <stdio.h>

int main(void) {
    printf("int    : %zu bytes\n", sizeof(int));
    printf("float  : %zu bytes\n", sizeof(float));
    printf("long   : %zu bytes\n", sizeof(long));
    printf("double : %zu bytes\n", sizeof(double));
    printf("char   : %zu byte\n", sizeof(char));
    return 0;
}

Output:

Output of the above program is

int : 4 bytes
float : 4 bytes
long : 8 bytes
double : 8 bytes
char : 1 byte

How it works

  • sizeof gives the size of a type in bytes. It returns the type size_t, which is printed with %zu.
  • The sizes can change on a different computer. For example, long is 4 bytes on 64 bit Windows. This output is from a 64 bit Mac.

Read C Data Types.

Write a C program to get the marks of 5 subjects and find the total and average

Description: Take the marks of 5 subjects as input. Print the total and the average.

Hint:

  • Average is total / 5. Use float so the decimal part is not lost.

C program to find total and average marks

#include <stdio.h>

int main(void) {
    int m1, m2, m3, m4, m5, total;
    float average;

    printf("Enter marks of 5 subjects: ");
    scanf("%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5);

    total = m1 + m2 + m3 + m4 + m5;
    average = total / 5.0f;

    printf("Total = %d\n", total);
    printf("Average = %.2f\n", average);
    return 0;
}

Output:

Output of the above program is

Enter marks of 5 subjects: 70 65 80 90 55
Total = 360
Average = 72.00

How it works

  • The 5 values are read with one scanf().
  • We divide by 5.0f (a float), so the result keeps its decimal part. With 5 the division would be an integer division.

Read C Type Casting.

Write a C program to calculate the perimeter of a rectangle

Description: Take the height and width of a rectangle as input, and print its perimeter.

Hint:

  • Perimeter = 2 x (height + width).

C program to calculate the perimeter of a rectangle

#include <stdio.h>

int main(void) {
    float height, width, perimeter;

    printf("Enter height and width: ");
    scanf("%f %f", &height, &width);

    perimeter = 2 * (height + width);
    printf("Perimeter = %.2f\n", perimeter);
    return 0;
}

Output:

Output of the above program is

Enter height and width: 5 3.5
Perimeter = 17.00

How it works

  • The user enters the height and width.
  • We use the formula 2 * (height + width) and print the result.

Write a C program to convert minutes into hours and minutes

Description: Take the total minutes from the user, and print how many hours and minutes it is.

Hint:

  • Hours = minutes / 60 (integer division). Remaining minutes = minutes % 60.

C program to convert minutes to hours and minutes

#include <stdio.h>

int main(void) {
    int total, hours, minutes;

    printf("Enter minutes: ");
    scanf("%d", &total);

    hours = total / 60;
    minutes = total % 60;
    printf("%d minutes = %d hours and %d minutes\n", total, hours, minutes);
    return 0;
}

Output:

Output of the above program is

Enter minutes: 135
135 minutes = 2 hours and 15 minutes

How it works

  • 135 / 60 is 2 (integer division), so there are 2 full hours.
  • 135 % 60 is 15, the minutes which are left.

Read C Operators.

Write a C program to calculate the sum of three numbers

Description: Take three numbers as input and print their sum.

Hint:

  • Read the numbers with scanf() and add them with the + operator.

C program to calculate the sum of three numbers

#include <stdio.h>

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

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

    printf("Sum = %d\n", a + b + c);
    return 0;
}

Output:

Output of the above program is

Enter three numbers: 10 20 30
Sum = 60

How it works

  • The three numbers are stored in a, b and c.
  • The expression a + b + c is calculated and printed.

Write a C program to calculate the area of a square

Description: Take the side of a square as input and print its area.

Hint:

  • Area of a square = side x side.

C program to calculate the area of a square

#include <stdio.h>

int main(void) {
    float side, area;

    printf("Enter the side: ");
    scanf("%f", &side);

    area = side * side;
    printf("Area = %.2f\n", area);
    return 0;
}

Output:

Output of the above program is

Enter the side: 4.5
Area = 20.25

How it works

  • The side is read as a float, so decimal values also work.
  • The area is side * side, and %.2f prints two decimal digits.

Write a C program to convert Celsius to Fahrenheit

Description: Take a temperature in Celsius and print it in Fahrenheit.

Hint:

  • Fahrenheit = (Celsius x 9 / 5) + 32. Write 9.0 / 5 to avoid integer division.

C program to convert Celsius to Fahrenheit

#include <stdio.h>

int main(void) {
    float celsius, fahrenheit;

    printf("Enter temperature in Celsius: ");
    scanf("%f", &celsius);

    fahrenheit = celsius * 9.0f / 5 + 32;
    printf("%.1f C = %.1f F\n", celsius, fahrenheit);
    return 0;
}

Output:

Output of the above program is

Enter temperature in Celsius: 37
37.0 C = 98.6 F

How it works

  • 37 * 9.0 / 5 is 66.6, and adding 32 gives 98.6.
  • If we write 9 / 5 with integers, the result is 1 and the answer is wrong.

Read C Type Casting.

Write a C program to convert centimeters to meters and kilometers

Description: Take a length in centimeters and print it in meters and kilometers.

Hint:

  • 1 meter = 100 cm and 1 kilometer = 100000 cm.

C program to convert centimeters to meters and kilometers

#include <stdio.h>

int main(void) {
    float cm, meter, km;

    printf("Enter length in cm: ");
    scanf("%f", &cm);

    meter = cm / 100;
    km = cm / 100000;
    printf("Meters = %.2f\n", meter);
    printf("Kilometers = %.5f\n", km);
    return 0;
}

Output:

Output of the above program is

Enter length in cm: 25000
Meters = 250.00
Kilometers = 0.25000

How it works

  • We divide the centimeters by 100 to get meters, and by 100000 to get kilometers.
  • The variables are float, so the decimal part is not lost.

Write a C program to calculate 5% DA of a salary

Description: Take the basic salary as input. Calculate 5% DA on it and print the DA and the total salary.

Hint:

  • DA = salary x 5 / 100.

C program to calculate the DA of a salary

#include <stdio.h>

int main(void) {
    float salary, da, total;

    printf("Enter basic salary: ");
    scanf("%f", &salary);

    da = salary * 5 / 100;
    total = salary + da;

    printf("DA = %.2f\n", da);
    printf("Total salary = %.2f\n", total);
    return 0;
}

Output:

Output of the above program is

Enter basic salary: 20000
DA = 1000.00
Total salary = 21000.00

How it works

  • 5% of 20000 is 20000 * 5 / 100 = 1000.
  • The total salary is the basic salary plus the DA.