This comprehensive guide provides 50+ basic C programming exercises designed specifically for beginners.
These coding problems are structured to help you practice core skills incrementally. Each exercise includes a Practice Problem, Hint, Solution code, and detailed Explanation, ensuring you don’t just copy code, but genuinely understand how and why it works.
Also, See: C Programming Exercises with 9 topic-wise sets and 275+ practice questions.
What You’ll Practice
The exercises cover the following core topics:
- Fundamentals: Basic I/O, Variable Declaration, Arithmetic Operators, Type Casting.
- Conditional Statement and Looping:
if-else,else-if,switch,for,while,do-whileloops. Used for Factorial, Fibonacci, Palindrome, Prime Check, and more. - Data Structures: Arrays, Strings, and Structures (including nested and arrays of structs).
- Simple Functions: Definition/Calling,
voidvs. Return Type, Functions for Arithmetic/Array tasks. - Advanced Basics: Pointers (declaration, dereferencing, pass by reference, pointer arithmetic) and basic File Handling.
Use Online C Compiler to solve exercises.
+ Table Of Contents (53 Exercises)
Table of contents
- Exercise 1: Float Input/Output
- Exercise 2: Calculate Sum
- Exercise 3: Arithmetic Operations
- Exercise 4: Circumference/Area of a Circle
- Exercise 5: Simple Interest
- Exercise 6: Swapping Numbers
- Exercise 7: Swapping Without Third Variable
- Exercise 8: ASCII Value
- Exercise 9: Check Even or Odd
- Exercise 10: Find Largest of Three Numbers
- Exercise 11: Leap Year Check
- Exercise 12: Simple Calculator using switch
- Exercise 13: Print Natural Numbers (for loop)
- Exercise 14: Print Numbers in Reverse (while loop)
- Exercise 15: Sum of Natural Numbers
- Exercise 16: Print odd numbers from 1 to 20
- Exercise 17: Multiplication Table
- Exercise 18: Do-While Menu
- Exercise 19: Factorial of a Number
- Exercise 20: Count Digits
- Exercise 21: Reverse a Number
- Exercise 22: Check Palindrome
- Exercise 23: Skip Even Numbers
- Exercise 24: Fibonacci Series
- Exercise 25: Solid Rectangle Pattern
- Exercise 26: Input and Print Array
- Exercise 27: Sum of Array Elements
- Exercise 28: Find Maximum and Minimum
- Exercise 29: Search Element
- Exercise 30: Function for Even/Odd
- Exercise 31: Function to Find Maximum in Array
- Exercise 32: String Length Calculation
- Exercise 33: Copy String
- Exercise 34: Vowels and Consonants
- Exercise 35: Words in a String
- Exercise 36: String Reversal
- Exercise 37: Character Frequency Count
- Exercise 38: Basic Student Record
- Exercise 39: Array of Structures
- Exercise 40: Nested Structures
- Exercise 41: Pointers to Structures
- Exercise 42: Basic Pointer Declaration and Dereference
- Exercise 43: Modifying Value via Pointer
- Exercise 44: Function with Pointer (Pass by Reference)
- Exercise 45: Simple Pointer Arithmetic
- Exercise 46: Compare Pointers
- Exercise 47: Basic Recursion (Factorial)
- Exercise 48: Copy Array
- Exercise 49: Create and Write to a File
- Exercise 50: Read and Display File Content
- Exercise 51: Append Data to a File
- Exercise 52: Count Characters in a File
- Exercise 53: Count Lines in a File
Exercise 1: Float Input/Output
Practice Problem: Write a C program that takes a floating-point number (a decimal number, like 3.14159) from the user and prints it, formatted to display with only two decimal places.
Expected Output:
Enter a floating-point number (e.g., 3.14159): 75.35678
The number rounded to two decimal places is: 75.36
+ Hint
Use the float or double data type. The format specifier for reading floats is %f, and for printing a float with two decimal places, you use %.2f.
+ Show Solution
#include <stdio.h>
int main() {
float pi_value;
printf("Enter a floating-point number (e.g., 3.14): ");
// Read the float value
scanf("%f", &pi_value);
// Print the value formatted to two decimal places
printf("\nThe number rounded to two decimal places is: %.2f\n", pi_value);
return 0;
}Code language: C++ (cpp)
Explanation:
float pi_value;: Declares a variable to store the decimal value.scanf("%f", &pi_value);: Reads a floating-point number from input.printf("... %.2f\n", pi_value);: This is the key line for formatting. The format specifier%.2ftells theprintf()function to display the correspondingfloatargument (pi_value) with exactly two digits after the decimal point.
Exercise 2: Calculate Sum
Practice Problems: Write a C program that prompts the user to enter two separate integers, calculates their sum, and then prints the result.
Expected Output:
Enter the first integer: 10
Enter the second integer: 20
The sum of 10 and 20 is: 30
+ Hint
Declare three integer variables: two for input and one for the result. You can use a single scanf() call to read both numbers at once.
+ Show Solution
#include <stdio.h>
int main() {
int num1, num2, sum;
printf("Enter the first integer: ");
scanf("%d", &num1);
printf("\nEnter the second integer: ");
scanf("%d", &num2);
// Calculate the sum
sum = num1 + num2;
// Print the result
printf("\nThe sum of %d and %d is: %d\n", num1, num2, sum);
return 0;
}Code language: C++ (cpp)
Explanation:
int num1, num2, sum;: Three integer variables are declared.- The program uses two separate
scanf()calls to read the values intonum1andnum2. sum = num1 + num2;: The addition operator (+) calculates the sum, and the result is stored in thesumvariable.- The final
printf()uses three%dformat specifiers, substituting them in order with the values ofnum1,num2, andsum.
Exercise 3: Arithmetic Operations
Practice Problem: Write a C program that calculates and prints the sum, difference, product, and quotient (division) of two integers.
Given:
int a, b;
a = 10;
b = 20;Code language: C++ (cpp)
Expected Output:
Sum: 20 + 10 = 30
Difference: 20 - 10 = 10
Product: 20 * 10 = 200
Quotient: 20 / 10 = 2.00
+ Hint
Use four separate arithmetic operators: +, -, *, and /. Use floating-point casting for the division to ensure an accurate decimal result.
+ Show Solution
#include <stdio.h>
int main() {
int a, b;
a = 20;
b = 10;
// Perform operations
printf("\nSum: %d + %d = %d\n", a, b, a + b);
printf("\nDifference: %d - %d = %d\n", a, b, a - b);
printf("\nProduct: %d * %d = %d\n", a, b, a * b);
// Division with float casting for accuracy
if (b != 0) {
printf("\nQuotient: %d / %d = %.2f\n", a, b, (float)a / b);
} else {
printf("\nQuotient: Cannot divide by zero.\n");
}
return 0;
}Code language: C++ (cpp)
Explanation:
- The first three operations (
+,-,*) are straightforward integer arithmetic. - The Division: Integer division (
a / b) in C truncates the decimal part (e.g., 5/2 would be 2). To get a precise result, one of the operands is temporarily converted to a float using type casting:(float)a. This forces the entire division operation to be performed in floating-point arithmetic, and the result is printed using%.2f. - An
ifstatement is used to prevent the program from crashing or giving an error if the user attempts to divide by zero.
Exercise 4: Circumference/Area of a Circle
Practice Problem: Write a C program to calculate both the area and circumference of a circle, given its radius. Use a pre-defined constant for π with value 3.14159.
Given:
float radius;
radius = 5;Code language: C++ (cpp)
Expected Output:
Area of the circle: 78.540
Circumference of the circle: 31.416
+ Hint
- Use the formula Area = πr2 and Circumference = 2πr.
- Define π using a
#definepreprocessor directive or aconst floatvariable.
+ Show Solution
#include <stdio.h>
#define PI 3.14159
int main() {
float radius, area, circumference;
radius = 5;
// Calculate Area: PI * r * r
area = PI * radius * radius;
// Calculate Circumference: 2 * PI * r
circumference = 2 * PI * radius;
printf("\nArea of the circle: %.3f\n", area);
printf("\nCircumference of the circle: %.3f\n", circumference);
return 0;
}Code language: C++ (cpp)
Explanation:
#define PI 3.14159: This defines a symbolic constant. The preprocessor replaces every instance ofPIin the code with3.14159before compilation.- The program reads the
radiusas a float. - The formulas for area and circumference are implemented directly using the
*operator and thePIconstant. - The output uses
%.3fto display the results with three decimal places.
Exercise 5: Simple Interest
Practice Problem: Calculate simple interest for a loan, given the Principal amount (P), Rate of interest (R), and Time in years (T) as input.
Given:
float principal, rate, time;
principal = 1000;
rate = 8;
time = 3;Code language: C++ (cpp)
Expected Output:
Simple Interest is: 240.00
+ Hint
- The formula for Simple Interest is: I=(P×R×T)/100.
- Use
floatfor all inputs and the result to handle decimal amounts and rates.
+ Show Solution
#include <stdio.h>
int main() {
float principal, rate, time, simple_interest;
principal = 1000;
rate = 8;
time = 3;
// Calculate Simple Interest
simple_interest = (principal * rate * time) / 100;
printf("\nSimple Interest is: %.2f\n", simple_interest);
return 0;
}Code language: C++ (cpp)
Explanation:
- All variables are declared as
floatto accommodate monetary values and decimal interest rates. - The program reads the three input values (P,R,T).
simple_interest = (principal * rate * time) / 100;: This line directly implements the simple interest formula. Parentheses are used around the numerator to ensure multiplication happens before division, although standard operator precedence (multiplication and division have equal precedence and are evaluated left-to-right) would handle it correctly here too.- The final result is printed with two decimal places (
%.2f), which is conventional for currency.
Exercise 6: Swapping Numbers
Practice Problem: Write a C program to read two integer values, A and B, and then swap their contents so that A holds the original value of B, and B holds the original value of A. Use a third, temporary variable.
Given:
int A, B;
A = 10;
B = 20;Code language: C++ (cpp)
Expected Output:
--- Before Swap ---
A = 10, B = 20
--- After Swap ---
A = 20, B = 10
+ Hint
This classic three-step swap requires:
- storing one value in the temporary variable
- overwriting that variable with the other value
- assigning the temporary value back to the second variable.
+ Show Solution
#include <stdio.h>
int main() {
int A, B, temp;
A = 10;
B = 20;
printf("\n--- Before Swap ---\n");
printf("A = %d, B = %d\n", A, B);
// The three-step swap logic
temp = A; // Step 1: Store original A
A = B; // Step 2: Overwrite A with B's value
B = temp; // Step 3: Overwrite B with the original A (stored in temp)
printf("\n--- After Swap ---\n");
printf("A = %d, B = %d\n", A, B);
return 0;
}Code language: C++ (cpp)
Explanation:
int A, B, temp;: Three integer variables are declared.tempacts as a necessary intermediary storage location.- Step 1:
temp = A;: The original value of A is saved intemp. If we didn’t do this, the original value of A would be lost in the next step. - Step 2:
A = B;: The value of B is copied into A. A now holds B’s original value. - Step 3:
B = temp;: The value stored intemp(the original value of A) is copied into B. B now holds A’s original value. The swap is complete
Exercise 7: Swapping Without Third Variable
Practice Problem: Write a C program swap two integer values, A and B, without using a third temporary variable.
Given:
int A, B;
A = 10;
B = 20;Code language: C++ (cpp)
Expected Output:
--- Before Swap ---
A = 10, B = 20
--- After Swap ---
A = 20, B = 10
+ Hint
- Use arithmetic operators (
+,-) to perform the swap. - The key is to store the sum of the two numbers in one variable, then use subtraction to extract the original values.
+ Show Solution
#include <stdio.h>
int main() {
int A, B;
A = 10;
B = 20;
printf("\n--- Before Swap ---\n");
printf("A = %d, B = %d\n", A, B);
// The arithmetic swap logic
A = A + B; // A now holds the sum of original A and B
B = A - B; // B now holds (A + B) - B, which is original A
A = A - B; // A now holds (A + B) - (original A), which is original B
printf("\n--- After Swap ---\n");
printf("A = %d, B = %d\n", A, B);
return 0;
}Code language: C++ (cpp)
Explanation:
This method relies purely on arithmetic:
- A=A−B: We subtract the new A (the sum) by the new B (the original A). The result is the original value of B. (Example: A=15−5=10. Now A=10,B=5). The swap is complete.
- A=A+B: We store the sum in A. (Example: if A=5,B=10, now A=15,B=10)
- B=A−B: We subtract the new A (the sum) by B. The result is the original value of A. (Example: B=15−10=5. Now A=15,B=5)
Exercise 8: ASCII Value
Practice Problem: Write a C program that prompts the user to enter a single character and prints its corresponding ASCII (American Standard Code for Information Interchange) value.
Expected Output:
Enter a character: A
The character entered is: A
The ASCII value of 'A' is: 65
+ Hint
When printing a char variable, using the %d format specifier instead of %c will instruct printf() to output the numerical (ASCII) value stored in that variable.
+ Show Solution
#include <stdio.h>
int main() {
char ch;
printf("\nEnter a character: ");
scanf(" %c", &ch); // Note the space to handle whitespace
// Print the character itself
printf("\nThe character entered is: %c\n", ch);
// Print the ASCII value by using %d
printf("\nThe ASCII value of '%c' is: %d\n", ch, ch);
return 0;
}Code language: C++ (cpp)
Explanation:
In C, the char data type is actually an integer type that typically stores the 8-bit numerical ASCII code of a character.
- When we read the character with
scanf(" %c", &ch), the variablechstores the integer code (e.g., 65 for ‘A’, 97 for ‘a’). - When we use
printf("...%c...", ch), the program interprets the number inchas a character and prints ‘A’. - When we use
printf("...%d...", ch), the program interprets the number inchas an integer and prints 65.
Exercise 9: Check Even or Odd
Practice Problem: Write a C program to determines whether given integer is even or odd.
Given:
int num;
num = 12;Code language: C++ (cpp)
Expected Output:
12 is an EVEN number.
+ Hint
- An even number is perfectly divisible by 2.
- Use the modulo operator (
%) which gives the remainder of a division. Ifnumber % 2is 0, the number is even; otherwise, it’s odd.
+ Show Solution
#include <stdio.h>
int main() {
int num;
num = 12;
// Use the modulo operator for the check
if (num % 2 == 0) {
printf("%d is an EVEN number.\n", num);
} else {
printf("%d is an ODD number.\n", num);
}
return 0;
}Code language: C++ (cpp)
Explanation:
num % 2calculates the remainder whennumis divided by 2.- The
ifstatement checks the conditionnum % 2 == 0. - If the remainder is 0 (the condition is true), the number is even, and the code inside the
ifblock executes. - If the remainder is not 0 (it will be 1 for any odd integer), the condition is false, and the code inside the
elseblock executes, concluding the number is odd.
Exercise 10: Find Largest of Three Numbers
Practice Problem: Write a C program to find and print the largest of given three numbers (A, B, and C).
Given:
int A, B, C;
A = 10;
B = 30;
C = 20;Code language: C++ (cpp)
Expected Output:
B (30) is the largest number.
+ Hint
- Use
>=(greater than equal to operator) for value comparison. - Use nested
ifstatements or use logical operators (like&&for AND) to combine multiple comparison conditions in a singleif-else ifstructure.
+ Show Solution
#include <stdio.h>
int main() {
int A, B, C;
A = 10;
B = 30;
C = 20;
if (A >= B && A >= C) {
printf("A (%d) is the largest number.\n", A);
}
else if (B >= A && B >= C) {
printf("B (%d) is the largest number.\n", B);
}
else {
// If A and B aren't the largest, C must be (or all are equal)
printf("C (%d) is the largest number.\n", C);
}
return 0;
}Code language: C++ (cpp)
Explanation:
- The first condition
A >= B && A >= Cchecks if A is greater than or equal to both B AND C. The logical AND operator (&&) requires both sub-conditions to be true. If true, A is the maximum. - If A wasn’t the maximum, the program proceeds to the
else ifblock. The conditionB >= A && B >= Cchecks if B is greater than or equal to both A AND C. - If neither of the first two conditions is met, it means C must be the largest (or equal to the others, in which case any would be a correct answer), so the final
elseblock executes.
Exercise 11: Leap Year Check
Practice Problem: Write a C program to determine if a given year is a leap year.
Leap year: A year is a leap year if it is divisible by 400, OR if it is divisible by 4 but NOT by 100. Use the modulo operator (%) and the logical OR (||) and logical AND (&&) operators.
Given:
int year;
year = 2024;Code language: C++ (cpp)
Expected Output:
2024 is a LEAP YEAR.
+ Hint
Use the modulo operator (%) and the logical OR (||) and logical AND (&&) operators.
+ Show Solution
#include <stdio.h>
int main() {
int year;
year = 2024;
// Leap year conditions:
// (Divisible by 400) OR (Divisible by 4 AND Not divisible by 100)
if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)) {
printf("%d is a LEAP YEAR.\n", year);
} else {
printf("%d is NOT a leap year.\n", year);
}
return 0;
}Code language: C++ (cpp)
Explanation:
The expression contains the full logic for a leap year:
year % 400 == 0: True for years like 2000 and 2400.year % 4 == 0 && year % 100 != 0: True for years like 2004,2008,2012, but false for century years like 1900,2100.
The || (OR) operator connects these two main conditions. If either condition is true, the overall condition is true, and the year is declared a leap year.
Exercise 12: Simple Calculator using switch
Practice Problem: Implement a basic calculator that takes two numbers and an operator (+,−,∗,/) as input, and performs the calculation using a switch statement.
Expected Output:
Enter operator (+, -, *, /): *
Enter two operands: 10 20
10.00 * 20.00 = 200.00
+ Hint
- Use
floatfor the numbers andcharfor the operator. - The
switchstatement should evaluate the operator character and perform the corresponding arithmetic inside eachcase.
+ Show Solution
#include <stdio.h>
int main() {
char op;
float num1, num2;
printf("Enter operator (+, -, *, /): ");
scanf(" %c", &op); // Read operator first
printf("\nEnter two operands: ");
scanf("%f %f", &num1, &num2);
switch (op) {
case '+':
printf("%.2f + %.2f = %.2f\n", num1, num2, num1 + num2);
break;
case '-':
printf("%.2f - %.2f = %.2f\n", num1, num2, num1 - num2);
break;
case '*':
printf("%.2f * %.2f = %.2f\n", num1, num2, num1 * num2);
break;
case '/':
if (num2 != 0) {
printf("%.2f / %.2f = %.2f\n", num1, num2, num1 / num2);
} else {
printf("Error: Division by zero is not allowed.\n");
}
break;
default:
printf("Error: Invalid operator entered.\n");
}
return 0;
}Code language: C++ (cpp)
Explanation:
- The
switchstatement evaluates theopvariable. - Execution jumps to the
caselabel that matches the value ofop(e.g.,case '+'). - Inside the
case '/', an additionalifcheck is included to prevent division by zero. - The
breakstatement is essential in each case; it immediately exits theswitchblock. Without it, the code would “fall through” and execute the subsequentcaseblocks. - The
defaultcase handles any operator that doesn’t match the defined cases.
Exercise 13: Print Natural Numbers (for loop)
Practice Problem: Write a C program to print the first 10 natural numbers (1 to 10) in ascending order using a for loop.
Expected Output:
The first 10 natural numbers are:
1 2 3 4 5 6 7 8 9 10
+ Hint
The for loop structure requires three parts:
- initialization (
int i = 1) - condition (
i <= 10) - update (
i++).
+ Show Solution
#include <stdio.h>
int main() {
int i;
printf("The first 10 natural numbers are:\n");
// Loop from 1 up to 10, inclusive
for (i = 1; i <= 10; i++) {
printf("%d ", i);
}
printf("\n");
return 0;
}Code language: C++ (cpp)
Explanation:
- Initialization (
i = 1): The loop counteristarts at 1. - Condition (
i <= 10): The loop continues as long asiis less than or equal to 10. - Update (
i++): After each iteration, the value ofiis incremented by 1. - The
printfstatement inside the loop executes 10 times, printing the current value ofiin each iteration.
Exercise 14: Print Numbers in Reverse (while loop)
Practice Problem: Write a C program to print numbers from 10 down to 1 in descending order using a while loop.
Expected Output:
Numbers in reverse order:
10 9 8 7 6 5 4 3 2 1
+ Hint
- Initialize a counter variable to 10 before the loop.
- The loop condition should check if the counter is greater than or equal to 1.
- Remember to decrement the counter inside the loop body.
+ Show Solution
#include <stdio.h>
int main() {
int i = 10; // Initialize counter to 10
printf("Numbers in reverse order:\n");
// Loop continues as long as i is 1 or greater
while (i >= 1) {
printf("%d ", i);
i--; // Decrement the counter
}
printf("\n");
return 0;
}Code language: C++ (cpp)
Explanation:
- Initialization:
iis set to 10. - Condition (
i >= 1): The loop body executes repeatedly as long as i is 1 or greater. - Body:
printfprints the current value of i. - Update (
i--): The decrement operator reduces i by 1 in each pass (10,9,8,…). This step is crucial; without it, the condition would always be true, creating an infinite loop.
Exercise 15: Sum of Natural Numbers
Practice Problem: Write a C program to calculate and print the sum of the first N natural numbers.
Given:
int N;
N = 10;Code language: C++ (cpp)
Expected Output:
The sum of the first 10 natural numbers is: 55
+ Hint
- Use a
forloop that iterates from 1 up to N. - Initialize a
sumvariable to 0 and add the loop counter to it in each iteration.
+ Show Solution
#include <stdio.h>
int main() {
int N, i, sum = 0;
N = 10;
// Loop from 1 to N
for (i = 1; i <= N; i++) {
sum = sum + i; // Accumulate the sum
}
printf("The sum of the first %d natural numbers is: %d\n", N, sum);
return 0;
}Code language: C++ (cpp)
Explanation:
sum = 0: The accumulator variablesummust be initialized to 0 to ensure the starting point is correct.for (i = 1; i <= N; i++): This loop iterates N times.sum = sum + i;: This is the accumulation step. In the first iteration, sum=0+1. In the second, sum=1+2=3, and so on, until all numbers up to N are added.
Exercise 16: Print odd numbers from 1 to 20
Practice Problem: Write a C program to print odd numbers between 1 and 20 using a do...while loop.
Expected Output:
1 3 5 7 9 11 13 15 17 19
+ Hint
A do...while loop guarantees at least one execution. Start from 1 and increase the number by 2 on each iteration to directly reach the next odd number.
+ Show Solution
#include <stdio.h>
int main() {
int i = 1;
do {
printf("%d ", i);
i += 2;
} while (i <= 100);
return 0;
}Code language: C++ (cpp)
Explanation:
Unlike for and while, this do while loop runs the body first before checking the condition. Here, i begins at 1, and after each print, it is incremented by 2 to move to the next odd number. The loop continues until i becomes greater than 100.
Exercise 17: Multiplication Table
Practice Problem: Write a C program to print the multiplication table of a given integer N from 1 × N up to 10 × N.
Given:
int N;
N = 2;Code language: C++ (cpp)
Expected Output:
Multiplication Table for 2:
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
....
2 x 10 = 20
+ Hint
- Use a
forloop that runs 10 times, with a counter variable i going from 1 to 10. - Inside the loop, calculate the product i×N.
+ Show Solution
#include <stdio.h>
int main() {
int N, i;
N = 2;
printf("\nMultiplication Table for %d:\n", N);
// Loop from 1 to 10
for (i = 1; i <= 10; i++) {
// Print: N x i = (N * i)
printf("%d x %d = %d\n", N, i, N * i);
}
return 0;
}Code language: C++ (cpp)
Explanation:
- The
printfstatement formats the output to show the full equation (e.g., 5×3=15) for clarity. - The program takes the input number N.
- The
forloop uses i to represent the multiplier (1,2,3,…,10). - Inside the loop, the expression
N * iperforms the calculation.
Exercise 18: Do-While Menu
Create a simple menu-driven program that displays options (“1. Greet”, “2. Say Goodbye”, “3. Exit”). Use a do-while loop and a switch statement to repeatedly show the menu and process the user’s choice until they select the ‘Exit’ option.
Expected Output:
The area of a circle with radius 5.00 is 78.54
+ Hint
The do-while loop is perfect because you want the code block (displaying the menu) to execute at least once before checking the exit condition. The exit condition should be based on the user’s choice being equal to 3.
+ Show Solution
Explanation:
This combines control flow structures for interactive programs.
do { ... } while (condition): The code inside thedoblock executes first. The condition (choice != 3) is checked after the first run.- The
switchstatement inside the loop handles the different menu options. - The loop continues as long as
choiceis not equal to 3. Once the user enters 3, theswitchhandles the exit message, and thewhilecondition becomes false, terminating the entire loop and ending the program.
Exercise 19: Factorial of a Number
Practice Problem: Write a C program to calculate the factorial of a given non-negative integer N. (The factorial of N is the product of all positive integers less than or equal to N, denoted N!).
Formula: For a non-negative integer n, the factorial is defined as:
n! = n × (n - 1) × (n - 2) × ... × 1
Example (5!):
0! = 1
1! = 1
3! = 3 × 2 × 1 = 6
5! = 5 × 4 × 3 × 2 × 1 = 120
Given:
int N;
N = 5;Code language: C++ (cpp)
Expected Output:
The factorial of 5 is: 120
+ Hint
- Initialize a variable, typically
factorial, to 1. - Use a loop that iterates from 1 up to N. In each iteration, multiply the current
factorialvalue by the loop counter. - Use a
long long intordoubleif the factorial could get very large.
+ Show Solution
#include <stdio.h>
int main() {
int N, i;
N = 5;
// Factorials grow very fast, so we use long long
long long factorial = 1;
if (N < 0) {
printf("Error: Factorial is not defined for negative numbers.\n");
} else {
for (i = 1; i <= N; i++) {
factorial *= i; // Equivalent to: factorial = factorial * i;
}
printf("The factorial of %d is: %lld\n", N, factorial);
}
return 0;
}Code language: C++ (cpp)
Explanation:
- Initialization:
factorialis set to 1, because 0!=1 and multiplying by 1 won’t change the product. - Loop: The loop runs from i=1 to N.
- Calculation: The line
factorial *= i;is the multiplication step. For N=5, it calculates:5*4*3*2*1 = 120
Exercise 20: Count Digits
Practice Problem: Write a C program to counts the total number of digits in a given number.
Given:
long long num = 3456;Code language: C++ (cpp)
Expected Output:
The number 3456 has 4 digits.
+ Hint
- Use a
whileloop. Repeatedly divide the number by 10 (integer division) until the number becomes 0. - Maintain a counter that is incremented in each loop iteration.
+ Show Solution
#include <stdio.h>
int main() {
long long num = 3456;
int count = 0;
long long original_num = num; // Save the original number for printing
// Handle the case of 0 separately
if (num == 0) {
count = 1;
} else {
// Loop until the number becomes 0
while (num > 0) {
num /= 10; // Integer division removes the last digit
count++; // Increment digit count
}
}
printf("The number %lld has %d digits.\n", original_num, count);
return 0;
}Code language: C++ (cpp)
Explanation:
- Process: The core of the logic is the loop:
num /= 10;(e.g., 1234→123→12→1→0). - Iteration: For every iteration, one digit is “removed” by the integer division, and the
countis incremented. - Termination: The loop stops when
numis no longer greater than 0. The total number of iterations equals the number of digits. The special case for num=0 is handled separately, as the loop conditionnum > 0would fail immediately.
Exercise 21: Reverse a Number
Practice Problem: Write a C program to reverse a given integer (e.g., 1234 becomes 4321).
Given:
int num = 123Code language: C++ (cpp)
Expected Output:
The reverse of 123 is: 321
+ Hint
- Use a
whileloop to extract the last digit using the modulo operator (% 10). - Build the reversed number by multiplying the current reversed number by 10 and adding the extracted digit.
+ Show Solution
#include <stdio.h>
int main() {
int num = 123, reversed_num = 0, remainder;
int original_num = num;
while (num != 0) {
remainder = num % 10; // 1. Extract the last digit
reversed_num = reversed_num * 10 + remainder; // 2. Build the reversed number
num /= 10; // 3. Remove the last digit
}
printf("The reverse of %d is: %d\n", original_num, reversed_num);
return 0;
}Code language: C++ (cpp)
Explanation: If num=123:
- Loop ends. This pattern successfully extracts digits from the right and prepends them to the new reversed number.
- Iter 1: remainder = 3.
reversed_num = 0*10 + 3 = 3. num = 12. - Iter 2: remainder = 2.
reversed_num = 3*10 + 2 = 32. num = 1. - Iter 3: remainder = 1.
reversed_num = 32*10 + 1 = 321. num = 0.
Exercise 22: Check Palindrome
Practice Problem: Write a C program to check if a given integer is a palindrome (reads the same forwards and backward, e.g., 121,3553).
Given:
int num = 121Code language: C++ (cpp)
Expected Output:
121 is a PALINDROME
+ Hint
- This exercise combines concepts from “Reverse a Number” (Exercise 19).
- Calculate the reverse of the input number.
- Then, use an
ifstatement to check if the reversed number is equal to the original number.
+ Show Solution
#include <stdio.h>
int main() {
int num = 121, original_num, reversed_num = 0, remainder;
original_num = num; // Crucial: save the original value
// Logic to reverse the number
while (num != 0) {
remainder = num % 10;
reversed_num = reversed_num * 10 + remainder;
num /= 10;
}
// Check if the original and reversed numbers are the same
if (original_num == reversed_num) {
printf("%d is a PALINDROME.\n", original_num);
} else {
printf("%d is NOT a palindrome.\n", original_num);
}
return 0;
}Code language: C++ (cpp)
Explanation:
- Saving Original: Before entering the
whileloop, the value ofnumis copied tooriginal_num. This is essential because the loop modifies and eventually reducesnumto 0. - Reversal: The
whileloop calculates thereversed_numexactly as in Exercise 19. - Comparison: The final
ifstatement compares the intactoriginal_numagainst the computedreversed_numto determine if the number is a palindrome.
Exercise 23: Skip Even Numbers
Practice Problem: Write a C program to print all odd numbers between 1 and N using a single for loop and use the continue keyword to skip the even numbers.
Given:
int N = 20;Code language: C++ (cpp)
Expected Output:
Odd numbers from 1 to 20:
1 3 5 7 9 11 13 15 17 19
+ Hint
Loop through every number from 1 to N. Inside the loop, use an if statement to check if the current number is even (i % 2 == 0). If it is, execute the continue statement.
+ Show Solution
#include <stdio.h>
int main() {
int N = 20, i;
printf("Odd numbers from 1 to %d:\n", N);
for (i = 1; i <= N; i++) {
// Control flow check for even numbers
if (i % 2 == 0) {
continue; // Skips the rest of the loop body for even numbers
}
// This line only executes if 'i' is ODD
printf("%d ", i);
}
printf("\n");
return 0;
}Code language: C++ (cpp)
Explanation:
The continue keyword alters control flow within a loop by skipping the current iteration and immediately moving to the next one (i.e., the loop update expression).
- The loop iterates through all numbers.
- When an even number is encountered (
i % 2 == 0),continueis executed. This causes the program to jump directly toi++, skipping theprintfstatement for that even number. - The
printfstatement is only reached wheniis an odd number.
Exercise 24: Fibonacci Series
Practice Problem: Write a C program to print the first N terms of the Fibonacci series. (The series starts with 0, 1 and each subsequent number is the sum of the two preceding ones: 0,1,1,2,3,5,8,…).
Given:
int N = 8;Code language: C++ (cpp)
Expected Output:
Fibonacci Series up to 8 terms:
0, 1, 1, 2, 3, 5, 8, 13,
+ Hint
- Initialize two variables,
t1 = 0andt2 = 1. - Use a
forloop that runs N times. - Inside the loop, calculate the
nextTermast1 + t2, - Then update
t1 = t2andt2 = nextTerm.
+ Show Solution
#include <stdio.h>
int main() {
int N=8, i;
int t1 = 0, t2 = 1;
int nextTerm = t1 + t2;
printf("Fibonacci Series up to %d terms:\n%d, %d, ", N, t1, t2);
// Start loop from i=3 since the first two terms are printed already
for (i = 3; i <= N; ++i) {
printf("%d, ", nextTerm);
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}
printf("\n");
return 0;
}Code language: C++ (cpp)
Explanation:
Base Case: The first two terms (0 and 1) are initialized and printed outside the loop.
Loop Logic: The for loop iterates for the remaining terms. In each iteration:
- A new
nextTermis calculated. This three-step update shifts the window of the last two terms forward. - The
nextTermis printed. - The “old” second term (
t2) becomes the new first term (t1). - The
nextTermbecomes the new second term (t2).
Exercise 25: Solid Rectangle Pattern
Practice Problem: Write a C program that uses nested for-loops to print a solid rectangle pattern of asterisks (*) with 3 rows and 3 columns.
Given:
int rows=3, cols=3;Code language: C++ (cpp)
Expected Output:
***
***
***
+ Hint
- The outer loop controls the rows (running R times). The inner loop controls the columns (running C times).
- The inner loop prints the
*and then the outer loop finishes its iteration by printing a newline character (\n).
+ Show Solution
#include <stdio.h>
int main() {
int rows=3, cols=3, i, j;
// Outer loop for rows
for (i = 1; i <= rows; i++) {
// Inner loop for columns (prints stars in a single row)
for (j = 1; j <= cols; j++) {
printf("*");
}
printf("\n"); // Move to the next line after a row is complete
}
return 0;
}Code language: C++ (cpp)
Explanation:
Nested loops are essential for 2D patterns.
- Outer loop (
i): Iterates R times, representing each row. - Inner loop (
j): Iterates C times. In each iteration, it prints one*without a newline, building a single row horizontally. - Newline:
printf("\n");is placed outside the inner loop but inside the outer loop. This ensures that after a complete row of C stars is printed, the cursor moves to the beginning of the next line.
Exercise 26: Input and Print Array
Practice Problem: Write a C program that prompts the user to enter 5 integer values, stores them in an array, and then prints all the stored elements.
Expected Output:
Enter 5 integers:
Enter element 1: 10
Enter element 2: 20
Enter element 3: 30
Enter element 4: 40
Enter element 5: 50
Elements stored in the array: 10 20 30 40 50
+ Hint
- Use one
forloop withscanf()to read the elements. - use a separate
forloop withprintf()to display them. - Remember to use the address-of operator (
&) withscanf().
+ Show Solution
#include <stdio.h>
int main() {
const int SIZE = 5;
int arr[SIZE];
int i;
// 1. Input Loop
printf("Enter 5 integers:\n");
for (i = 0; i < SIZE; i++) {
printf("Enter element %d: ", i + 1);
scanf("%d", &arr[i]); // Read into the address of the array element
}
// 2. Output Loop
printf("\nElements stored in the array: ");
for (i = 0; i < SIZE; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}Code language: C++ (cpp)
Explanation:
- Input: In the first loop,
scanf("%d", &arr[i]);reads the integer and stores it at the memory address of the array element at index i. - Output: The second loop retrieves the stored value at
arr[i]and prints it. Separating input and output loops is standard practice for clear array handling.
Exercise 27: Sum of Array Elements
Practice Problem: Write a C program to calculate and print the sum of all elements in a pre-initialized integer array of size 5.
Given:
int arr[5] = {10, 5, 20, 15, 30};Code language: C++ (cpp)
Expected Output:
The elements are: 10, 5, 20, 15, 30
The sum of all array elements is: 80
+ Hint
- Initialize a variable
sumto 0. - Loop through the array and use the accumulation technique (
sum = sum + array[i]) from Exercise 15.
+ Show Solution
#include <stdio.h>
int main() {
int arr[5] = {10, 5, 20, 15, 30};
int i;
int sum = 0; // Accumulator variable
for (i = 0; i < 5; i++) {
sum = sum + arr[i]; // Add current element to the sum
}
printf("The elements are: 10, 5, 20, 15, 30\n");
printf("The sum of all array elements is: %d\n", sum);
return 0;
}Code language: C++ (cpp)
Explanation:
- Initialization:
sumstarts at 0. for (i = 0; i < 5; i++): Rum loop 5 times to loop through the array- Accumulation: Inside each iteration use the accumulation technique (
sum = sum + array[i]). It adds current element to the sum.
Exercise 28: Find Maximum and Minimum
Practice Problem: Write a C program to find and print both the largest (maximum) and smallest (minimum) elements in a given integer array.
Given:
int arr[6] = {55, 12, 89, 7, 42, 60};Code language: C++ (cpp)
Expected Output:
Array elements: {55, 12, 89, 7, 42, 60}
Maximum element: 89
Minimum element: 7
+ Hint
- Initialize both
maxandminvariables with the first element of the array (arr[0]). - Loop from the second element (
arr[1]) onwards, usingifstatements to updatemaxif a larger element is found, andminif a smaller element is found.
+ Show Solution
#include <stdio.h>
int main() {
int arr[6] = {55, 12, 89, 7, 42, 60};
int i;
// Initialize max and min with the first element
int max = arr[0];
int min = arr[0];
// Loop starts from the second element (index 1)
for (i = 1; i < 6; i++) {
if (arr[i] > max) {
max = arr[i]; // New maximum found
}
if (arr[i] < min) {
min = arr[i]; // New minimum found
}
}
printf("Array elements: {55, 12, 89, 7, 42, 60}\n");
printf("Maximum element: %d\n", max);
printf("Minimum element: %d\n", min);
return 0;
}Code language: C++ (cpp)
Explanation:
- Initialization: By setting
maxandmintoarr[0], we ensure they have valid starting points from the array. - Comparison: The loop starts at index 1 because the element at index 0 has already been accounted for. Two separate
ifstatements check for the maximum and minimum in every iteration. This efficient technique avoids unnecessary nested logic.
Exercise 29: Search Element
Practice Problem: Write a C program that takes an integer array and a search value (key) from the user. Check if the key is present in the array. If found, print its index; otherwise, print a “Not found” message.
Given:
int arr[5] = {10, 25, 30, 45, 50};Code language: C++ (cpp)
Expected Output:
Enter the element to search: 30
Element 30 found at index 2.
+ Hint
- Use a
forloop to traverse the array. Inside the loop, use anifcondition to check ifarray[i]equals thekey. - Use a flag variable or the
breakstatement to signal success.
+ Show Solution
#include <stdio.h>
int main() {
int arr[5] = {10, 25, 30, 45, 50};
int key, i;
int found_index = -1; // -1 indicates not found
printf("Enter the element to search: ");
scanf("%d", &key);
for (i = 0; i < 5; i++) {
if (arr[i] == key) {
found_index = i; // Store the index where it was found
break; // Element found, exit loop immediately
}
}
if (found_index != -1) {
printf("Element %d found at index %d.\n", key, found_index);
} else {
printf("Element %d not found in the array.\n", key);
}
return 0;
}Code language: C++ (cpp)
Explanation:
- Flag/Index: The variable
found_indexis used to track the search result. Initializing it to −1 is a common way to denote “not found” since array indices are always non-negative. - Search: The
forloop performs a linear search. Theif (arr[i] == key)condition checks for a match. - Efficiency: Once a match is found,
breakterminates the loop, preventing unnecessary comparisons for the remaining elements. - Result: The final
if-elsestatement checks the value offound_indexto report the result.
Exercise 30: Function for Even/Odd
Practice Problem: Write a C function named check_even_odd that takes an integer as a parameter and prints whether it is “Even” or “Odd” directly within the function. Call this function from main().
Given:
int A = 42;
int B = 17;Code language: C++ (cpp)
Expected Output:
Checking numbers...
42 is EVEN.
17 is ODD.
+ Hint
- The function’s return type should be
voidsince it performs the printing internally and doesn’t need to return a value. - Use the modulo operator (
%) and anif-elseblock inside the function body.
+ Show Solution
#include <stdio.h>
// Function signature is void, meaning it returns nothing
void check_even_odd(int num) {
if (num % 2 == 0) {
printf("%d is EVEN.\n", num);
} else {
printf("%d is ODD.\n", num);
}
}
int main() {
int A = 42;
int B = 17;
printf("Checking numbers...\n");
// Call the function for A
check_even_odd(A);
// Call the function for B
check_even_odd(B);
return 0;
}Code language: C++ (cpp)
Explanation:
voidReturn Type:void check_even_odd(int num)signifies that the function accepts an integer but does not return any data. Its purpose is solely to execute the code within its body (the printing).- Functionality: The logic inside the function is the same as in Exercise 13 (Even/Odd check).
- Call: The function is called with
check_even_odd(A);. This simply transfers control and the value of A to the function. When the function finishes, control returns tomain().
Exercise 31: Function to Find Maximum in Array
Practice Problem: Write a C function named find_max that takes an integer array and its size as parameters, and returns the largest element in the array.
Given:
int data[] = {8, 15, 2, 70, 9, 33};Code language: C++ (cpp)
Expected Output:
The array elements are: {8, 15, 2, 70, 9, 33}
The largest element found by the function is: 70
+ Hint
- The function signature should be
int find_max(int arr[], int size). - Implement the logic from Exercise 35 inside this function, and use
returnto send the maximum value back to the caller.
+ Show Solution
#include <stdio.h>
// Function definition
int find_max(int arr[], int size) {
int max = arr[0]; // Initialize max with the first element
int i;
for (i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max; // Return the final maximum value
}
int main() {
int data[] = {8, 15, 2, 70, 9, 33};
int size = 6;
int result;
// Call the function
result = find_max(data, size);
printf("The array elements are: {8, 15, 2, 70, 9, 33}\n");
printf("The largest element found by the function is: %d\n", result);
return 0;
}Code language: C++ (cpp)
Explanation:
- Function Parameters:
int arr[]tells the function it’s receiving an array of integers. Theint sizeis passed separately because C arrays, when passed to a function, decay into pointers and lose their size information. - Logic: The function uses the comparison logic to iteratively update
max. - Return: Once the loop completes,
return max;sends the single maximum value back tomain(), which stores it in theresultvariable.
Exercise 32: String Length Calculation
Practice Problem: Develop a C program that prompts the user to enter a string (a sequence of characters) and then calculates and prints the length of that string without using the built-in strlen() function.
Expected Output:
Enter a string: PYnative
The length of the string is: 8
+ Hint
- A C-style string is a character array terminated by a null character (
\0). - Use a
fororwhileloop to iterate through the characters of the array until the null terminator is encountered.
+ Show Solution
#include <stdio.h>
int main() {
char str[100];
int length = 0;
printf("Enter a string:\n ");
// Read string input (up to 99 characters)
scanf("%s", str);
// Loop through the array until the null terminator is found
while (str[length] != '\0') {
length++;
}
printf("The length of the string is: %d\n", length);
return 0;
}Code language: C++ (cpp)
Explanation:
char str[100];: Declares a character array to store the string.scanf("%s", str);: Reads the string. Note thatscanfwith%sautomatically appends the null terminator (\0) and does not need the address-of operator (&) for the array name.while (str[length] != '\0'): The loop increments thelengthcounter until the null terminator is reached. Since the null terminator itself is not counted as part of the string’s length, the loop correctly exits after counting the last valid character.
Exercise 33: Copy String
Practice Problem: Write a C program to copy the contents of one string (source) to another string (destination) manually without using the built-in strcpy() function.
Given:
char source[] = "Copy Me!";
// Destination must be large enough to hold the source string + '\0'
char destination[20]; Code language: C++ (cpp)
Expected Output:
Source: Copy Me!
Destination: Copy Me!
+ Hint
- Iterate through the
sourcestring character by character, copying each element into the corresponding index of thedestinationstring. - Don’t forget to manually add the null terminator (
\0) to the end of thedestinationstring.
+ Show Solution
#include <stdio.h>
int main() {
char source[] = "Copy Me!";
// Destination must be large enough to hold the source string + '\0'
char destination[20];
int i = 0;
// Loop until the null terminator of the source string is reached
while (source[i] != '\0') {
destination[i] = source[i];
i++;
}
// Essential: Add the null terminator to the destination string
destination[i] = '\0';
printf("Source: %s\n", source);
printf("Destination: %s\n", destination);
return 0;
}Code language: C++ (cpp)
Explanation:
- The code uses a
whileloop to traverse thesourcestring. In each iteration,destination[i] = source[i];copies the character from the source to the destination. - The loop stops when
source[i]is the null terminator. - After the loop, the index
iis pointing to the position right after the last copied character. The linedestination[i] = '\0';manually places the null terminator, ensuring thedestinationarray is treated as a valid C string.
Exercise 34: Vowels and Consonants
Practice Problem: Write a C program to count the total number of vowels (A, E, I, O, U, and their lowercase counterparts) and consonants in a given string.
Given:
char str[] = "Programming In C is fun.";Code language: C++ (cpp)
Expected Output:
String: Programming In C is fun.
Total Vowels: 6
Total Consonants: 13
+ Hint
Use an if/else if structure. First, ensure the character is an alphabet (check the entire range ‘a’-‘z’ and ‘A’-‘Z’). Then, inside this check, use a complex if condition with logical OR (||) to check for all 10 possible vowels. Any alphabet that isn’t a vowel must be a consonant.
+ Show Solution
#include <stdio.h>
#include <ctype.h> // For tolower() to simplify the vowel check
int main() {
char str[] = "Programming In C is fun.";
int vowels = 0;
int consonants = 0;
int i = 0;
while (str[i] != '\0') {
char ch = tolower(str[i]); // Convert to lowercase for simplified check
// Check if the character is an alphabet
if (ch >= 'a' && ch <= 'z') {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
} else {
consonants++;
}
}
i++;
}
printf("String: %s\n", str);
printf("Total Vowels: %d\n", vowels);
printf("Total Consonants: %d\n", consonants);
return 0;
}Code language: C++ (cpp)
Explanation:
- The code iterates through the string. It first uses
tolower()from<ctype.h>to convert the character to lowercase, simplifying the vowel check. The outerifcondition ensures that the character is an alphabet. - The inner
ifcondition explicitly checks if the character matches any of the five lowercase vowels using the logical OR operator (||). If it is an alphabet and not a vowel, theelseblock increments theconsonantscount. Non-alphabetic characters (spaces, periods, digits) are correctly ignored.
Exercise 35: Words in a String
Practice Problem: Write a C program to count the number of words in a given string (sentence). Assume words are separated by one or more spaces, and the string may start or end with spaces.
Given:
char str[] = "This is a test string";Code language: C++ (cpp)
Expected Output:
The string is: "This is a test string"
Total number of words: 5
+ Hint
A word count can be determined by counting transitions: a word starts when a non-space character is encountered immediately after a space character, or when the string starts with a non-space character. Use a flag variable to track whether the program is currently “inside a word.”
+ Show Solution
#include <stdio.h>
#include <ctype.h> // For isspace()
int main() {
// String starts/ends with spaces and has multiple spaces between words
char str[] = "This is a test string";
int word_count = 0;
// 0: outside a word, 1: inside a word
int is_word = 0;
int i = 0;
while (str[i] != '\0') {
if (isspace(str[i])) {
// Character is a space (or other whitespace)
is_word = 0;
} else if (is_word == 0) {
// Character is NOT a space AND we were previously outside a word
is_word = 1; // Now inside a word
word_count++; // Increment count (start of a new word)
}
i++;
}
printf("The string is: \"%s\"\n", str);
printf("Total number of words: %d\n", word_count);
return 0;
}Code language: C++ (cpp)
Explanation:
The code uses a state-machine approach with the is_word flag. The isspace() function (from <ctype.h>) reliably checks for any whitespace character (space, tab, newline).
- If a space is found, the
is_wordflag is reset to 0 (the program is “outside a word”). - If a non-space character is found and
is_wordwas 0 (meaning the previous character was a space or it’s the start of the string), it means a new word has begun. Theis_wordflag is set to 1, andword_countis incremented. This logic correctly handles leading/trailing spaces and multiple spaces between words by only counting the transition from a space/non-word state to a non-space/word state.
Exercise 36: String Reversal
Practice Problem: Write a C program to reverse a given string.
Given:
char str[] = "Elon";Code language: C++ (cpp)
Expected Output:
Enter a string to reverse: Elon
Reversed string: nolE
+ Hint
- First, determine the length of the string (see Exercise 28).
- Then, use a
forloop that starts at the last character’s index (length - 1) and decrements down to index 0.
+ Show Solution
#include <stdio.h>
int main() {
int length = 0;
int i;
char str[] = "Elon";
// 1. Calculate length
while (str[length] != '\0') {
length++;
}
printf("Reversed string: ");
// 2. Print characters from last to first
for (i = length - 1; i >= 0; i--) {
printf("%c", str[i]);
}
printf("\n");
return 0;
}Code language: C++ (cpp)
Explanation:
Length Calculation: The while loop calculates the length, necessary for knowing where the string ends.
Reverse Loop: The for loop is structured to iterate backward:
- Initialization:
i = length - 1(The last valid character index). - Condition:
i >= 0(Continue until the first index). - Update:
i--(Move backward one character).
In each iteration, str[i] prints the character starting from the end, effectively reversing the output.
Exercise 37: Character Frequency Count
Practice Problem: Write a C program to count the frequency of each unique character (case-insensitive) in a given string.
Given:
char str[] = "Jessa";Code language: C++ (cpp)
Expected Output:
Enter a string: Jessa
Character Frequencies:
a: 1
e: 1
j: 1
s: 2
+ Hint
- Use an integer array (e.g.,
frequency[26]) to store the counts for all 26 letters of the alphabet. - Traverse the input string, convert each character to lowercase, and use its numerical position relative to ‘a’ (
ch - 'a') as the index to increment the corresponding count in the frequency array.
+ Show Solution
#include <stdio.h>
#include <ctype.h>
int main() {
char str[] = "Jessa";
int frequency[26] = {0}; // Initialize all 26 counters to zero
int i, index;
for (i = 0; str[i] != '\0'; i++) {
char ch = tolower(str[i]);
if (ch >= 'a' && ch <= 'z') {
// Calculate index (a=0, b=1, c=2, ...)
index = ch - 'a';
frequency[index]++;
}
}
printf("\nCharacter Frequencies:\n");
for (i = 0; i < 26; i++) {
if (frequency[i] > 0) {
// Convert index back to character: 'a' + 0 = 'a'
printf("%c: %d\n", 'a' + i, frequency[i]);
}
}
return 0;
}Code language: C++ (cpp)
Explanation:
- Frequency Array: An array of size 26 is used, where index 0 stores the count for ‘a’, index 1 for ‘b’, and so on.
- Indexing: The expression
index = ch - 'a';utilizes the fact that characters are stored as sequential ASCII values. For example, ifchis ‘c’,'c' - 'a'is 2, which is the correct index for ‘c’. - Counting:
frequency[index]++;increments the counter for the corresponding letter. - Output: The final loop iterates through the 26 counters. Only if a count is greater than 0 is the character (
'a' + i) and its count printed.
Exercise 38: Basic Student Record
Practice Problem: Define a structure named Student with members for their name (string), roll_number (integer), and percentage (float). Write a C program to input the details for one student and then display those details.
Expected Output:
Enter Student Name: Jessa
Enter Roll Number: 25
Enter Percentage: 85
--- Student Details ---
Name: Jessa
Roll Number: 25
Percentage: 85.00%
+ Hint
Use the dot operator (.) to access the members of the structure variable. Use scanf("%s", ...) for the name, but be careful with strings and spaces. fgets is often safer for strings, but for simplicity here, stick to basic scanf.
+ Show Solution
#include <stdio.h>
// 1. Structure Definition
struct Student {
char name[50];
int roll_number;
float percentage;
};
int main() {
// 2. Declare a structure variable
struct Student s1;
// 3. Input details
printf("Enter Student Name: \n");
scanf("%s", s1.name); // Note: scanf stops reading at the first whitespace
printf("Enter Roll Number: \n");
scanf("%d", &s1.roll_number);
printf("Enter Percentage: \n");
scanf("%f", &s1.percentage);
// 4. Display details
printf("\n--- Student Details ---\n");
printf("Name: %s\n", s1.name);
printf("Roll Number: %d\n", s1.roll_number);
printf("Percentage: %.2f%%\n", s1.percentage);
return 0;
}Code language: C++ (cpp)
Explanation:
- The program first defines the
Studentstructure template. Inmain(), a variables1of this structure type is created, reserving memory for all three members contiguously. - The input process uses the dot operator (
s1.name,s1.roll_number, etc.) to directly access and assign values to the individual fields of thes1variable. The output simply retrieves and prints these stored values.
Exercise 39: Array of Structures
Practice Problem: Using the Student structure from Exercise 34, write a program to store the records of three students. Use a loop to read the data for all three and then display their records.
Expected Output:
--- Enter Data for Student 1 ---
Name: Jessa
Roll Number: 25
Marks: 85
--- Enter Data for Student 2 ---
Name: Jon
Roll Number: 26
Marks: 90
--- Enter Data for Student 3 ---
Name: Gari
Roll Number: 27
Marks: 93
--- All Student Records ---
Student 1: Name=Jessa, Roll=25, Marks=85.00
Student 2: Name=Jon, Roll=26, Marks=90.00
Student 3: Name=Gari, Roll=27, Marks=93.00
+ Hint
- Declare an array of structures, such as
struct Student students[3]. - Use a
forloop to iterate from i=0 to 2, usingstudents[i]to access the current student’s record and the dot operator to access its members.
+ Show Solution
#include <stdio.h>
struct Student {
char name[50];
int roll_number;
float marks;
};
int main() {
// Array of 3 Student structures
struct Student students[3];
int i;
// Input loop
for (i = 0; i < 3; i++) {
printf("\n--- Enter Data for Student %d ---\n", i + 1);
printf("Name: ");
scanf("%s", students[i].name);
printf("Roll Number: ");
scanf("%d", &students[i].roll_number);
printf("Marks: ");
scanf("%f", &students[i].marks);
}
// Output loop
printf("\n--- All Student Records ---\n");
for (i = 0; i < 3; i++) {
printf("Student %d: Name=%s, Roll=%d, Marks=%.2f\n",
i + 1, students[i].name, students[i].roll_number, students[i].marks);
}
return 0;
}Code language: C++ (cpp)
Explanation:
- Array Declaration:
struct Student students[3];creates an array where each element (students[0],students[1],students[2]) is a completeStudentstructure. - Looping: The
forloop makes it easy to process multiple records. Inside the loop,students[i]accesses the i-th student’s record, and the dot operator (.name,.roll_number, etc.) accesses the fields within that record.
Exercise 40: Nested Structures
Practice Problem: Define a structure named Date with members day, month, and year. Then, define a structure named Employee with members id, name, and an embedded (or nested) structure of type Date named date_of_joining. Read and display the record for one employee.
Expected Output:
Enter Employee ID: 1
Enter Employee Name: Jessa
Enter Date of Joining (day month year): 10 6 2024
--- Employee Record ---
ID: 1
Name: Jessa
Joining Date: 10/6/2024
+ Hint
- The
Employeestructure will contain a member whose type is another structure (struct Date). - Access members using chained dot operators, e.g.,
e1.date_of_joining.year.
+ Show Solution
#include <stdio.h>
// 1. Inner Structure
struct Date {
int day;
int month;
int year;
};
// 2. Outer Structure, containing an instance of Date
struct Employee {
int id;
char name[50];
struct Date date_of_joining; // Nested Structure
};
int main() {
struct Employee e1;
printf("Enter Employee ID: \n");
scanf("%d", &e1.id);
printf("Enter Employee Name: \n");
scanf("%s", e1.name);
printf("Enter Date of Joining (day month year): \n");
// Chained access for nested members
scanf("%d %d %d", &e1.date_of_joining.day,
&e1.date_of_joining.month,
&e1.date_of_joining.year);
// Displaying the data
printf("\n--- Employee Record ---\n");
printf("ID: %d\n", e1.id);
printf("Name: %s\n", e1.name);
printf("Joining Date: %d/%d/%d\n",
e1.date_of_joining.day,
e1.date_of_joining.month,
e1.date_of_joining.year);
return 0;
}Code language: C++ (cpp)
Explanation:
- Nesting:
struct Date date_of_joining;withinstruct Employeemakesdate_of_joininga member of typeDate. - Chained Access: To reach the
yearmember, you must first access the employee variable (e1), then the nested structure member (.date_of_joining), and finally the desired field (.year), resulting ine1.date_of_joining.year. This demonstrates how to navigate layers of structures.
Exercise 41: Pointers to Structures
Practice Problem: Define a Car structure (members: model_year, color). Declare a variable of this structure and a pointer to this structure. Use the structure pointer to: 1) assign values to the members, and 2) print the assigned values.
Expected Output:
Enter Car Model Year: 2024
Enter Car Color: Red
--- Car Details (via Pointer) ---
Model Year: 2024
Color: Red
+ Hint
When accessing members using a structure pointer, you must use the arrow operator (->) instead of the dot operator (.). Also, the pointer must be assigned the address of the structure variable (ptr = &car_var;).
+ Show Solution
#include <stdio.h>
// 1. Structure Definition
struct Car {
int model_year;
char color[20];
};
int main() {
// 2. Declare a structure variable
struct Car my_car;
// 3. Declare a pointer to the structure
struct Car *car_ptr;
// 4. Point the pointer to the structure variable
car_ptr = &my_car;
// 5. Access and assign values using the arrow operator (->)
printf("Enter Car Model Year: \n");
scanf("%d", &car_ptr->model_year);
printf("Enter Car Color: ");
scanf("%s", car_ptr->color);
// 6. Access and display values using the arrow operator
printf("\n--- Car Details (via Pointer) ---\n");
printf("Model Year: %d\n", car_ptr->model_year);
printf("Color: %s\n", car_ptr->color);
return 0;
}Code language: C++ (cpp)
Explanation:
car_ptris a pointer designed to hold the memory address of astruct Car.- By assigning
car_ptr = &my_car;, it points to themy_carvariable. - The arrow operator (
->) is syntactical shorthand for dereferencing the pointer and then accessing a member. For example,car_ptr->model_yearis equivalent to(*car_ptr).model_year. This is the standard way to interact with structures via pointers.
Exercise 42: Basic Pointer Declaration and Dereference
Practice Problem: Declare an integer variable num and initialize it with a value (e.g., 42). Declare a pointer variable ptr that points to num. Print the value of num, the address of num, and the value retrieved by dereferencing the pointer ptr.
Expected Output:
Value of num: 42
Address of num (&num): 0x7ffd91a90a84
Value stored in ptr (address): 0x7ffd91a90a84
Value retrieved by *ptr: 42
+ Hint
- Use the address-of operator (
&) to assign the address ofnumtoptr. - Use the dereference operator (
*) to get the value stored at the address inptr. Use%pto print the memory address.
+ Show Solution
#include <stdio.h>
int main() {
int num = 42;
// Declare a pointer to an integer
int *ptr;
// Assign the address of num to ptr
ptr = #
printf("Value of num: %d\n", num);
printf("Address of num (&num): %p\n", &num);
printf("Value stored in ptr (address): %p\n", ptr);
// Dereference ptr to get the value at that address
printf("Value retrieved by *ptr: %d\n", *ptr);
return 0;
}Code language: C++ (cpp)
Explanation:
int *ptr;: This declaresptras a variable that holds the memory address of an integer.ptr = #: The address-of operator (&) retrieves the memory address wherenumis stored, and this address is assigned to the pointerptr.*ptr: The dereference operator (*) tells the program to access the value stored at the memory location currently held byptr. Sinceptrholds the address ofnum,*ptrgives us the value 42.
Exercise 43: Modifying Value via Pointer
Practice Problem: Declare an integer variable data with an initial value of 100. Declare a pointer data_ptr that points to data. Use the pointer only to change the value of data to 250. Print the final value of data.
Expected Output:
Initial value of data: 100
New value of data (modified via pointer): 250
+ Hint
To change the value that a pointer points to, you must dereference it on the left side of the assignment operator: *ptr = new_value;.
+ Show Solution
#include <stdio.h>
int main() {
int data = 100;
int *data_ptr = &data; // Initialization and assignment in one step
printf("Initial value of data: %d\n", data);
// Use the pointer to modify the value stored at its address
*data_ptr = 250;
printf("New value of data (modified via pointer): %d\n", data);
return 0;
}Code language: C++ (cpp)
Explanation:
int *data_ptr = &data;: The pointer is initialized to hold the address ofdata.*data_ptr = 250;: This is the core pointer operation. It is equivalent to saying: “Go to the memory address held bydata_ptr(which is the address ofdata), and put the value 250 there.” This directly overwrites the original value ofdata.
Exercise 44: Function with Pointer (Pass by Reference)
Practice Problem: Write a function named square_value that takes a pointer to an integer as its only argument. The function should calculate the square of the integer the pointer points to and store the result back into the same memory location.
Given:
int x = 5;Code language: Python (python)
Expected Output:
Original value of x: 5
Value of x after function call: 25
+ Hint
- The function signature should be
void square_value(int *n). - Inside the function, use the dereference operator to read the value (
*n), calculate the square, and then use the dereference operator again to write the result back (*n = ...).
+ Show Solution
#include <stdio.h>
// Function takes a pointer to an integer (pass by reference)
void square_value(int *n) {
// Read the value, calculate the square, and write the result back
*n = (*n) * (*n);
}
int main() {
int x = 5;
printf("Original value of x: %d\n", x);
// Pass the address of x to the function
square_value(&x);
printf("Value of x after function call: %d\n", x);
return 0;
}Code language: C++ (cpp)
Explanation:
- Pass by Reference: By passing the address (
&x), the function does not work on a copy of x but on the original variable’s memory. This is called pass by reference. *n = (*n) * (*n);: The function first dereferences the pointer to get the value 5. It squares it to get 25. It then uses the dereference operator on the left side to write 25 back into the memory location pointed to by n (which isx). The original variablexis permanently modified.
Exercise 45: Simple Pointer Arithmetic
Practice Problem: Declare an integer array arr of size 3 and initialize it with {10,20,30}. Declare an integer pointer p and make it point to the beginning of the array. Use pointer arithmetic to access and print the value of the second element (20).
Expected Output:
Value of the first element (arr[0]): 10
Value of the second element (arr[1] via pointer arithmetic): 20
Value of the second element (*p after increment): 20
+ Hint
- An array name (like
arr) is a pointer to its first element. - To access the next element, you can simply increment the pointer:
p + 1. Dereference the result to get the value.
+ Show Solution
#include <stdio.h>
int main() {
int arr[3] = {10, 20, 30};
int *p;
// The array name acts as a pointer to the first element (arr[0])
p = arr;
printf("Value of the first element (arr[0]): %d\n", *p);
// Pointer arithmetic: p + 1 points to the next integer element (arr[1])
// The asterisk (*) dereferences the new address
printf("Value of the second element (arr[1] via pointer arithmetic): %d\n", *(p + 1));
// We can also increment the pointer itself:
p++; // p now points to arr[1]
printf("Value of the second element (*p after increment): %d\n", *p);
return 0;
}Code language: C++ (cpp)
Explanation:
p = arr;: The array namearrevaluates to the address of its first element (&arr[0]).*(p + 1): When you add an integer N to a pointer, the pointer doesn’t just increase by N bytes; it increases by N times the size of the data type it points to. Since p is anint *,p + 1automatically moves the address forward bysizeof(int)bytes, making it point directly toarr[1]. The dereference operator then retrieves the value 20.
Exercise 46: Compare Pointers
Practice Problem: Declare two integer variables, A and B, and initialize them. Declare two pointers, ptrA and ptrB, pointing to A and B, respectively. Write a program to compare the values pointed to by ptrA and ptrB, and print which variable holds the larger value.
Given:
int A = 75;
int B = 92;Code language: Python (python)
Expected Output:
Variable A holds: 75
Variable B holds: 92
B is larger (Value: 92).
(Address of A is higher than address of B)
+ Hint
Use the dereference operator (*) to access the values for comparison. The comparison should be if (*ptrA > *ptrB).
+ Show Solution
#include <stdio.h>
int main() {
int A = 75;
int B = 92;
int *ptrA = &A;
int *ptrB = &B;
printf("Variable A holds: %d\n", *ptrA);
printf("Variable B holds: %d\n", *ptrB);
// Compare the values pointed to by the pointers
if (*ptrA > *ptrB) {
printf("A is larger (Value: %d).\n", *ptrA);
} else if (*ptrB > *ptrA) {
printf("B is larger (Value: %d).\n", *ptrB);
} else {
printf("The values are equal (Value: %d).\n", *ptrA);
}
// Example of comparing addresses (for conceptual clarity, though not the main requirement)
if (ptrA > ptrB) {
printf("\n(Address of A is higher than address of B)\n");
} else {
printf("\n(Address of B is higher than address of A)\n");
}
return 0;
}Code language: C++ (cpp)
Explanation:
- Pointer Assignment:
ptrA = &AandptrB = &Bassign the addresses of the two variables. - Value Comparison: The crucial part is
*ptrA > *ptrB. This compares the content of the memory locations (the values 75 and 92), not the addresses themselves. The program correctly identifies B as having the larger value. - Address Comparison: The second
ifstatement shows that you can also compare the pointers directly (ptrA > ptrB), which compares the numerical memory addresses, but this is usually only meaningful when pointers point to the same array or structure.
Exercise 47: Basic Recursion (Factorial)
Practice Problem: Write a recursive function factorial(int n) to calculate the factorial of a non-negative integer (n!). The definition is n!=n×(n−1)! and 0!=1.
A factorial, represented by an exclamation point (!), is the product of all positive integers up to a given non-negative integer, written as n!
Formula: For a non-negative integer n, the factorial is defined as:
n! = n × (n - 1) × (n - 2) × ... × 1
Examples:
0! = 1
1! = 1
3! = 3 × 2 × 1 = 6
5! = 5 × 4 × 3 × 2 × 1 = 120
Given:
int num = 5;Code language: Python (python)
+ Hint
Every recursive function needs two things:
- A Base Case: The condition that stops the recursion (
n == 0). - A Recursive Step: The call to the function itself, usually with a reduced parameter (
n * factorial(n - 1)).
+ Show Solution
#include <stdio.h>
// Recursive function for factorial
long long factorial(int n) {
// Base Case: Stops the recursion
if (n == 0) {
return 1;
}
// Recursive Step: Calls itself with n-1
return n * factorial(n - 1);
}
int main() {
int num = 5;
long long result = factorial(num);
printf("Factorial of %d is: %lld\n", num, result); // 5! = 120
return 0;
}Code language: C++ (cpp)
Explanation:
Recursion is the process where a function calls itself.
- Base Case (n=0): When the function hits the base case, it returns 1, preventing infinite calls.
- Stacking Calls: For
factorial(5), the calls stack up: 5×fact(4)→5×(4×fact(3))→⋯→5×4×3×2×1×fact(0). - Unwinding: Once fact(0) returns 1, the multiplication results are returned back up the stack (unwinding) until the final result is returned to
main. This process uses the program’s call stack to store intermediate results.
Exercise 48: Copy Array
Practice Problem: Write a C program to declare two arrays, A and B, and copy every element from array A into the corresponding position in array B.
Given:
int source_arr[5] = {1, 2, 3, 4, 5};
int dest_arr[5]; // Destination arrayCode language: C++ (cpp)
Expected Output:
Source array elements: 1 2 3 4 5
Destination array elements (after copy): 1 2 3 4 5
+ Hint
Create two arrays: a source array initialized with values, and a destination array declared with the same size. Use a simple for loop to iterate through the indices and directly assign the elements: destination[i] = source[i];.
+ Show Solution
#include <stdio.h>
int main() {
int size = 5;
int source_arr[5] = {1, 2, 3, 4, 5};
int dest_arr[5]; // Destination array
int i;
printf("Source array elements: ");
for (i = 0; i < size; i++) {
printf("%d ", source_arr[i]);
}
printf("\n");
// Loop to copy elements
for (i = 0; i < size; i++) {
dest_arr[i] = source_arr[i];
}
printf("Destination array elements (after copy): ");
for (i = 0; i < size; i++) {
printf("%d ", dest_arr[i]);
}
printf("\n");
return 0;
}Code language: C++ (cpp)
Explanation:
This is the most straightforward array manipulation technique.
- The program uses a
forloop that iterates from the first index (0) to the last index (size−1). - Inside the loop, the assignment statement
dest_arr[i] = source_arr[i];explicitly copies the value stored at index i of the source array into the same index i of the destination array. This ensures an exact, element-by-element replication of the source array’s content.
Exercise 49: Create and Write to a File
Practice Problem: Develop a C program to create a new text file named data.txt and write two lines of personal information (e.g., your name and age) to it using fprintf().
Expected Output:
Data successfully written to data.txt.
data.txt
Name: Alice Johnson
Age: 30 years
+ Hint
Use fopen() with the write mode ("w") to create or overwrite the file. Remember to check if the file pointer is NULL to handle potential errors, and use fclose() when finished.
+ Show Solution
Explanation:
- The program first declares a
FILEpointer,fp. It attempts to opendata.txtin write mode ("w"). If the file doesn’t exist, it’s created; if it exists, its content is truncated (deleted). The program checks iffpisNULL, which indicates a failure to open the file. - If successful,
fprintf()is used exactly likeprintf(), but its first argument is the file pointer, directing the output to the file instead of the console. Finally,fclose(fp)is called to close the file, flushing any remaining buffers and releasing the file resource.
Exercise 50: Read and Display File Content
Practice Problem: Read the entire content of the existing file data.txt (created in Exercise 1) and display it line by line on the console using fscanf() or fgets().
Expected Output:
Name: Alice Johnson
Age: 30 years
+ Hint
Open the file in read mode ("r"). Use a loop with fgets() to read strings line by line until it returns NULL (indicating the End-Of-File, or EOF, is reached).
+ Show Solution
Explanation:
- The file is opened in read mode (
"r"). A character array,buffer, is used as a temporary storage space for each line read. - The
fgets()function reads a line from the file stream (fp) and stores it intobuffer, reading at mostsizeof(buffer) - 1characters, or until a newline character or EOF is encountered. - The loop continues as long as
fgets()returns a non-NULL value. The content of the buffer is then printed to the standard output usingprintf().
Exercise 51: Append Data to a File
Practice Problem: Open the existing file data.txt(created in Exercise 1) in append mode and add today’s date and a short message (“Successfully appended.”) as new lines to the end of the file.
Expected Output:
data.txt
Name: Alice Johnson
Age: 30 years
Date Appended: 2025-10-15
Status: Successfully appended.
+ Hint
Use fopen() with the append mode ("a"). The append mode ensures that any new data is written to the end of the existing file content without overwriting it.
+ Show Solution
Explanation:
The core difference here is the use of the append mode ("a") in fopen(). When a file is opened in this mode, the file pointer is automatically positioned at the end of the file. Subsequent write operations using fprintf() or other output functions will simply add the new data after the existing content, preserving the original data.
Exercise 52: Count Characters in a File
Practice Problem: Write a program to read a text file (e.g., data.txt updated in Exercise 3) character by character and count the total number of characters in it, including spaces and newlines.
Expected Output:
Total number of characters in the file: 91
+ Hint
Open the file in read mode ("r"). Use a loop with the fgetc() function to read one character at a time. The loop should terminate when fgetc() returns the EOF (End-Of-File) constant.
+ Show Solution
Explanation:
- The file is read using the
fgetc()function, which returns the next character from the file stream as anint. We use anintto store the return value because it must be able to hold theEOFvalue (which is outside the range of a standardchar). - Inside the
whileloop, as long as the returned value is not equal toEOF, the character counter (char_count) is incremented.
Exercise 53: Count Lines in a File
Practice Problem: Read a any text file (e.g., data.txt updated in Exercise 3) and count the total number of lines in it. (A line is typically counted by the presence of the newline character \n).
Expected Output:
Total number of lines in the file: 4
+ Hint
Similar to the character counting exercise, use fgetc(). Inside the loop, check if the character read is equal to the newline character ('\n'). Increment a counter each time a newline is found.
+ Show Solution
Explanation:
This exercise uses fgetc() to iterate through the file.
- The program specifically looks for the newline character (
'\n'); every time this character is found, theline_countis incremented. - A key complexity in line counting is handling the last line of the file. If a file ends with actual content but without a final newline character, the last line won’t be counted.
- The robust solution often involves a conditional check after the loop to see if the file contained any characters at all and if the last character read was not a newline.
