This article provides 20+ essential C programming exercises and challenges designed to test and improve your understanding of variables, data types, and basic input/output (I/O).
If you’re a beginner learning C, understanding how to declare, initialize, and manipulate different types of data (like integers, floats, and characters) is absolutely essential before moving on to complex topics.
What You’ll Practice
Each exercise includes a Problem Statement, Hint, Solution code, and detailed Explanation, ensuring you don’t just copy code, but genuinely understand how and why it works.
The exercises cover the following core topics:
- Variable Fundamentals & I/O: Variable Declaration, initialization, and assignment; basic scanf() and printf() input/output with proper format specifiers.
- Data Types: Use of int, float, double, and char, including type modifiers (
unsigned,long long,const). - Operations: Arithmetic operations (including the Modulo Operator) and Implicit/Explicit Type Casting.
- Advanced Basics: Using the sizeof operator and working with octal/hexadecimal literals.
Use Online C Compiler to solve exercises.
+ Table Of Contents (21 Exercises)
Table of contents
- Exercise 1: Integer Operations
- Exercise 2: Floating-Point Arithmetic
- Exercise 3: Character and ASCII
- Exercise 4: Size of Data Types
- Exercise 5: Type Casting
- Exercise 6: Variable Swapping (Third Variable)
- Exercise 7: Variable Swapping (Without Third Variable)
- Exercise 8: User Input
- Exercise 9: Area of a Circle
- Exercise 10: Average of Three Numbers
- Exercise 11: Integer Overflow
- Exercise 12: Long Long Integer
- Exercise 13: Decimal to Hexadecimal
- Exercise 14: Octal to Decimal
- Exercise 15: Constant Variables
- Exercise 16: ASCII to Character
- Exercise 17: Variable Scope
- Exercise 18: Casting with Expressions
- Exercise 19: ASCII Arithmetic
- Exercise 20: Formatted Output
- Exercise 21: Exponential Notation
Exercise 1: Integer Operations
Practice Problem: Write a C program that declares two integer variables, assigns them values, and prints their sum, difference, product, and quotient.
+ Hint
Use the arithmetic operators +, -, *, and / are used for addition, subtraction, multiplication, and division, respectively.
+ Show Solution
#include <stdio.h>
int main() {
int num1 = 10;
int num2 = 5;
int sum = num1 + num2;
int difference = num1 - num2;
int product = num1 * num2;
int quotient = num1 / num2;
printf("Sum: %d\n", sum);
printf("Difference: %d\n", difference);
printf("Product: %d\n", product);
printf("Quotient: %d\n", quotient);
return 0;
}Code language: C++ (cpp)
Explanation:
- Inside the
mainfunction, two integer variables,num1andnum2, are declared and initialized. - We then perform the four basic arithmetic operations and store the results in separate integer variables:
sum,difference,product, andquotient. - Finally,
printfis used to print the label for each result followed by its value, using the%dformat specifier to represent the integer data.
Exercise 2: Floating-Point Arithmetic
Practice Problem: Write a C program that declares two float variables and computes their sum, difference, and product. Print the results with two decimal places.
+ Hint
Use the float data type for the variables. When using printf, you can specify the number of decimal places to display using the format specifier %.2f.
+ Show Solution
#include <stdio.h>
int main() {
float f1 = 15.5f;
float f2 = 7.2f;
float sum = f1 + f2;
float difference = f1 - f2;
float product = f1 * f2;
printf("Sum: %.2f\n", sum);
printf("Difference: %.2f\n", difference);
printf("Product: %.2f\n", product);
return 0;
}Code language: C++ (cpp)
Explanation:
- The program uses
floatvariables for decimal numbers. Thefsuffix on the values ensures they are treated as floats. - The arithmetic operations are performed, and the results are printed using
printfwith the%.2fformat specifier, which limits the output to two decimal places.
Exercise 3: Character and ASCII
Practice Problem: Write a C program that takes a single character input from the user and prints its ASCII value.
+ Hint
Use the char data type to store the character. You can print the ASCII value of a character by using the %d format specifier instead of %c in printf.
+ Show Solution
#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
scanf(" %c", &ch);
printf("The ASCII value of '%c' is %d\n", ch, ch);
return 0;
}Code language: C++ (cpp)
Explanation:
- This program reads a character from the user using
scanfand stores it in acharvariable. - When
printfis called, the same variable is passed twice: once with%cto print the character itself, and again with%dto print its integer ASCII value. This works because C internally stores characters as their corresponding ASCII numbers.
Exercise 4: Size of Data Types
Practice Problem: Print the size of int, float, double, char, and long double on your system.
Expected Output:
Size of int: 4 bytes
Size of float: 4 bytes
Size of double: 8 bytes
Size of char: 1 bytes
Size of long double: 16 bytes
+ Hint
Use the The sizeof operator to get size in bytes. Use it with the data type name, like sizeof(int). The result is of type size_t and should be printed with the %zu format specifier.
+ Show Solution
#include <stdio.h>
int main() {
printf("Size of int: %zu bytes\n", sizeof(int));
printf("Size of float: %zu bytes\n", sizeof(float));
printf("Size of double: %zu bytes\n", sizeof(double));
printf("Size of char: %zu bytes\n", sizeof(char));
printf("Size of long double: %zu bytes\n", sizeof(long double));
return 0;
}Code language: C++ (cpp)
Explanation:
- The program uses the
sizeofoperator to check the memory footprint of different data types. This size can vary depending on the system’s architecture (e.g., 32-bit vs. 64-bit). - The
%zuformat specifier is the correct way to print thesize_tvalue returned bysizeof.
Exercise 5: Type Casting
Practice Problem: Write a C program that declares an integer and a float. Perform a type cast to convert the float to an int and vice versa. Print both results.
Given:
int intVar = 10;
float floatVar = 25.75f;Code language: Python (python)
+ Hint
Type casting is an explicit conversion. The syntax is (new_data_type)variable_name.
+ Show Solution
#include <stdio.h>
int main() {
int intVar = 10;
float floatVar = 25.75f;
// Casting float to int
int castedInt = (int)floatVar;
printf("Casting float (%.2f) to int: %d\n", floatVar, castedInt);
// Casting int to float
float castedFloat = (float)intVar;
printf("Casting int (%d) to float: %.2f\n", intVar, castedFloat);
return 0;
}Code language: C++ (cpp)
Explanation:
- This program shows explicit type conversion.
- When a
floatis cast to anint, the decimal part is truncated. When anintis cast to afloat, it’s converted to a floating-point number with a decimal and a zero. The original variables remain unchanged.
Exercise 6: Variable Swapping (Third Variable)
Practice Problem: Swap the values of two integer variables using a third temporary variable. Print the values before and after the swap
Given:
int a = 5;
int b = 10;Code language: C/AL (cal)
Expected Output:
Before swap: a = 5, b = 10
After swap: a = 10, b = 5
+ Hint
Use a temporary variable as a placeholder to hold one of the values during the swap.
+ Show Solution
#include <stdio.h>
int main() {
int a = 5;
int b = 10;
int temp;
printf("Before swap: a = %d, b = %d\n", a, b);
temp = a;
a = b;
b = temp;
printf("After swap: a = %d, b = %d\n", a, b);
return 0;
}Code language: C++ (cpp)
Explanation:
- A third variable,
temp, is used to temporarily store the value ofa. - The value of
bis then assigned toa, and finally, the value fromtemp(the original value ofa) is assigned tob.
Exercise 7: Variable Swapping (Without Third Variable)
Practice Problem: Write a C program to swap the values of two integer variables without using a third variable.
Given:
int a = 5;
int b = 10;Code language: Python (python)
Expected Output:
Before swap: a = 5, b = 10
After swap: a = 10, b = 5
+ Hint
- Use a series of arithmetic operations to achieve the swap.
- A common method is
a = a + b, thenb = a - b, and finallya = a - b.
+ Show Solution
#include <stdio.h>
int main() {
int a = 5;
int b = 10;
printf("Before swap: a = %d, b = %d\n", a, b);
a = a + b;
b = a - b;
a = a - b;
printf("After swap: a = %d, b = %d\n", a, b);
return 0;
}Code language: C++ (cpp)
Explanation:
This technique uses a sequence of additions and subtractions to swap the values. It avoids the need for a temporary variable, but it’s important to be aware of potential integer overflow if the sum of the two variables exceeds the data type’s limit.
Exercise 8: User Input
Practice Problem: Prompt the user to enter his/her age and name. Store these values in variables and print them back to the user in a formatted sentence.
Expected Output:
You are 30 years old and your name is 'Jhon'.
+ Hint
Use printf for prompts and scanf for input. Remember to use the & operator before variable names in scanf.
+ Show Solution
#include <stdio.h>
int main() {
int age;
char name[50];
printf("Enter your age: ");
scanf("%d", &age);
printf("Enter your first name: ");
scanf("%s", name);
printf("You are %d years old and your name is '%s'.\n", age, name);
return 0;
}Code language: C++ (cpp)
Explanation:
This program takes user input using scanf. The & symbol is the address-of operator; it provides scanf with the memory address of the variable so it can store the input value there.
Exercise 9: Area of a Circle
Practice Problem: Declare a float variable for the radius of a circle, initialize it with value 5.0, and calculate its area. Use a constant for Pi (3.14159).
Expected Output:
The area of a circle with radius 5.00 is 78.54
+ Hint
- The formula for the area is A=πr2.
- You can use a constant for Pi by using the
#definepreprocessor directive.
+ Show Solution
#include <stdio.h>
#define PI 3.14159
int main() {
float radius = 5.0f;
float area = PI * radius * radius;
printf("The area of a circle with radius %.2f is %.2f\n", radius, area);
return 0;
}Code language: C++ (cpp)
Explanation:
- This program uses a
#defineconstant for Pi. - The preprocessor replaces all occurrences of
PIwith3.14159before the code compiles. - The area is calculated and printed with two decimal places using the
%.2fformat specifier.
Exercise 10: Average of Three Numbers
Practice Problem: Take three integer inputs from the user, calculate their average as a float, and print the result.
Expected Output:
Enter three integers: 10 20 30
The average is: 20.00
+ Hint
Use scanf to get three integer inputs. To ensure the average is a float, perform a type cast on one of the numbers before division, like (float)num1.
+ Show Solution
#include <stdio.h>
int main() {
int num1, num2, num3;
float average;
printf("Enter three integers: ");
scanf("%d %d %d", &num1, &num2, &num3);
average = (float)(num1 + num2 + num3) / 3;
printf("The average is: %.2f\n", average);
return 0;
}Code language: C++ (cpp)
Explanation:
- First, we take three integer values from the user.
- To calculate a precise average with decimal places, we need to perform floating-point division. By using the type cast
(float)on the sum, we force the entire expression to be evaluated as a float, ensuring the division by3yields a floating-point number.
Exercise 11: Integer Overflow
Practice Problem: Declare an int and assign it a value close to its maximum limit. Increment it by a small value (e.g., 1) to demonstrate integer overflow.
Expected Output:
Maximum value of int: 2147483647
After incrementing: -2147483648
+ Hint
The maximum value for a 32-bit signed int is 2147483647 (INT_MAX from ). When you go beyond this value, the number “wraps around” to the negative side.
+ Show Solution
#include <stdio.h>
#include <limits.h>
int main() {
int max_int = INT_MAX;
printf("Maximum value of int: %d\n", max_int);
int overflow_int = max_int + 1;
printf("After incrementing: %d\n", overflow_int);
return 0;
}Code language: C++ (cpp)
Explanation:
- This program illustrates a critical concept in C: integer overflow. The
INT_MAXmacro from the<limits.h>header provides the largest possible value for anint. When we add1toINT_MAX, the value exceeds the maximum capacity of the variable, causing it to wrap around to the lowest possible negative value. - This unexpected behavior highlights the importance of choosing the correct data type for the range of values you expect to handle.
Exercise 12: Long Long Integer
Practice Problem: Use a long long int to store a very large number and print its value.
+ Hint
The long long int data type is used for numbers larger than what a standard int can hold. Use the %lld format specifier with printf.
+ Show Solution
#include <stdio.h>
int main() {
long long int large_number = 9876543210987654321LL;
printf("The large number is: %lld\n", large_number);
return 0;
}Code language: C++ (cpp)
Explanation:
This program demonstrates how to handle values that exceed the range of a standard int. The long long int data type is at least 64 bits wide, capable of storing much larger numbers.
The LL suffix on the number literal explicitly tells the compiler to treat it as a long long int. The %lld format specifier is specifically used to print long long int values.
Exercise 13: Decimal to Hexadecimal
Practice Problem: Declare an integer variable, assign it a decimal value, and print its hexadecimal representation.
Given:
int decimal_num = 255;Code language: Python (python)
+ Hint
Use the %x format specifier in printf to display the hexadecimal value.
+ Show Solution
#include <stdio.h>
int main() {
int decimal_num = 255;
printf("The decimal number %d in hexadecimal is: %x\n", decimal_num, decimal_num);
return 0;
}Code language: C++ (cpp)
Explanation:
C’s printf function provides several format specifiers. The %x specifier directly interprets the integer value as a hexadecimal (base 16) number and prints its representation.
Exercise 14: Octal to Decimal
Practice Problem: Print decimal equivalent of a octal.
Given:
int octal_num = 015; // Represents 13 in decimalCode language: Python (python)
Expected Output:
The octal number 015 in decimal is: 13
+ Hint
In C, you can specify an octal literal by prefixing the number with a 0. Use the %o format specifier in scanf or printf to handle octal input/output. To print the decimal value, use %d.
+ Show Solution
#include <stdio.h>
int main() {
int octal_num = 015; // Represents 13 in decimal
printf("The octal number 015 in decimal is: %d\n", octal_num);
return 0;
}Code language: C++ (cpp)
Explanation:
This exercise highlights how C handles numbers in different bases. The leading 0 in 015 tells the compiler that the number is an octal (base 8) literal.
Internally, the computer still stores this value as its decimal equivalent (1*8^1 + 5*8^0 = 13). When we print the value using the %d format specifier, it is correctly displayed as 13.
Exercise 15: Constant Variables
Practice Problem: Declare a constant variable for a price or a fixed value, and then try to change its value to see the compile-time error.
+ Hint
The const keyword makes a variable read-only. Once initialized, its value cannot be modified during program execution.
+ Show Solution
#include <stdio.h>
int main() {
const float PI = 3.14159f;
// The following line will cause a compile-time error
// PI = 3.14f;
printf("The constant value of PI is: %f\n", PI);
return 0;
}Code language: C++ (cpp)
Explanation:
Once a const variable is initialized, any attempt to reassign it a new value will result in a compile-time error. This prevents accidental modification of important values in your code, making it safer and more reliable.
Exercise 16: ASCII to Character
Practice Problem: Take an integer input from the user (an ASCII value) and print the corresponding character.
+ Hint
Read the input using the int data type and the %d format specifier. Print the integer variable using the %c format specifier; C will automatically interpret the integer as an ASCII code.
+ Show Solution
#include <stdio.h>
int main() {
int ascii_val;
printf("Enter an ASCII value (0-127): ");
scanf("%d", &ascii_val);
printf("The character for ASCII %d is: %c\n", ascii_val, ascii_val);
return 0;
}Code language: C++ (cpp)
Explanation:
The program reads an integer value into ascii_val. This exercise showcases the relationship between integers and characters in C.
When the int variable is printed using the %c format specifier, the compiler treats the integer value as an ASCII code and outputs the corresponding character.
Exercise 17: Variable Scope
Practice Problem: Write a program with at least two blocks ({}) to demonstrate the concept of variable scope. Declare a variable in the outer block and another with the same name in the inner block. Print both to show their different scopes.
+ Hint
Variables declared inside a block are local to that block. A variable in an inner block can shadow (hide) a variable of the same name from an outer block.
+ Show Solution
#include <stdio.h>
int main() {
int x = 10; // Outer scope variable
printf("Outer x: %d\n", x);
{ // Start of Inner Block/Scope
int x = 50; // Inner scope variable (Shadows outer x)
int y = 5;
printf("Inner x: %d\n", x);
printf("Inner y: %d\n", y);
} // End of Inner Block/Scope
printf("Outer x (after inner block): %d\n", x);
// printf("%d", y); // This would cause a compile-time error!
return 0;
}Code language: C++ (cpp)
Explanation:
- This program demonstrates variable scope. The first
xis declared in themainfunction’s scope. - Inside the inner block, a new variable named
xis declared and initialized to50; this shadows the outerx. - The inner
printfsees the value50. After the inner block ends, the innerxis destroyed, and the outerx(value10) is visible again. Variables likeyare only accessible within their declared block.
Exercise 18: Casting with Expressions
Practice Problem: Declare an integer and a float. Perform a multiplication operation and explicitly cast the result to a int data type. Print the final value.
+ Hint
Declare an int and a float. Multiply them. The result will naturally be a float. Use a type cast to explicitly convert this floating-point result into an int, truncating the decimal part.
+ Show Solution
#include <stdio.h>
int main() {
int count = 7;
float price = 3.50f;
// Result of count * price is automatically a float (24.50)
float total_float = count * price;
// Explicitly cast the floating-point result to an integer
int total_int = (int)(count * price);
printf("Floating-point result: %.2f\n", total_float);
printf("Casted integer result (truncation): %d\n", total_int);
return 0;
}Code language: C++ (cpp)
Explanation:
- When mixing an
intand afloatin an expression (count * price), C performs implicit type promotion, converting theintto afloatbefore multiplication. - The result (
24.5) is afloat. The line withtotal_intuses an explicit type cast(int)to convert the floating-point result back to an integer, which truncates the fractional part (.5), yielding24.
Exercise 19: ASCII Arithmetic
Practice Problem: Take two characters as input, add their ASCII values, and print the sum.
+ Hint
Read the characters using scanf("%c", ...) and store them in char variables. When you add two char variables, C implicitly promotes them to ints before performing the addition.
+ Show Solution
#include <stdio.h>
int main() {
char char1, char2;
int sum_ascii;
printf("Enter two characters: ");
// Note: space before %c to consume whitespace
scanf(" %c %c", &char1, &char2);
sum_ascii = char1 + char2;
printf("The ASCII value of '%c' is %d\n", char1, char1);
printf("The ASCII value of '%c' is %d\n", char2, char2);
printf("Sum of ASCII values: %d\n", sum_ascii);
return 0;
}Code language: C++ (cpp)
Explanation:
- In C, when arithmetic operations are performed on
charvariables, they are automatically promoted toints to perform the calculation. - Therefore, adding
char1andchar2effectively adds their corresponding ASCII values. The result is stored in theintvariablesum_asciiand printed as an integer.
Exercise 20: Formatted Output
Practice Problem: Calculate total price and Print below variables in a single formatted sentence with different format specifiers.
Given:
#include <stdio.h>
int main() {
int quantity = 3;
float unit_price = 15.75f;
char code = 'A';
//print here
return 0;
}Code language: Python (python)
Expected Output:
Item Code: A, Quantity: 3, Total Price: $47.25
+ Hint
Construct a single printf string that includes all necessary format specifiers (%d, %.1f, %c). Ensure the variables are passed to printf in the same order as their corresponding format specifiers.
+ Show Solution
#include <stdio.h>
int main() {
int quantity = 3;
float unit_price = 15.75f;
char code = 'A';
printf("Item Code: %c, Quantity: %d, Total Price: $%.2f\n",
code, quantity, quantity * unit_price);
return 0;
}Code language: C++ (cpp)
Explanation:
This exercise focuses on using the full capability of the printf function. A single statement is used to combine different data types (char, int, and the result of a float calculation) into one descriptive output sentence.
The use of specific format specifiers (like %.2f for currency) ensures the output is properly formatted.
Exercise 21: Exponential Notation
This exercise demonstrates the use of exponential (scientific) notation, which is useful for representing numbers that are either extremely large or extremely small.
Problem Statement: Declare a double variable and assign it a very large or small number. Print its value using exponential notation (%e).
+ Hint
Use the double data type for high precision. The %e format specifier will display the number in scientific notation (e.g., 1.234567e+09).
+ Show Solution
#include <stdio.h>
int main() {
double large_num = 1234567890.12345;
double small_num = 0.00000000123;
printf("Large number in standard format: %f\n", large_num);
printf("Large number in exponential format: %e\n", large_num);
printf("Small number in exponential format: %e\n", small_num);
return 0;
}Code language: C++ (cpp)
Explanation:
The %e format specifier tells printf to display the double value in the form of mantissa and exponent (e.g., 1.234568e+09), a concise way to handle vast numerical ranges.

Leave a Reply