This collection of 40 C programming array exercises is designed to sharpen your skills across all difficulty levels, from Beginner to Advanced. Arrays are fundamental to C programming, serving as the most basic structure for storing a collection of similar data types (like a list of numbers or characters).
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.
What You’ll Practice
These exercises provide practice problems and challenges to master the following core topics:
- 1D Arrays: Declaration, initialization, traversal, and basic manipulation of one-dimensional arrays.
- Core Concepts: Problems involving element insertion/deletion, frequency counting, finding duplicates, and reversing array elements.
- Searching & Sorting: Implementing and optimizing common algorithms like Linear Search, Binary Search, Bubble Sort, and Selection Sort using arrays.
- 2D Arrays (Matrices): Working with two-dimensional arrays, including initialization, matrix addition, subtraction, multiplication, and finding the transpose.
- Pointers & Arrays: Understanding the crucial relationship between arrays and pointers, including pointer arithmetic and using dynamic memory allocation (
malloc/calloc) with arrays.
Use Online C Compiler to solve exercises.
+ Table of Contents (40 Exercises)
Table of contents
- Exercise 1: Read and Print elements of an array
- Exercise 2: Sum and Average
- Exercise 3: Maximum and Minimum element
- Exercise 4: Count Even and Odd Elements
- Exercise 5: Reverse An Array In Place
- Exercise 6: Copy Array
- Exercise 7: Insert Element In Array
- Exercise 8: Delete an Element From Array
- Exercise 9: Find Second Largest and Second Smallest Element
- Exercise 10: Sum of Positive and Negative Numbers Separately
- Exercise 11: Search In Array
- Exercise 12: Frequency Count
- Exercise 13: Binary Search
- Exercise 14: Print Unique Elements
- Exercise 15: Merge Two Arrays
- Exercise 16: Check Array Palindrome
- Exercise 17: Sort An Array
- Exercise 18: Check If an Array Is Already Sorted
- Exercise 19: Sort An Array In Descending Order
- Exercise 20: Insertion Sort
- Exercise 21: Merge Two Sorted Arrays
- Exercise 22: Remove Duplicate Elements
- Exercise 23: Count Frequency Of Each Element
- Exercise 24: Most Frequent Element
- Exercise 25: Two arrays are equal or not
- Exercise 26: Separate Even and Odd Numbers
- Exercise 27: Rotate Array Left by One Position
- Exercise 28: Rotate Array Right by One Position
- Exercise 29: Rotate Array Left by n Positions
- Exercise 30: Rotate Array Right by n Positions
- Exercise 31: Remove Duplicate Elements from a Sorted Array
- Exercise 32: Remove Duplicate Elements from an Unsorted Array
- Exercise 33: Reverse a Portion of an Array
- Exercise 34: Find a Missing Number in a Sequence of 1 to N
- Exercise 35: Read and Print a 3×3 Matrix
- Exercise 36: Calculate Sum of All Elements in a Matrix
- Exercise 37: Print Matrix Elements in Reverse Order
- Exercise 38: Sum of Rows and Columns of a Matrix
- Exercise 39: Add Two Matrices
- Exercise 40: Subtract Two Matrices
Exercise 1: Read and Print elements of an array
Problem Statement: Write a C program that prompts the user to enter the size of an integer array, reads that many integer elements from the user, and then prints all the stored elements back to the console.
Expected Output:
Enter the number of elements (size of array): 5
Enter 5 integers:
Element 1: 10
Element 2: 20
Element 3: 30
Element 4: 40
Element 5: 50
Elements stored in the array are: 10 20 30 40 50
+ Hint
Use a single for loop combined with the scanf() function to handle all input elements. Use a separate for loop with printf() to display the elements. Remember to declare the array size before input, or use a Variable Length Array (VLA) based on the user’s input size.
+ Show Solution
#include <stdio.h>
int main() {
int size;
// 1. Get array size
printf("Enter the number of elements (size of array): ");
scanf("%d", &size);
// 2. Declare the array (using VLA feature)
int arr[size];
int i;
// 3. Read elements
printf("Enter %d integers:\n", size);
for (i = 0; i < size; i++) {
printf("Element %d: ", i + 1);
scanf("%d", &arr[i]);
}
// 4. Print elements
printf("\nElements stored in the array are: ");
for (i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}Code language: C++ (cpp)
Explanation:
- The program starts by taking the desired
sizeof the array from the user. An integer arrayarris then declared using this size. - The first
forloop iterates from i=0 up to i<size. In each iteration,scanf("%d", &arr[i]);reads an integer from the standard input and stores it at the current index i of the array. - The second
forloop is identical in structure but usesprintf()to retrieve and display the value stored atarr[i].
Exercise 2: Sum and Average
Problem Statement: Write a C program that calculates and prints the total sum and the arithmetic average of all numerical elements present in a given array.
Given:
int arr[5] = {10, 20, 30, 40, 50};Code language: C++ (cpp)
Expected Output:
Sum of array elements: 150
Average of array elements: 30.00
+ Hint
Initialize a variable, say sum, to 0. Iterate through the array and add each element to sum. For the average, divide the final sum by the total number of elements. Remember to use a floating-point data type for the average calculation to avoid integer division truncation.
+ Show Solution
#include <stdio.h>
int main() {
int size = 5;
int arr[5] = {10, 20, 30, 40, 50};
int sum = 0;
int i;
float average;
// 1. Calculate sum
for (i = 0; i < size; i++) {
sum += arr[i]; // sum = sum + arr[i]
}
// 2. Calculate average using type casting
average = (float)sum / size;
printf("\nSum of array elements: %d\n", sum);
printf("Average of array elements: %.2f\n", average);
return 0;
}Code language: C++ (cpp)
Explanation:
- The variable
sumis initialized to 0 to ensure an accurate starting point for calculation. - The
forloop traverses the array, and the linesum += arr[i];adds the value of the current element to the running total. - To compute the average, we divide
sumbysize. The critical step is(float)sum / size;, which performs explicit type casting. This converts the integersuminto a floating-point number before division, ensuring the division result is a precise floating-point number, which is then stored in thefloatvariableaverage.
Exercise 3: Maximum and Minimum element
Problem Statement: Write a C program that determines and prints the largest (maximum) and the smallest (minimum) value among all elements in a given array.
Given:
int arr[6] = {55, 12, 89, 4, 30, 77};Code language: C++ (cpp)
Expected Output:
Maximum element in the array: 89
Minimum element in the array: 4
+ Hint
- Initialize your
maxandminvariables with the first element of the array. - Then, loop through the rest of the array (starting from the second element, index 1) and compare each element to your current
maxandmin, updating them if a larger or smaller value is found.
+ Show Solution
#include <stdio.h>
int main() {
int size = 6;
int arr[6] = {55, 12, 89, 4, 30, 77};
int i;
int max, min;
// Initialize max and min with the first element of the array
max = arr[0];
min = arr[0];
// Iterate from the second element (index 1)
for (i = 1; i < size; i++) {
// Check for Maximum
if (arr[i] > max) {
max = arr[i];
}
// Check for Minimum
if (arr[i] < min) {
min = arr[i];
}
}
printf("Array elements: 55, 12, 89, 4, 30, 77\n");
printf("Maximum element in the array: %d\n", max);
printf("Minimum element in the array: %d\n", min);
return 0;
}Code language: C++ (cpp)
Explanation:
The program initializes max and min to arr[0]. This guarantees the starting values are within the range of the array’s elements. The for loop then begins at index i=1. Inside the loop, two independent if statements perform the comparisons:
- If the current element
arr[i]is greater than the currentmax,maxis updated. - If the current element
arr[i]is less than the currentmin,minis updated.
By the end of the single traversal, max holds the largest value and min holds the smallest.
Exercise 4: Count Even and Odd Elements
Problem Statement: Write a C program that counts and print the total number of even numbers and the total number of odd numbers stored within an integer array.
Given:
int arr[8] = {1, 4, 7, 12, 15, 20, 3, 10};Code language: C++ (cpp)
Expected Output:
Array: 1, 4, 7, 12, 15, 20, 3, 10
Total even elements: 4
Total odd elements: 4
+ Hint
- Use two counters,
even_countandodd_count, initialized to 0. - Iterate through the array. For each element, use the modulo operator (
%) to check its parity: ifelement%2==0, it is even; otherwise, it is odd. Increment the respective counter.
+ Show Solution
#include <stdio.h>
int main() {
int size = 8;
int arr[8] = {1, 4, 7, 12, 15, 20, 3, 10};
int even_count = 0;
int odd_count = 0;
int i;
printf("Array: 1, 4, 7, 12, 15, 20, 3, 10\n");
for (i = 0; i < size; i++) {
// Check if the remainder when divided by 2 is 0 (Even)
if (arr[i] % 2 == 0) {
even_count++;
}
// If the remainder is not 0 (Odd)
else {
odd_count++;
}
}
printf("Total even elements: %d\n", even_count);
printf("Total odd elements: %d\n", odd_count);
return 0;
}Code language: C++ (cpp)
Explanation:
The core logic relies on the modulo operator (%).
- If the remainder is 0 (i.e.,
arr[i] % 2 == 0), the number is perfectly divisible by 2 and is counted as even. - If the remainder is 1 (or any non-0 value in the case of negative numbers, though here we assume positive inputs), the number is not perfectly divisible by 2 and is counted as odd.
The program uses a single for loop to check every element once, making the process efficient.
Exercise 5: Reverse An Array In Place
Problem Statement: Write a C program to reverse the order of elements in an array without using a second, auxiliary array. The reversal must be performed directly within the original array (in-place).
Given:
int arr[7] = {10, 20, 30, 40, 50, 60, 70};Code language: C++ (cpp)
Expected Output:
Original array: 10 20 30 40 50 60 70
Reversed array: 70 60 50 40 30 20 10
+ Hint
To reverse in place, you need to swap elements. You should swap the element at index 0 with the element at index size−1, index 1 with index size−2, and so on. Crucially, you only need to iterate up to the middle of the array, specifically size/2, to prevent swapping the elements back to their original positions.
+ Show Solution
#include <stdio.h>
int main() {
int size = 7;
int arr[7] = {10, 20, 30, 40, 50, 60, 70};
int temp; // Temporary variable for swapping
int i;
printf("Original array: ");
for (i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// Loop only up to size / 2
for (i = 0; i < size / 2; i++) {
// Swap arr[i] with arr[size - 1 - i]
// 1. Store the value of the element from the end
temp = arr[size - 1 - i];
// 2. Replace the element from the end with the element from the start
arr[size - 1 - i] = arr[i];
// 3. Replace the element from the start with the stored value (original end element)
arr[i] = temp;
}
printf("Reversed array: ");
for (i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}Code language: C++ (cpp)
Explanation:
The key to in-place reversal is the swapping mechanism and limiting the loop to half the array size.
- Index Pair: For an array of size, the index i (from the start) is paired with the index size−1−i (from the end).
- Swapping: A temporary variable (
temp) is mandatory to hold one of the values during the swap operation.- The value at the end index (
arr[size - 1 - i]) is stored intemp. - The value at the start index (
arr[i]) is copied to the end index. - The value saved in
temp(the original end value) is copied to the start index.
- The value at the end index (
- Loop Limit: The loop runs only up to
size / 2(e.g., for size 7, i runs from 0 to 2, performing 3 swaps: (0,6), (1,5), (2,4)). This prevents the elements from being swapped twice, which would return them to their original order.
Exercise 6: Copy Array
Problem Statement: 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 7: Insert Element In Array
Problem Statement: Write a C program that takes an element and a desired position from the user and inserts that element into the specified position of an array, shifting existing elements as necessary.
Given:
#include <stdio.h>
int main() {
int size = 5; // Initial size is 5, capacity for 6
int arr[6] = {10, 20, 30, 40, 50};
int element = 35;
int position = 4; // Insert at Position 4 (index 3)
return 0;
}Code language: C++ (cpp)
Expected Output:
Array after inserting 35 at position 4 (index 3):
10 20 30 35 40 50
+ Hint
Before inserting the new value, you must make space for it. If you insert at position P, all elements from P to the end of the array must be shifted one position to the right (e.g., arr[i]=arr[i−1]). Crucially, this shifting must be done starting from the last element and working backward to prevent overwriting the element you still need to shift.
+ Show Solution
#include <stdio.h>
int main() {
int size = 5;
// Initial size is 5, capacity for 6
int arr[6] = {10, 20, 30, 40, 50};
int element = 35;
int position = 4; // Position 4 (index 3)
int i;
printf("Initial array (size %d): 10, 20, 30, 40, 50\n", size);
// Position is 1-based, convert to 0-based index
int index = position - 1;
if (index < 0 || index > size) {
printf("Invalid position for insertion.\n");
return 1;
}
// 1. Shift elements one position to the right (starting from the end)
for (i = size; i > index; i--) {
arr[i] = arr[i - 1];
}
// 2. Insert the new element
arr[index] = element;
// 3. Increment the size of the array
size++;
printf("Array after inserting %d at position %d (index %d):\n", element, position, index);
for (i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}Code language: C++ (cpp)
Explanation:
Array insertion requires two main steps:
- Shifting (The Critical Step): The loop
for (i = size; i > index; i--)starts from the new logical end of the array (size) and moves backward until it reaches the insertion point (index). Inside,arr[i] = arr[i - 1];copies the element at the preceding index (i-1) to the current index (i). This creates a duplicate of the element atindex, effectively making space. - Insertion: Once space is made, the new element is placed at
arr[index] = element;. - Size Update: Finally, the logical size of the array (
size) is incremented to reflect the new element count. (Note: Arrays in C have a fixed physical size; this process is only possible if the array was declared with extra capacity).
Exercise 8: Delete an Element From Array
Problem Statement: Write a C program that takes a position from the user and removes the element at that position in an array, shifting the subsequent elements to fill the resulting gap.
Given:
int size = 6;
int arr[6] = {10, 20, 30, 40, 50, 60};
int position = 3; // Remove Position 3 (i.e., index 2)Code language: C++ (cpp)
Expected Output:
Initial array (size 6): 10, 20, 30, 40, 50, 60
Array after deleting element at position 3 (index 2):
10 20 40 50 60
+ Hint
To delete an element at position P, you need to overwrite it. Shift all elements from position P+1 to the end of the array one position to the left (e.g., arr[i−1]=arr[i]). This shifting must be done starting from the position after the deletion point and moving forward.
+ Show Solution
#include <stdio.h>
int main() {
int size = 6;
int arr[6] = {10, 20, 30, 40, 50, 60};
int position = 3; // Position 3 (index 2)
int i;
printf("Initial array (size %d): 10, 20, 30, 40, 50, 60\n", size);
// Position is 1-based, convert to 0-based index
int index = position - 1;
if (index < 0 || index >= size) {
printf("Invalid position for deletion.\n");
return 1;
}
// 1. Shift elements one position to the left (starting from the deletion index)
// This overwrites the element at 'index'
for (i = index; i < size - 1; i++) {
arr[i] = arr[i + 1];
}
// 2. Decrement the size of the array
size--;
printf("Array after deleting element at position %d (index %d):\n", position, index);
for (i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}Code language: C++ (cpp)
Explanation:
Array deletion is essentially the reverse of insertion:
- Shifting (The Critical Step): The loop
for (i = index; i < size - 1; i++)starts at the index where the deletion is to occur (index). Inside the loop,arr[i] = arr[i + 1];copies the element at the next index (i+1) into the current index (i). This action immediately overwrites the element being deleted and shifts all subsequent elements to the left. - Size Update: The logical size of the array (
size) is decremented. Although the array element at the last physical position remains (it’s a duplicate of the previous element), it is now outside the logical bounds of the array and will not be printed in the output loop.
Exercise 9: Find Second Largest and Second Smallest Element
Problem Statement: Write a C program to identify and print the second largest and the second smallest unique elements in a given array.
Given:
int size = 7;
int arr[7] = {10, 50, 20, 80, 40, 90, 30};Code language: C++ (cpp)
Expected Output:
Array elements: 10, 50, 20, 80, 40, 90, 30
Second Largest (Max): 80
Second Smallest (Min): 20
+ Hint
- The most efficient approach is a single-pass solution. Maintain four variables:
max1(largest),max2(second largest),min1(smallest), andmin2(second smallest). - Initialize all four variables carefully (e.g., using the first few unique elements or a very large/small dummy value). Iterate through the array and update the maximum and minimum pairs simultaneously based on the element’s value.
+ Show Solution
#include <stdio.h>
#include <limits.h> // For INT_MIN and INT_MAX
int main() {
int size = 7;
int arr[7] = {10, 50, 20, 80, 40, 90, 30};
int i;
// Initialize max1 and max2 to the smallest possible integer value
int max1 = INT_MIN;
int max2 = INT_MIN;
// Initialize min1 and min2 to the largest possible integer value
int min1 = INT_MAX;
int min2 = INT_MAX;
printf("Array elements: 10, 50, 20, 80, 40, 90, 30\n");
for (i = 0; i < size; i++) {
// Finding Max1 and Max2
if (arr[i] > max1) {
max2 = max1; // Current max1 becomes the second max
max1 = arr[i]; // Current element becomes the new max1
} else if (arr[i] > max2 && arr[i] != max1) {
max2 = arr[i]; // Update max2 if element is between max1 and max2
}
// Finding Min1 and Min2
if (arr[i] < min1) {
min2 = min1; // Current min1 becomes the second min
min1 = arr[i]; // Current element becomes the new min1
} else if (arr[i] < min2 && arr[i] != min1) {
min2 = arr[i]; // Update min2 if element is between min1 and min2
}
}
printf("First Largest (Max1): %d\n", max1);
printf("Second Largest (Max2): %d\n", max2);
printf("First Smallest (Min1): %d\n", min1);
printf("Second Smallest (Min2): %d\n", min2);
return 0;
}Code language: C++ (cpp)
Explanation:
This solution uses a single loop to find both pairs simultaneously.
- Initialization:
max1andmax2are initialized toINT_MIN(the smallest possible integer) to ensure any array element will be larger. Conversely,min1andmin2are initialized toINT_MAX(the largest possible integer). - Max Logic:
- If
arr[i]is greater thanmax1, it means we found a new largest element. We promote the oldmax1tomax2, and setarr[i]as the newmax1. - If
arr[i]is not the largest (max1), but it is greater thanmax2and not equal tomax1(handling duplicates), then it is the new second largest (max2).
- If
- Min Logic: The logic for
min1andmin2follows the same structure but with reversed comparison operators (<). This single-pass method is more efficient than sorting the entire array first.
Exercise 10: Sum of Positive and Negative Numbers Separately
Problem Statement: Write a C program that iterates through an array of positive, negative, and zero integers and calculates two separate sums: the total sum of all positive numbers, and the total sum of all negative numbers.
Given:
int size = 9;
int arr[9] = {15, -5, 20, 0, -10, 30, -25, 5, 0};Code language: C++ (cpp)
Expected Output:
Array elements: 15, -5, 20, 0, -10, 30, -25, 5, 0
Sum of all positive numbers: 70
Sum of all negative numbers: -40
+ Hint
- Initialize two accumulators,
pos_sumandneg_sum, to 0. - Loop through the array. Inside the loop, use an
if-else ifstructure to check if the current element is greater than 0 (positive) or less than 0 (negative). Add the element to the corresponding sum variable. Ignore elements that are equal to 0.
+ Show Solution
#include <stdio.h>
int main() {
int size = 9;
int arr[9] = {15, -5, 20, 0, -10, 30, -25, 5, 0};
long long pos_sum = 0; // Use long long for potential large sums
long long neg_sum = 0;
int i;
printf("Array elements: 15, -5, 20, 0, -10, 30, -25, 5, 0\n");
for (i = 0; i < size; i++) {
if (arr[i] > 0) {
// Positive numbers
pos_sum += arr[i];
} else if (arr[i] < 0) {
// Negative numbers
neg_sum += arr[i];
}
// If arr[i] == 0, it is ignored
}
printf("Sum of all positive numbers: %lld\n", pos_sum);
printf("Sum of all negative numbers: %lld\n", neg_sum);
return 0;
}Code language: C++ (cpp)
Explanation:
This program uses a conditional approach within a single traversal loop.
- Initialization: Two separate variables,
pos_sumandneg_sum, are initialized to 0. We uselong longfor the sums to safely handle large possible totals. - Conditional Check:
- The
if (arr[i] > 0)block handles positive numbers, adding them topos_sum. - The
else if (arr[i] < 0)block handles negative numbers, adding them toneg_sum. Note that when adding a negative number, the sum effectively decreases.
- The
- Zero Handling: Since there is no
elseblock to catcharr[i] == 0, any zero elements are naturally skipped and do not affect eitherpos_sumorneg_sum.
Exercise 11: Search In Array
Problem Statement: Implement a C program to search for a specific target value within an array. The program should return the index (position) of the first occurrence of the element if found, or a message indicating it was not found.
Given:
int arr[] = {10, 50, 30, 70, 80, 20, 90, 40};
int search_element = 70;Code language: C++ (cpp)
Expected Output:
Element 70 found at index 3.
+ Hint
Use a simple for loop to iterate sequentially through the array, starting from index 0. In each iteration, compare the current array element with the target value. If they match, immediately print the index and use return or break to exit the loop/function
+ Show Solution
#include <stdio.h>
int linear_search(int arr[], int size, int target) {
int i;
for (i = 0; i < size; i++) {
// Check if the current element matches the target
if (arr[i] == target) {
return i; // Return the index immediately upon finding the element
}
}
return -1; // Return -1 if the loop completes without finding the target
}
int main() {
int arr[] = {10, 50, 30, 70, 80, 20, 90, 40};
int size = sizeof(arr) / sizeof(arr[0]);
int search_element = 70;
int index;
index = linear_search(arr, size, search_element);
if (index != -1) {
printf("Element %d found at index %d.\n", search_element, index);
} else {
printf("Element %d not found in the array.\n", search_element);
}
return 0;
}Code language: C++ (cpp)
Explanation:
- Linear search is the simplest search algorithm. It sequentially checks every element in the array until a match is found.
- The
linear_searchfunction iterates using aforloop. Ifarr[i]equals thetarget, the loop is terminated early by returning the index i. If the loop completes without finding a match, it means the element is not present, and the function returns −1 (a conventional indicator for “not found”). - The time complexity of this algorithm is O(n).
Exercise 12: Frequency Count
Problem Statement: Write a C program to count how many times a particular element (provided by the user or hardcoded) appears in a given array.
Given:
int arr[] = {1, 5, 2, 8, 5, 1, 5, 9};
int search_element = 5;Code language: C++ (cpp)
Expected Output:
Element 5 appears 3 times in the array.
+ Hint
Initialize a counter variable to 0. Use a for loop to traverse the array. Inside the loop, check if the current array element matches the target element. If it matches, increment the counter.
+ Show Solution
#include <stdio.h>
int count_frequency(int arr[], int size, int target) {
int i;
int count = 0;
for (i = 0; i < size; i++) {
if (arr[i] == target) {
count++;
}
}
return count;
}
int main() {
int arr[] = {1, 5, 2, 8, 5, 1, 5, 9};
int size = sizeof(arr) / sizeof(arr[0]);
int search_element = 5;
int freq;
freq = count_frequency(arr, size, search_element);
printf("Element %d appears %d times in the array.\n", search_element, freq);
return 0;
}Code language: C++ (cpp)
Explanation:
This is another linear scan problem with O(n) complexity.
The function count_frequency iterates through the array element by element. It uses a simple equality check (arr[i] == target). Every time a match is found, the count variable is incremented. The final value of count represents the total occurrences of the target element.
Exercise 13: Binary Search
Problem Statement: Implement a C program to search for a target value in a sorted array using the highly efficient binary search algorithm. The program should return the index of the element if found.
Binary search requires the array to be sorted. It works by repeatedly dividing the search interval in half. Define three indices: low (start of the segment), high (end of the segment), and mid (the middle element). Compare the target with the value at mid:
- If
targetequalsmid, returnmid. - If
targetis less thanmid, sethigh = mid - 1. - If
targetis greater thanmid, setlow = mid + 1.
Given:
int arr[] = {10, 20, 30, 40, 50, 60, 70, 80};
int search_element = 50;Code language: C++ (cpp)
Expected Output:
Element 50 found at index 4.
+ Hint
- If
targetequalsmid, returnmid. - If
targetis less thanmid, sethigh = mid - 1. - If
targetis greater thanmid, setlow = mid + 1.
+ Show Solution
#include <stdio.h>
int binary_search(int arr[], int size, int target) {
int low = 0;
int high = size - 1;
int mid;
while (low <= high) {
mid = low + (high - low) / 2; // Prevent integer overflow for very large arrays
if (arr[mid] == target) {
return mid; // Element found
} else if (arr[mid] < target) {
low = mid + 1; // Search in the right half
} else {
high = mid - 1; // Search in the left half
}
}
return -1; // Element not found
}
int main() {
// Binary search requires a SORTED array
int arr[] = {10, 20, 30, 40, 50, 60, 70, 80};
int size = sizeof(arr) / sizeof(arr[0]);
int search_element = 50;
int index;
index = binary_search(arr, size, search_element);
if (index != -1) {
printf("Element %d found at index %d.\n", search_element, index);
} else {
printf("Element %d not found.\n", search_element);
}
return 0;
}Code language: C++ (cpp)
Explanation:
Binary search operates on the principle of divide and conquer. It uses a while (low <= high) loop to continue searching as long as the segment is valid. In each step, it calculates the midpoint mid.
- If the element at
midis the target, the index is returned. - If the target is larger, the search space is narrowed to the right half by setting
low = mid + 1. - If the target is smaller, the search space is narrowed to the left half by setting
high = mid - 1. Because it eliminates half of the remaining elements in each step, its time complexity is O(logn), making it vastly superior to linear search for large, sorted datasets.
Exercise 14: Print Unique Elements
Problem Statement: Develop a C program that initializes an integer array and identifies and prints all unique elements (those that appear exactly once in the array).
Given:
int arr[] = {5, 2, 8, 5, 1, 2, 9, 8, 4};Code language: C++ (cpp)
Expected Output:
Array: 5 2 8 5 1 2 9 8 4
Unique elements are: 1 9 4
+ Hint
- Use two nested loops. The outer loop selects an element, and the inner loop checks if that element is repeated anywhere else in the array.
- Use a flag or counter to track the frequency of the selected element.
+ Show Solution
#include <stdio.h>
int main() {
int arr[] = {5, 2, 8, 5, 1, 2, 9, 8, 4};
int n = sizeof(arr) / sizeof(arr[0]);
int i, j, is_unique;
printf("Array: ");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\nUnique elements are: ");
for (i = 0; i < n; i++) {
is_unique = 1; // Assume the element is unique
// Check the element against all other elements
for (j = 0; j < n; j++) {
// Check for duplicates, but skip comparing the element with itself (i != j)
if (i != j && arr[i] == arr[j]) {
is_unique = 0; // Found a duplicate, so it is NOT unique
break; // No need to check further for this element
}
}
// If the flag is still 1, no duplicate was found
if (is_unique == 1) {
printf("%d ", arr[i]);
}
}
printf("\n");
return 0;
}Code language: C++ (cpp)
Explanation:
- The program iterates through the array using the outer loop (
i). For each elementarr[i], a flagis_uniqueis set to1(true). - The inner loop (
j) checks ifarr[i]matches any other elementarr[j]. The conditioni != jensures an element isn’t compared to itself. If a match is found,is_uniqueis set to0(false), and the inner loop breaks. - If, after the inner loop completes,
is_uniqueremains1, the elementarr[i]is printed as it has no duplicates, meaning it appeared exactly once.
Exercise 15: Merge Two Arrays
Problem Statement: Write a C program that takes two separate integer arrays, A and B, and merges all their elements into a third, larger array, C. Print the resulting merged array.
Given:
int arrA[] = {10, 20, 30};
int arrB[] = {40, 50, 60, 70};Code language: C++ (cpp)
Expected Output:
Merged array C: 10 20 30 40 50 60 70
+ Hint
- The size of the merged array C must be the sum of the sizes of A and B.
- Use two separate loops to copy all elements from A into the beginning of C, and then copy all elements from B into the remaining positions of C, starting the second copy operation at the index equal to the size of A.
+ Show Solution
#include <stdio.h>
int main() {
int arrA[] = {10, 20, 30};
int nA = sizeof(arrA) / sizeof(arrA[0]);
int arrB[] = {40, 50, 60, 70};
int nB = sizeof(arrB) / sizeof(arrB[0]);
int nC = nA + nB; // Total size of the merged array
int arrC[nC];
int i;
// 1. Copy elements of arrA into arrC
for (i = 0; i < nA; i++) {
arrC[i] = arrA[i];
}
// 2. Copy elements of arrB into arrC, starting at index nA
// The index for arrC is (nA + i)
for (i = 0; i < nB; i++) {
arrC[nA + i] = arrB[i];
}
// 3. Print the merged array arrC
printf("Merged array C: ");
for (i = 0; i < nC; i++) {
printf("%d ", arrC[i]);
}
printf("\n");
return 0;
}Code language: C++ (cpp)
Explanation:
- The program first determines the size of the third array,
nC = nA + nB. - The first
forloop copies the elements ofarrAinto the firstnApositions ofarrC. - The second
forloop handles the merging ofarrB. - Crucially, to place the elements of
arrBafter those ofarrA, the destination index inarrCis calculated asnA + i. - As
igoes from 0 tonB-1, the destination indices arenA,nA+1, …,nC-1, successfully appending the second array.
Exercise 16: Check Array Palindrome
Problem Statement: Create a C program that determines whether an array of integers is a palindrome. An array is a palindrome if it reads the same forwards and backwards.
Given:
int arr1[] = {1, 2, 3, 2, 1}; // Palindrome
int arr2[] = {1, 2, 3, 4, 5}; // Not a palindromeCode language: C++ (cpp)
Expected Output:
Array 1 is a palindrome.
Array 2 is NOT a palindrome.
+ Hint
- Use two index pointers: one starting at the beginning of the array (
start = 0) and one starting at the end (end = n-1). - Use a
whileloop that continues as long asstartis less thanend. In each iteration, compare the elements atarr[start]andarr[end]. - If they don’t match, the array is not a palindrome, and you can immediately stop and report the result.
+ Show Solution
#include <stdio.h>
int is_array_palindrome(int arr[], int n) {
int start = 0;
int end = n - 1;
while (start < end) {
if (arr[start] != arr[end]) {
return 0; // Not a palindrome
}
start++;
end--;
}
return 1; // It is a palindrome
}
int main() {
int arr1[] = {1, 2, 3, 2, 1}; // Palindrome
int n1 = sizeof(arr1) / sizeof(arr1[0]);
int arr2[] = {1, 2, 3, 4, 5}; // Not a palindrome
int n2 = sizeof(arr2) / sizeof(arr2[0]);
if (is_array_palindrome(arr1, n1)) {
printf("Array 1 is a palindrome.\n");
} else {
printf("Array 1 is NOT a palindrome.\n");
}
if (is_array_palindrome(arr2, n2)) {
printf("Array 2 is a palindrome.\n");
} else {
printf("Array 2 is NOT a palindrome.\n");
}
return 0;
}Code language: C++ (cpp)
Explanation:
- The function
is_array_palindromeuses the two-pointer approach. Pointersstartandendare initialized to the first and last indices, respectively. Thewhile (start < end)loop continues checking pairs of elements from the outside inward. - If any pair
arr[start]andarr[end]are unequal, the function immediately returns0(false). If the loop completes without finding any unequal pairs (meaningstarthas met or passedend), the array is a palindrome, and the function returns1(true).
Exercise 17: Sort An Array
Problem Statement: Write a C program to sort an array of integers in ascending order using the Bubble Sort algorithm.
Given:
int arr[] = {64, 34, 25, 12, 22, 11, 90};Code language: C++ (cpp)
Expected Output:
Array sorted in ascending order: 11 12 22 25 34 64 90
+ Hint
- Bubble sort uses nested loops. The outer loop controls the number of passes (size−1 passes are needed). The inner loop performs the comparisons and swaps.
- In each pass
i, the largest unsorted element “bubbles up” to its correct position at the end of the unsorted portion. The inner loop can be optimized to run only up tosize−1−ibecause the elements at the end are already sorted.
+ Show Solution
#include <stdio.h>
void bubble_sort(int arr[], int size) {
int i, j, temp;
int swapped;
// Outer loop for passes (size - 1 passes)
for (i = 0; i < size - 1; i++) {
swapped = 0; // Flag to detect if any swap occurred (optimization)
// Inner loop for comparison and swapping
// Iterates up to the last unsorted element
for (j = 0; j < size - 1 - i; j++) {
// Compare adjacent elements for ascending order
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j+1]
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = 1;
}
}
// If no two elements were swapped in inner loop, array is sorted
if (swapped == 0) {
break;
}
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int size = sizeof(arr) / sizeof(arr[0]);
int i;
bubble_sort(arr, size);
printf("Array sorted in ascending order: ");
for (i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}Code language: C++ (cpp)
Explanation:
Bubble sort compares and swaps adjacent elements.
- The outer loop ensures the process repeats until the entire array is sorted. The inner loop’s condition (
arr[j] > arr[j + 1]) checks for ascending order. If the condition is true, the elements are swapped using a temporary variabletemp. - The complexity is O(n2) in the worst and average cases. The
swappedflag provides a slight optimization: if a pass completes with no swaps, the array is already sorted, and the outer loop can break early.
Exercise 18: Check If an Array Is Already Sorted
Problem Statement: Create a function in C that takes an array and its size, and returns a boolean value (or 1/0 in C) indicating whether the array is currently sorted in ascending order.
Given:
int sorted_arr[] = {10, 20, 30, 40, 50};
int unsorted_arr[] = {10, 30, 20, 40, 50};
int size = 5;Code language: C++ (cpp)
Expected Output:
Array 1 is sorted: True
Array 2 is sorted: False
+ Hint
- To check for ascending order, you only need to compare each element
arr[i]with the element immediately following it,arr[i+1]. If, at any point,arr[i] > arr[i+1], the array is not sorted, and you can immediately return false/0. - If the loop completes without finding any such violation, the array is sorted.
+ Show Solution
#include <stdio.h>
#include <stdbool.h> // Include for using bool type (optional, can use int/0/1)
// Returns 1 (true) if sorted, 0 (false) otherwise
int is_sorted(int arr[], int size) {
int i;
// Only need to check up to the second-to-last element (size - 2)
for (i = 0; i < size - 1; i++) {
// If the current element is greater than the next element, it is NOT sorted
if (arr[i] > arr[i + 1]) {
return 0; // Not sorted
}
}
return 1; // Loop completed, no violation found
}
int main() {
int sorted_arr[] = {10, 20, 30, 40, 50};
int unsorted_arr[] = {10, 30, 20, 40, 50};
int size = 5;
printf("Array 1 is sorted: %s\n", is_sorted(sorted_arr, size) ? "True" : "False");
printf("Array 2 is sorted: %s\n", is_sorted(unsorted_arr, size) ? "True" : "False");
return 0;
}Code language: C++ (cpp)
Explanation:
- This function is highly efficient with O(n) time complexity. It only requires a single pass through the array.
- The loop iterates from
i=0up toi<size−1. This ensures that when we checkarr[i+1], we do not go out of bounds. The conditionarr[i] > arr[i + 1]is the definition of unsorted (in ascending order). As soon as this condition is met, the function immediately terminates and returns 0. - If the entire loop finishes, it means every adjacent pair was correctly ordered, and the function returns 1
Exercise 19: Sort An Array In Descending Order
Problem Statement: Write a C program to sort an array of integers in non-increasing (descending) order using the Selection Sort algorithm.
Given:
int arr[] = {64, 25, 12, 22, 11};Code language: C++ (cpp)
Expected Output:
Array sorted in descending order: 64 25 22 12 11
+ Hint
Selection sort also uses nested loops.
- The outer loop iterates from
i=0tosize−2. In each pass i, the inner loop searches the unsorted portion (from indexitosize−1) to find the maximum element. - Once the maximum is found, it is swapped with the element at the current starting position
i.
+ Show Solution
#include <stdio.h>
void selection_sort_descending(int arr[], int size) {
int i, j, max_idx, temp;
// Outer loop runs from 0 up to size - 2
for (i = 0; i < size - 1; i++) {
// Assume the first element of the unsorted subarray is the maximum
max_idx = i;
// Inner loop finds the true maximum element in the remaining unsorted array
for (j = i + 1; j < size; j++) {
// Find the index of the maximum element for descending order
if (arr[j] > arr[max_idx]) {
max_idx = j;
}
}
// Swap the found maximum element with the element at position i
if (max_idx != i) {
temp = arr[i];
arr[i] = arr[max_idx];
arr[max_idx] = temp;
}
}
}
int main() {
int arr[] = {64, 25, 12, 22, 11};
int size = sizeof(arr) / sizeof(arr[0]);
int i;
selection_sort_descending(arr, size);
printf("Array sorted in descending order: ");
for (i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}Code language: C++ (cpp)
Explanation:
Selection sort is characterized by minimizing the number of swaps (one per pass). For descending order, the goal of each pass is to find the largest remaining element.
- The outer loop controls the boundary between the sorted and unsorted parts.
- The inner loop finds the index (
max_idx) of the largest element in the unsorted segment. - After the inner loop finishes, the largest element (at
max_idx) is swapped with the element at the beginning of the unsorted segment (arr[i]). This places the maximum value in its correct descending position. Its time complexity is alwaysO(n2)because it always performs the full nested loop comparisons, regardless of the initial order.
Exercise 20: Insertion Sort
Problem Statement: Write a C program to sort an array in ascending order using the Insertion Sort algorithm.
Given:
int arr[] = {12, 11, 13, 5, 6};Code language: C++ (cpp)
Expected Output:
Array sorted using Insertion Sort: 5 6 11 12 13
+ Hint
Insertion sort works like sorting a hand of playing cards. It divides the array into a sorted portion (initially just the first element) and an unsorted portion. The outer loop picks an element from the unsorted part (the key). The inner loop shifts elements in the sorted portion that are greater than the key one position to the right, and then inserts the key into the correct empty slot.
+ Show Solution
#include <stdio.h>
void insertion_sort(int arr[], int size) {
int i, key, j;
// Outer loop iterates from the second element (start of unsorted section)
for (i = 1; i < size; i++) {
key = arr[i]; // The element to be inserted into the sorted sub-array
j = i - 1; // Start comparison from the last element of the sorted sub-array
// Inner loop: Move elements of the sorted sub-array that are greater than key,
// to one position ahead of their current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
// Place the key element in its correct position
arr[j + 1] = key;
}
}
int main() {
int arr[] = {12, 11, 13, 5, 6};
int size = sizeof(arr) / sizeof(arr[0]);
int i;
insertion_sort(arr, size);
printf("Array sorted using Insertion Sort: ");
for (i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}Code language: C++ (cpp)
Explanation:
Insertion sort excels when the array is nearly sorted.
- The outer loop (
i) iterates through the unsorted elements, picking thekey. - The
keyis compared backward (j) against the elements in the already sorted subarray. - If an element
arr[j]is larger than thekey, it is shifted right (arr[j + 1] = arr[j]). - This shifting continues until an element smaller than or equal to the
keyis found, or the beginning of the array is reached. - Finally, the
keyis placed into the empty spot created by the shifts (arr[j + 1] = key). Its best-case time complexity isO(n)(when already sorted), but its worst-case complexity remainsO(n2).
Exercise 21: Merge Two Sorted Arrays
Problem Statement: Given two arrays, A and B, which are both individually sorted in ascending order, write a C program to merge them into a third array, C, such that C is also sorted, without using a sorting algorithm on C.
Given:
int arr1[] = {10, 30, 50, 70};
int size1 = 4;
int arr2[] = {20, 40, 60, 80, 90};
int size2 = 5;Code language: C++ (cpp)
Expected Output:
Merged sorted array: 10 20 30 40 50 60 70 80 90
+ Hint
Use a three-point approach:
- One point for array A (
i), one for array B (j), and one for the resulting merged array C (k). - While both A and B have elements remaining, compare
A[i]andB[j]. Copy the smaller element toC[k]and increment the corresponding source pointer and the C pointer. - After one array is exhausted, copy the remaining elements from the other array into C.
+ Show Solution
#include <stdio.h>
void merge_sorted_arrays(int arr1[], int size1, int arr2[], int size2, int arr3[]) {
int i = 0; // Pointer for arr1
int j = 0; // Pointer for arr2
int k = 0; // Pointer for arr3 (merged array)
// 1. Traverse both arrays and compare elements
while (i < size1 && j < size2) {
if (arr1[i] < arr2[j]) {
arr3[k++] = arr1[i++];
} else {
arr3[k++] = arr2[j++];
}
}
// 2. Copy remaining elements of arr1 (if any)
while (i < size1) {
arr3[k++] = arr1[i++];
}
// 3. Copy remaining elements of arr2 (if any)
while (j < size2) {
arr3[k++] = arr2[j++];
}
}
int main() {
int arr1[] = {10, 30, 50, 70};
int size1 = 4;
int arr2[] = {20, 40, 60, 80, 90};
int size2 = 5;
// The merged array must be large enough to hold all elements
int size3 = size1 + size2;
int arr3[size3];
int i;
merge_sorted_arrays(arr1, size1, arr2, size2, arr3);
printf("Merged sorted array: ");
for (i = 0; i < size3; i++) {
printf("%d ", arr3[i]);
}
printf("\n");
return 0;
}Code language: C++ (cpp)
Explanation:
This efficient merging process has a time complexity of O(n+m) where n and m are the sizes of the input arrays.
- Main Loop: The first
whileloop runs as long as there are elements in both source arrays. It compares the current elements (arr1[i]vsarr2[j]) and copies the smaller one to the merged array (arr3[k]), incrementing both the source pointer and the merge pointer. - Cleanup Loops: The two subsequent
whileloops handle the case where one array has run out of elements but the other still has some remaining. Since the remaining elements of the non-exhausted array are already sorted, they can be directly appended to the merged array.
Exercise 22: Remove Duplicate Elements
Problem Statement: Write a C program that removes duplicate elements from an array, modifying the array in-place to contain only unique elements, and returns the new size of the modified array.
Given:
int arr[] = {10, 20, 20, 30, 10, 40, 50, 50, 40};Code language: C++ (cpp)
Expected Output:
Original array (size 9): 10 20 20 30 10 40 50 50 40
Array after removing duplicates (new size 5): 10 20 30 40 50
+ Hint
- The easiest way to remove duplicates efficiently is to first sort the array. After sorting, duplicates will be adjacent.
- Use two pointers:
ito traverse all elements, andjto keep track of the last unique element recorded. Ifarr[i]is different fromarr[j], copyarr[i]toarr[j+1]and advancej.
+ Show Solution
#include <stdio.h>
#include <stdlib.h> // For qsort
// Comparison function for qsort (ascending order)
int compare(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
// Function to remove duplicates (modifies the array and returns new size)
int remove_duplicates(int arr[], int size) {
if (size == 0 || size == 1) {
return size;
}
// 1. Sort the array so duplicates are adjacent
qsort(arr, size, sizeof(int), compare);
int i, j = 0; // j is the index of the last unique element written
// 2. Traverse the sorted array
for (i = 1; i < size; i++) {
// If the current element is NOT equal to the last unique element (arr[j])
if (arr[i] != arr[j]) {
j++; // Move the unique index forward
arr[j] = arr[i]; // Copy the new unique element
}
// If arr[i] == arr[j], it's a duplicate and is skipped
}
// New size is j + 1
return j + 1;
}
int main() {
int arr[] = {10, 20, 20, 30, 10, 40, 50, 50, 40};
int size = sizeof(arr) / sizeof(arr[0]);
int new_size;
int i;
printf("Original array (size %d): ", size);
for (i = 0; i < size; i++) { printf("%d ", arr[i]); }
printf("\n");
new_size = remove_duplicates(arr, size);
printf("Array after removing duplicates (new size %d): ", new_size);
// Print only up to the new size
for (i = 0; i < new_size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}Code language: C++ (cpp)
Explanation:
The most practical approach involves two steps:
- Sorting: The
qsortlibrary function is used to sort the array. This places all duplicates next to each other. The time complexity is dominated by the sorting, which is typically O(nlogn). - In-Place Removal: We use a pointer
jto track the position where the next unique element should be written, andito read all elements. The conditionarr[i] != arr[j]ensures that only unique values are copied to the front of the array. The final number of unique elements is j+1, which is returned as the new effective size of the array. The elements after this new size are logically considered removed.
Exercise 23: Count Frequency Of Each Element
Problem Statement: Write a C program to determine the frequency (number of occurrences) of every unique element within a given array.
Given:
int arr[] = {2, 5, 2, 8, 5, 1};Code language: C++ (cpp)
Expected Output:
Frequencies:
Element 1: 1 times
Element 2: 2 times
Element 5: 2 times
Element 8: 1 times
+ Hint
The simplest robust method is to first sort the array. After sorting, equal elements are adjacent. Iterate through the array and count consecutive identical elements. Use a separate auxiliary array or set a flag to handle elements that have already been counted (though sorting makes this simpler).
+ Show Solution
#include <stdio.h>
#include <stdlib.h> // For qsort
// Comparison function for qsort (ascending order)
int compare_qsort(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
void count_all_frequencies(int arr[], int size) {
int i, j;
int count;
// 1. Sort the array
qsort(arr, size, sizeof(int), compare_qsort);
printf("Frequencies:\n");
// 2. Iterate through the sorted array and count consecutive duplicates
for (i = 0; i < size; i++) {
// If the current element is different from the previous one, start a new count
if (i == 0 || arr[i] != arr[i - 1]) {
count = 1;
// Inner loop to count consecutive occurrences
for (j = i + 1; j < size; j++) {
if (arr[j] == arr[i]) {
count++;
} else {
break; // Stop counting when a different element is found
}
}
// Print the result for the unique element arr[i]
printf("Element %d: %d times\n", arr[i], count);
}
}
}
int main() {
int arr[] = {2, 5, 2, 8, 5, 1, 5, 9, 1, 2};
int size = sizeof(arr) / sizeof(arr[0]);
count_all_frequencies(arr, size);
return 0;
}Code language: C++ (cpp)
Explanation:
This technique leverages sorting to group identical elements, simplifying the counting process.
- Sorting: The array is sorted (O(nlogn)).
- Outer Loop (
i): Iterates through the entire array. The conditionif (i == 0 || arr[i] != arr[i - 1])ensures that we only start a new count when we encounter a unique element for the first time in the sorted sequence. - Inner Loop (
j): This loop efficiently counts how many elements immediately followingarr[i]are identical. - Printing: Once the inner loop breaks (due to finding a different element), the frequency is printed for the element at index i. Because the outer loop only processes the first occurrence of a unique element, we avoid redundant counting and printing.
Exercise 24: Most Frequent Element
Problem Statement: Write a C program to find and print the element that appears the greatest number of times (the mode) in a given array.
Given:
int arr[] = {2, 5, 2, 8, 5, 1, 5, 9, 1, 2, 5};Code language: C++ (cpp)
Expected Output:
The most frequent element is: 5
+ Hint
This builds on the frequency counting from Exercise 20. First, sort the array. Then, traverse the array, keeping track of the current_count and the max_count found so far. Every time current_count exceeds max_count, update max_count and store the current element as the most_frequent_element.
+ Show Solution
#include <stdio.h>
#include <stdlib.h>
// Comparison function for qsort (ascending order)
int compare_qsort_mf(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
int find_most_frequent(int arr[], int size) {
if (size == 0) return -1; // Handle empty array
// 1. Sort the array
qsort(arr, size, sizeof(int), compare_qsort_mf);
int max_count = 0;
int most_frequent_element = arr[0];
int current_count;
int i, j;
// 2. Traverse the sorted array
for (i = 0; i < size; i++) {
// Start count only for the first occurrence of a unique element
if (i == 0 || arr[i] != arr[i - 1]) {
current_count = 1;
// Count consecutive occurrences (inner loop is not strictly necessary,
// but keeps the logic simple after sorting)
for (j = i + 1; j < size; j++) {
if (arr[j] == arr[i]) {
current_count++;
} else {
break;
}
}
// 3. Update maximum frequency
if (current_count > max_count) {
max_count = current_count;
most_frequent_element = arr[i];
}
}
}
return most_frequent_element;
}
int main() {
int arr[] = {2, 5, 2, 8, 5, 1, 5, 9, 1, 2, 5};
int size = sizeof(arr) / sizeof(arr[0]);
int result;
result = find_most_frequent(arr, size);
printf("The most frequent element is: %d\n", result);
return 0;
}Code language: C++ (cpp)
Explanation:
This solution uses the same O(nlogn) sorting approach as the previous exercise, adding a simple comparison to find the maximum frequency.
- Sorting: The array is sorted.
- Tracking Max: We maintain
max_countandmost_frequent_element. - Counting & Comparison: As we iterate and count the occurrences of each unique element (
current_count), we compare it againstmax_count. Ifcurrent_countis higher, the max variables are updated. Since the elements are already sorted, the first one encountered that matches themax_countwill be the one stored. If multiple elements have the same highest frequency, the one that appeared first in the sorted array is returned.
Exercise 25: Two arrays are equal or not
Problem Statement: Write a C program that compares two arrays of integers, A and B, and determines if they are exactly equal (same size and all elements at corresponding indices are identical).
Given:
int arr_a[] = {10, 20, 30, 40};
int arr_b[] = {10, 20, 30, 40}; // Equal to A
int arr_c[] = {10, 20, 30, 41}; // Mismatch in last element
int arr_d[] = {10, 20, 30}; // Different sizeCode language: C++ (cpp)
Expected Output:
A and B are equal: True
A and C are equal: False
A and D are equal: False
+ Hint
Two arrays are equal if and only if:
- They have the same size.
- Every element at index i in array A is equal to the element at index i in array B.
First, check the sizes. If sizes differ, return 0. If sizes are the same, iterate through the arrays and check for element inequality (A[i] != B[i]). If inequality is found, return 0. If the loop completes, return 1.
+ Show Solution
#include <stdio.h>
// Returns 1 (equal) or 0 (not equal)
int are_arrays_equal(int arr1[], int size1, int arr2[], int size2) {
int i;
// 1. Check if the sizes are equal
if (size1 != size2) {
return 0; // Not equal if sizes differ
}
// 2. Check elements one by one
for (i = 0; i < size1; i++) {
if (arr1[i] != arr2[i]) {
return 0; // Not equal if any element mismatch
}
}
// 3. If sizes are same and no mismatch found
return 1; // Arrays are equal
}
int main() {
int arr_a[] = {10, 20, 30, 40};
int arr_b[] = {10, 20, 30, 40}; // Equal to A
int arr_c[] = {10, 20, 30, 41}; // Mismatch in last element
int arr_d[] = {10, 20, 30}; // Different size
int size_a = 4;
int size_b = 4;
int size_c = 4;
int size_d = 3;
// Test cases
printf("A and B are equal: %s\n", are_arrays_equal(arr_a, size_a, arr_b, size_b) ? "True" : "False");
printf("A and C are equal: %s\n", are_arrays_equal(arr_a, size_a, arr_c, size_c) ? "True" : "False");
printf("A and D are equal: %s\n", are_arrays_equal(arr_a, size_a, arr_d, size_d) ? "True" : "False");
return 0;
}Code language: C++ (cpp)
Explanation:
- The function first ensures the two arrays have the same number of elements. If they do, it proceeds to the single
forloop, which iterates from i=0 up to the common size. In this loop, if a mismatch is found (arr1[i] != arr2[i]), the function immediately returns 0 (false). - If the loop finishes without finding any mismatch, it confirms that all corresponding elements are identical, and the function returns 1 (true). The time complexity is dominated by the linear scan, O(n), where n is the size of the arrays.
Exercise 26: Separate Even and Odd Numbers
Problem Statement: Write a C program that takes one integer array and separates its elements into two new arrays: one containing all the even numbers and the other containing all the odd numbers. Print all three arrays.
Given:
int arr[] = {10, 15, 22, 27, 34, 41, 50};Code language: C++ (cpp)
Expected Output:
Even array: 10 22 34 50
Odd array: 15 27 41
+ Hint
- Declare two new arrays large enough to hold all elements.
- Iterate through the original array and use the modulus operator (
%) to check if an element is even (arr[i] % 2 == 0) or odd (arr[i] % 2 != 0). - Use separate index counters (
even_count,odd_count) for the new arrays to track where the next number should be placed.
+ Show Solution
#include <stdio.h>
int main() {
int arr[] = {10, 15, 22, 27, 34, 41, 50};
int n = sizeof(arr) / sizeof(arr[0]);
// Declare two new arrays and their respective counters
int even_arr[n], odd_arr[n];
int even_count = 0;
int odd_count = 0;
int i;
// 1. Separate the elements
for (i = 0; i < n; i++) {
if (arr[i] % 2 == 0) {
// Even number
even_arr[even_count] = arr[i];
even_count++;
} else {
// Odd number
odd_arr[odd_count] = arr[i];
odd_count++;
}
}
// 2. Print the original array
printf("Original array: ");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// 3. Print the even array
printf("Even array: ");
for (i = 0; i < even_count; i++) {
printf("%d ", even_arr[i]);
}
printf("\n");
// 4. Print the odd array
printf("Odd array: ");
for (i = 0; i < odd_count; i++) {
printf("%d ", odd_arr[i]);
}
printf("\n");
return 0;
}Code language: C++ (cpp)
Explanation:
The program iterates through the original array arr. Inside the loop, arr[i] % 2 checks the remainder when the element is divided by 2.
- If the remainder is 0, the number is even, and it is copied to the
even_arrat indexeven_count, andeven_countis incremented. - If the remainder is not 0, the number is odd, and it is copied to the odd_arr at index odd_count, and odd_count is incremented.
- The final printing loops use even_count and odd_count (rather than the full size n) to ensure only the valid elements are displayed
Exercise 27: Rotate Array Left by One Position
Problem Statement: Write a C program to perform a left rotation of an array by one position. In a left rotation, every element is shifted one index to the left, and the first element moves to the end of the array.
Given:
int arr[] = {1, 2, 3, 4, 5};Code language: C++ (cpp)
Expected Output:
Original array: 1 2 3 4 5
Array after left rotation by 1: 2 3 4 5 1
+ Hint
- Store the first element in a temporary variable before starting the rotation.
- Then, shift all subsequent elements one position to their left (
arr[i] = arr[i+1]). - Finally, place the temporary first element at the last position of the array.
+ Show Solution
#include <stdio.h>
void rotate_left_one(int arr[], int n) {
if (n <= 1) return; // No rotation needed for 0 or 1 element
int first_element = arr[0]; // Store the first element
// Shift all elements one position left
for (int i = 0; i < n - 1; i++) {
arr[i] = arr[i + 1];
}
// Place the stored first element at the end
arr[n - 1] = first_element;
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: 1 2 3 4 5\n");
rotate_left_one(arr, n);
printf("Array after left rotation by 1: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]); // Output: 2 3 4 5 1
}
printf("\n");
return 0;
}Code language: C++ (cpp)
Explanation: The rotation is done in three steps:
- The value of the first element (
arr[0]) is saved infirst_element. - A loop runs from index 0 up to
n-2. In each iteration, the element at the current index (arr[i]) is overwritten by the element at the next index (arr[i+1]). This effectively shifts all elements left by one. - The loop stops when the second-to-last element has been moved to the last index. The saved
first_elementis then placed into the empty last index (arr[n-1]).
Exercise 28: Rotate Array Right by One Position
Problem Statement: Write a C program to perform a right rotation of an array by one position. In a right rotation, every element is shifted one index to the right, and the last element moves to the beginning of the array.
Given:
int arr[] = {1, 2, 3, 4, 5};Code language: C++ (cpp)
Expected Output:
Original array: 1 2 3 4 5
Array after right rotation by 1: 5 1 2 3 4
+ Hint
- Store the last element in a temporary variable. Then, shift all preceding elements one position to their right, starting the shift from the second-to-last element down to the first element (
arr[i] = arr[i-1]). - Finally, place the temporary last element at the first position.
+ Show Solution
#include <stdio.h>
void rotate_right_one(int arr[], int n) {
if (n <= 1) return; // No rotation needed
int last_element = arr[n - 1]; // Store the last element
// Shift all elements one position right, starting from the end
for (int i = n - 1; i > 0; i--) {
arr[i] = arr[i - 1];
}
// Place the stored last element at the beginning
arr[0] = last_element;
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: 1 2 3 4 5\n");
rotate_right_one(arr, n);
printf("Array after right rotation by 1: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]); // Output: 5 1 2 3 4
}
printf("\n");
return 0;
}Code language: C++ (cpp)
Explanation: This rotation is similar to the left rotation but reversed.
- The value of the last element (
arr[n-1]) is saved. - A loop runs backward, from
n-1down to 1. In each step, the element atarr[i]receives the value fromarr[i-1]. This ensures we don’t overwrite the previous element before moving it. - When the loop finishes, the value at
arr[1]has been moved toarr[2], and the original value atarr[0]is now atarr[1]. - The saved
last_elementis placed into the empty first position (arr[0]).
Exercise 29: Rotate Array Left by n Positions
Problem Statement: Write a C program to perform a left rotation of an array by an arbitrary number of positions, k.
Given:
int arr[] = {1, 2, 3, 4, 5, 6, 7};Code language: C++ (cpp)
Expected Output:
Original array: 1 2 3 4 5 6 7
Array after left rotation by 3: 4 5 6 7 1 2 3
+ Hint
- The simplest approach is to call the
rotate_left_onefunction (from exercise 26) repeatedly, k times. - A more efficient approach is to use the Juggling Algorithm or the Reversal Algorithm. For beginners, the repeated single rotation is usually the first step.
+ Show Solution
#include <stdio.h>
// Helper function from exercise 26
void rotate_left_one(int arr[], int n) {
if (n <= 1) return;
int first = arr[0];
for (int i = 0; i < n - 1; i++) {
arr[i] = arr[i + 1];
}
arr[n - 1] = first;
}
void rotate_left_k(int arr[], int n, int k) {
// Normalize k: rotation by n positions is the same as 0 rotation
k = k % n;
for (int i = 0; i < k; i++) {
rotate_left_one(arr, n);
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7};
int n = sizeof(arr) / sizeof(arr[0]);
int k = 3; // Rotate left by 3 positions
printf("Original array: 1 2 3 4 5 6 7\n");
rotate_left_k(arr, n, k);
printf("Array after left rotation by %d: ", k);
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]); // Output: 4 5 6 7 1 2 3
}
printf("\n");
return 0;
}Code language: C++ (cpp)
Explanation: This solution utilizes the previous single-rotation logic.
- First, the rotation count k is normalized using the modulo operator:
k = k % n. This handles cases where k is greater than or equal to the array size (e.g., rotating an array of size 7 by 10 positions is the same as rotating it by 10%7 = 3 positions). - A loop then calls the
rotate_left_onefunction exactly k times, performing the overall multi-position shift
Exercise 30: Rotate Array Right by n Positions
Problem Statement: Write a C program to perform a right rotation of an array by an arbitrary number of positions, k.
Given:
int arr[] = {1, 2, 3, 4, 5, 6, 7};
int k = 3; // Rotate right by 3 positionsCode language: C++ (cpp)
Expected Output:
Original array: 1 2 3 4 5 6 7
Array after right rotation by 3: 5 6 7 1 2 3 4
+ Hint
Use the same strategy as the left rotation: call the rotate_right_one function (from rotate array right by one position exercise) repeatedly, k times. Remember to normalize k using the modulo operator.
+ Show Solution
#include <stdio.h>
// Helper function from exercise 27
void rotate_right_one(int arr[], int n) {
if (n <= 1) return;
int last = arr[n - 1];
for (int i = n - 1; i > 0; i--) {
arr[i] = arr[i - 1];
}
arr[0] = last;
}
void rotate_right_k(int arr[], int n, int k) {
// Normalize k
k = k % n;
for (int i = 0; i < k; i++) {
rotate_right_one(arr, n);
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7};
int n = sizeof(arr) / sizeof(arr[0]);
int k = 3; // Rotate right by 3 positions
printf("Original array: 1 2 3 4 5 6 7\n");
rotate_right_k(arr, n, k);
printf("Array after right rotation by %d: ", k);
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]); // Output: 5 6 7 1 2 3 4
}
printf("\n");
return 0;
}Code language: C++ (cpp)
Explanation: The solution uses the single right rotation function repeatedly.
- The number of rotations k is first normalized using
k = k % n. - The loop then calls rotate_right_one k times.
- Note: For an array of size N, rotating right by k positions is equivalent to rotating left by N – k positions.
- If efficiency is critical, one can check if k < N/2 to decide whether to rotate right or left for fewer operations.
Exercise 31: Remove Duplicate Elements from a Sorted Array
Problem Statement: Write a C program to remove duplicate elements from a given array that is already sorted. The modification should happen in-place (i.e., modify the original array), and the function should return the length of the new array with unique elements.
Given:
int arr[] = {1, 1, 2, 2, 2, 3, 4, 4, 5};Code language: C++ (cpp)
Expected Output:
Original array: 1 1 2 2 2 3 4 4 5
Array after removing duplicates (new size 5): 1 2 3 4 5
+ Hint
- Since the array is sorted, duplicates are always adjacent.
- Use two pointers:
ito iterate through the array andjto track the index of the last unique element found. - If
arr[i]is different fromarr[j], it’s a new unique element; thus, incrementjand copyarr[i]toarr[j]. If they are the same, just continue the loop, skipping the duplicate.
+ Show Solution
#include <stdio.h>
int remove_duplicates(int arr[], int n) {
if (n == 0 || n == 1) {
return n; // No duplicates if 0 or 1 element
}
int j = 0; // Index for the new array (last unique element found)
// Compare arr[i] with arr[j]. If different, copy arr[i] to arr[++j]
for (int i = 0; i < n - 1; i++) {
if (arr[i] != arr[i + 1]) {
arr[j] = arr[i];
j++;
}
}
// The last element of the original array is always unique in the new unique array
arr[j] = arr[n - 1];
j++;
return j; // New length of the array
}
int main() {
int arr[] = {1, 1, 2, 2, 2, 3, 4, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: 1 1 2 2 2 3 4 4 5\n");
int new_n = remove_duplicates(arr, n);
printf("Array after removing duplicates (new size %d): ", new_n);
for (int i = 0; i < new_n; i++) {
printf("%d ", arr[i]); // Output: 1 2 3 4 5
}
printf("\n");
return 0;
}Code language: C++ (cpp)
Explanation: The two-pointer technique efficiently removes duplicates in-place because the array is sorted.
- The outer loop compares
arr[i]with the next elementarr[i+1]. - If
arr[i] != arr[i+1], it meansarr[i]is the end of a unique sequence. This unique value is copied toarr[j], and the unique pointer j is incremented to point to the next free slot. - If
arr[i] == arr[i+1], we skiparr[i], effectively ignoring the duplicate. - The loop stops at the second-to-last element. The last element,
arr[n-1], must be added separately because the loop conditioni < n - 1prevents it from being compared againstarr[i+1]. The final value ofjis the new size.
Exercise 32: Remove Duplicate Elements from an Unsorted Array
Problem Statement: Write a C program to remove duplicate elements from a given array that is unsorted. The modification should happen in-place.
Given:
int arr[] = {4, 2, 4, 1, 5, 2, 3, 1};Code language: C++ (cpp)
Expected Output:
Original array: 4 2 4 1 5 2 3 1
Array after removing duplicates (new size 5): 4 2 1 5 3
+ Hint
Since the array is unsorted, we cannot use the efficient two-pointer method.
- Use two nested loops: the outer loop iterates through the array, and the inner loop checks for duplicates of the current element.
- If a duplicate is found, it must be removed, which means shifting all subsequent elements left by one position.
+ Show Solution
#include <stdio.h>
int remove_duplicates_unsorted(int arr[], int n) {
int i, j, k;
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
// Duplicate found
if (arr[i] == arr[j]) {
// Shift all subsequent elements one position left
for (k = j; k < n - 1; k++) {
arr[k] = arr[k + 1];
}
n--; // Decrease the array size
j--; // Recheck the element at the current 'j' index
}
}
}
return n; // New length
}
int main() {
int arr[] = {4, 2, 4, 1, 5, 2, 3, 1};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: 4 2 4 1 5 2 3 1\n");
int new_n = remove_duplicates_unsorted(arr, n);
printf("Array after removing duplicates (new size %d): ", new_n);
for (int i = 0; i < new_n; i++) {
printf("%d ", arr[i]); // Output: 4 2 1 5 3
}
printf("\n");
return 0;
}Code language: C++ (cpp)
Explanation:
The outer loop (i) picks a unique element candidate and the inner loop (j) checks all elements after arr[i].
If a duplicate (arr[i] == arr[j]) is found:
- A third loop (
k) performs a shift operation, moving every element from indexj+1one position left to fill the gap left by the duplicate. - The effective array size
nis decremented. - The inner loop index
jis decremented (j--) because the element that just shifted intoarr[j](which was originally atarr[j+1]) needs to be checked in the next iteration againstarr[i]for potential duplication.
Exercise 33: Reverse a Portion of an Array
Problem Statement: Write a C program to reverse the elements of an array between a specified start index and end index (inclusive).
Given:
int arr[] = {10, 20, 30, 40, 50, 60, 70};Code language: C++ (cpp)
Expected Output:
Original array: 10 20 30 40 50 60 70
Array after reversing indices 2 to 5: 10 20 60 50 40 30 70
+ Hint
- Use the two-pointer swap technique used in the palindrome check, but restrict the pointers to the specified sub-range.
- Initialize one pointer to the start index and the other to the end index. In a loop, swap the elements at the two pointers, then move the start pointer forward and the end pointer backward until they meet or cross.
+ Show Solution
#include <stdio.h>
void reverse_portion(int arr[], int start, int end) {
int temp;
// Use a while loop to swap elements from the outside-in
while (start < end) {
// Swap arr[start] and arr[end]
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
// Move pointers towards the middle
start++;
end--;
}
}
int main() {
int arr[] = {10, 20, 30, 40, 50, 60, 70};
int n = sizeof(arr) / sizeof(arr[0]);
int start_index = 2; // Element 30
int end_index = 5; // Element 60
printf("Original array: 10 20 30 40 50 60 70\n");
// Reverse portion from index 2 to 5 (30, 40, 50, 60)
reverse_portion(arr, start_index, end_index);
printf("Array after reversing indices %d to %d: ", start_index, end_index);
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]); // Output: 10 20 60 50 40 30 70
}
printf("\n");
return 0;
}Code language: C++ (cpp)
Explanation:
The reverse_portion function uses two parameters, start and end, which define the sub-array to be reversed.
- The
while (start < end)loop controls the process, ensuring elements are swapped only once. - Inside the loop, the element at
arr[start]is swapped with the element atarr[end]using a temporary variabletemp. - The pointers are then adjusted:
startincreases andenddecreases. This moves the pointers closer together, narrowing the un-reversed section until the entire portion is reversed.
Exercise 34: Find a Missing Number in a Sequence of 1 to N
Problem Statement: Given an array of size N-1 containing distinct integers in the range 1 to N, write a C program to find the single integer that is missing from the sequence.
Given:
// Array contains numbers from 1 to 9, so N=10. Missing is 6.
int arr[] = {1, 2, 3, 4, 5, 7, 8, 9, 10};Code language: C++ (cpp)
Expected Output:
The missing number in the sequence 1 to 10 is: 6
+ Hint
- The sum of all numbers from 1 to N can be calculated using the formula: Sum = N * (N + 1) / 2. Calculate the sum of the elements present in the given array.
- The missing number is the difference between the expected total sum and the actual array sum.
+ Show Solution
#include <stdio.h>
// Function to calculate the sum of 1 to N
long long expected_sum(int N) {
// Uses the arithmetic series sum formula
return (long long)N * (N + 1) / 2;
}
int find_missing_number(int arr[], int n) {
// The sequence is from 1 to N. Since the array has n elements, N = n + 1
int N = n + 1;
long long total_sum = expected_sum(N);
long long actual_sum = 0;
// Calculate the sum of elements present in the array
for (int i = 0; i < n; i++) {
actual_sum += arr[i];
}
// The missing number is the difference
return (int)(total_sum - actual_sum);
}
int main() {
// Array contains numbers from 1 to 9, so N=10. Missing is 6.
int arr[] = {1, 2, 3, 4, 5, 7, 8, 9, 10};
int n = sizeof(arr) / sizeof(arr[0]);
int missing = find_missing_number(arr, n);
printf("The missing number in the sequence 1 to %d is: %d\n", n + 1, missing); // Output: 6
return 0;
}Code language: C++ (cpp)
Explanation:
This problem is solved using a simple mathematical property of arithmetic series.
- The array size
nmeans the full sequence should contain N = n + 1 numbers. - The function
expected_sum(N)calculates the total sum if no number were missing (i.e., 1+2+…+N). - The main function calculates the
actual_sumof the elements currently in the array. - The difference:
Missing Number = Expected Sum - Actual Sumgives the single missing integer. This approach is highly efficient (O(n)).
Exercise 35: Read and Print a 3×3 Matrix
Problem Statement: Write a C program to read elements from the user for a 3×3 matrix (3 rows and 3 columns) and then display the matrix elements in a clear, row-by-row format.
Expected Output:
Enter the elements of the 3x3 matrix:
Element [0][0]: 10
Element [0][1]: 20
Element [0][2]: 30
Element [1][0]: 40
Element [1][1]: 50
Element [1][2]: 60
Element [2][0]: 70
Element [2][1]: 80
Element [2][2]: 90
The matrix is:
10 20 30
40 50 60
70 80 90
+ Hint
- You’ll need two nested
forloops for iteration. The outer loop controls the rows (i), and the inner loop controls the columns (j). - Use
scanf()inside the inner loop to read the elements andprintf()in a similar structure (with a newline\nafter the inner loop finishes) to display them.
+ Show Solution
#include <stdio.h>
int main() {
int matrix[3][3];
int i, j;
// 1. Read elements
printf("Enter the elements of the 3x3 matrix:\n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("Element [%d][%d]: ", i, j);
scanf("%d", &matrix[i][j]);
}
}
// 2. Print elements
printf("\nThe matrix is:\n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n"); // Newline after each row
}
return 0;
}Code language: C++ (cpp)
Explanation:
- A 2D array,
matrix[3][3], is declared. - The first set of nested loops handles input. The element is stored at
matrix[i][j]whereiis the row index andjis the column index. - The second set of nested loops prints the matrix. The
\t(tab) creates clean spacing between column elements, and the\n(newline) after the inner loop ensures that each new row starts on a new line, displaying the matrix correctly.
Exercise 36: Calculate Sum of All Elements in a Matrix
Problem Statement: Write a C program to calculate and print the sum of all integer elements present in a given matrix.
Given:
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}}; // 2x3 matrixCode language: C++ (cpp)
Expected Output:
Sum of all elements in the matrix: 21
+ Hint
- Initialize a variable
total_sumto zero. - Use nested loops to iterate through every cell of the matrix. Inside the innermost part of the loop, add the current element
matrix[i][j]tototal_sum.
+ Show Solution
#include <stdio.h>
int main() {
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}}; // 2x3 matrix
int rows = 2, cols = 3;
int i, j;
int total_sum = 0;
printf("Matrix:\n1 2 3\n4 5 6\n");
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
total_sum += matrix[i][j]; // Add current element to sum
}
}
printf("\nSum of all elements in the matrix: %d\n", total_sum); // Expected: 21
return 0;
}Code language: C++ (cpp)
Explanation:
- The variable
total_sumaccumulates the value. - The nested
forloops ensure that the indicesi(rows) andj(columns) cover every single element in the matrix exactly once. - The statement
total_sum += matrix[i][j];performs the accumulation.
Exercise 37: Print Matrix Elements in Reverse Order
Problem Statement: Write a C program to print all elements of a matrix starting from the last element (bottom-right) and ending with the first element (top-left).
Given:
int matrix[3][2] = {{10, 20}, {30, 40}, {50, 60}}; // 3x2 matrixCode language: C++ (cpp)
Expected Output:
Original Matrix:
10 20
30 40
50 60
Elements in reverse order: 60 50 40 30 20 10
+ Hint
- Reverse the order of the nested loops.
- The outer loop should iterate backward from the last row index (
rows - 1down to 0), and the inner loop should iterate backward from the last column index (cols - 1down to 0).
+ Show Solution
#include <stdio.h>
int main() {
int matrix[3][2] = {{10, 20}, {30, 40}, {50, 60}}; // 3x2 matrix
int rows = 3, cols = 2;
int i, j;
printf("Original Matrix:\n10 20\n30 40\n50 60\n");
printf("\nElements in reverse order: ");
// Outer loop: Iterate rows backwards
for (i = rows - 1; i >= 0; i--) {
// Inner loop: Iterate columns backwards
for (j = cols - 1; j >= 0; j--) {
printf("%d ", matrix[i][j]);
}
}
printf("\n"); // Output: 60 50 40 30 20 10
return 0;
}Code language: C++ (cpp)
Explanation: To achieve reverse order, the iteration direction is flipped.
- The outer loop starts at
i = rows - 1and decreases until 0, ensuring we start from the last row. - The inner loop starts at
j = cols - 1and decreases until 0, ensuring we print elements from right to left within each row.
Exercise 38: Sum of Rows and Columns of a Matrix
Problem Statement: Write a C program to calculate and print the sum of elements for each individual row and the sum of elements for each individual column of a matrix.
Given:
int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};Code language: C++ (cpp)
Expected Output:
Sum of Row 1: 6
Sum of Row 2: 15
Sum of Row 3: 24
Sum of Column 1: 12
Sum of Column 2: 15
Sum of Column 3: 18
+ Hint
- To find row sums, use nested loops. Initialize a
row_sumvariable to 0 outside the inner loop. Reset and calculaterow_sumwithin the inner loop for each iteration of the outer (row) loop. - To find column sums, you can either use a separate set of nested loops, switching the order of iteration, or use a separate array to accumulate column totals across the rows.
+ Show Solution
#include <stdio.h>
int main() {
int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int rows = 3, cols = 3;
int i, j;
int col_sum[cols]; // Array to store column sums
// Initialize column sum array to 0
for(i = 0; i < cols; i++) {
col_sum[i] = 0;
}
// 1. Calculate Row Sums and accumulate Column Totals
for (i = 0; i < rows; i++) {
int row_sum = 0; // Reset row sum for each new row
for (j = 0; j < cols; j++) {
row_sum += matrix[i][j]; // Accumulate row sum
col_sum[j] += matrix[i][j]; // Accumulate column total
}
printf("Sum of Row %d: %d\n", i + 1, row_sum);
}
// 2. Print Column Sums
printf("\n");
for (j = 0; j < cols; j++) {
printf("Sum of Column %d: %d\n", j + 1, col_sum[j]);
}
return 0;
}Code language: C++ (cpp)
Explanation:
An array col_sum is used to accumulate the totals for each column simultaneously with calculating the row sums.
- Row Sums: The
row_sumvariable is defined and reset to 0 inside the outer loop (which controls the rowi). This ensures a fresh calculation for every row. - Column Sums: The
col_sumarray has a size equal to the number of columns. The statementcol_sum[j] += matrix[i][j];adds the element to the correct column total regardless of the rowi.
Exercise 39: Add Two Matrices
Problem Statement: Write a C program to read two matrices, Matrix A and Matrix B, of the same dimension (e.g., 3×3), calculate their sum, and store the result in a third matrix, Matrix C (Matrix C = Matrix A + Matrix B).
Given:
int A[2][2] = {{1, 2}, {3, 4}};
int B[2][2] = {{5, 6}, {7, 8}};Code language: C++ (cpp)
Expected Output:
Matrix A + Matrix B (Matrix C):
6 8
10 12
+ Hint
- Matrix addition requires corresponding elements to be added:
C[i][j] = A[i][j] + B[i][j]. - You will need three 2D arrays and nested loops to iterate through the corresponding elements of Matrix A and Matrix B and store the result in Matrix C.
+ Show Solution
#include <stdio.h>
int main() {
int A[2][2] = {{1, 2}, {3, 4}};
int B[2][2] = {{5, 6}, {7, 8}};
int C[2][2]; // Resultant matrix
int rows = 2, cols = 2;
int i, j;
// 1. Perform addition
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}
// 2. Print the resultant matrix C
printf("Matrix A + Matrix B (Matrix C):\n");
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
printf("%d\t", C[i][j]); // Expected C: {{6, 8}, {10, 12}}
}
printf("\n");
}
return 0;
}Code language: C++ (cpp)
Explanation:
- Matrix addition is straightforward element-wise.
- The nested loops ensure that the same row index
iand column indexjare used across all three matrices (A, B, and C). - The statement
C[i][j] = A[i][j] + B[i][j];directly implements the mathematical definition of matrix addition for corresponding cells.
Exercise 40: Subtract Two Matrices
Problem Statement: Write a C program to read two matrices, Matrix A and Matrix B, of the same dimension, calculate their difference, and store the result in a third matrix, Matrix C (Matrix C = Matrix A – Matrix B).
Given:
int A[2][2] = {{10, 20}, {30, 40}};
int B[2][2] = {{1, 2}, {3, 4}};Code language: C++ (cpp)
Expected Output:
Matrix A - Matrix B (Matrix C):
9 18
27 36
+ Hint
- Similar to addition, matrix subtraction requires corresponding elements to be subtracted:
C[i][j] = A[i][j] - B[i][j]. - Use the same nested loop structure as matrix addition, simply changing the operator.
+ Show Solution
#include <stdio.h>
int main() {
int A[2][2] = {{10, 20}, {30, 40}};
int B[2][2] = {{1, 2}, {3, 4}};
int C[2][2]; // Resultant matrix
int rows = 2, cols = 2;
int i, j;
// 1. Perform subtraction
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
C[i][j] = A[i][j] - B[i][j];
}
}
// 2. Print the resultant matrix C
printf("Matrix A - Matrix B (Matrix C):\n");
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
printf("%d\t", C[i][j]); // Expected C: {{9, 18}, {27, 36}}
}
printf("\n");
}
return 0;
}Code language: C++ (cpp)
Explanation:
- The program iterates through both matrices using nested loops.
- The subtraction
C[i][j] = A[i][j] - B[i][j];is performed element-wise. - This simple structure applies because matrix subtraction, like addition, is only defined for matrices of identical dimensions.

Leave a Reply