C Exercises: Find the smallest missing element from a sorted array
C Array: Exercise-42 with Solution
Write a program in C to find the smallest missing element in a sorted array.
The problem requires writing a program to find the smallest missing element in a sorted array. The program identifies the first gap in the sequence, where the difference between consecutive elements is greater than one, indicating the missing number.
Visual Presentation:
Sample Solution:
C Code:
#include <stdio.h>
// Function to find the smallest missing element in a sorted array
int MissingSmallElement(int arr1[], int low_index, int high_index) {
// Check if low_index is greater than high_index, indicating the end of the search
if (low_index > high_index)
return low_index; // Return low_index as it represents the smallest missing element
// Calculate the middle index between low_index and high_index
int mid_index = low_index + (high_index - low_index) / 2;
// If the element at mid_index is equal to mid_index, the mismatch lies on the right half
if (arr1[mid_index] == mid_index)
return MissingSmallElement(arr1, mid_index + 1, high_index);
else // If not, the mismatch lies on the left half
return MissingSmallElement(arr1, low_index, mid_index - 1);
}
int main() {
int arr1[] = { 0, 1, 3, 4, 5, 6, 7, 9 };
int ctr = sizeof(arr1) / sizeof(arr1[0]);
int i;
// Print the original array
printf("The given array is : ");
for(i = 0; i < ctr; i++) {
printf("%d ", arr1[i]);
}
printf("\n");
// Define the low_index and high_index for the array
int low_index = 0, high_index = ctr - 1;
// Find the missing smallest element in the array
printf("The missing smallest element is: %d",
MissingSmallElement(arr1, low_index, high_index));
return 0;
}
Sample Output:
The given array is : 0 1 3 4 5 6 7 9 The missing smallest element is: 2
Flowchart:
C Programming Code Editor:
Previous: Write a program in C to find the Floor and Ceil of the number 0 to 10 from a sorted array
Next: Write a program in C to find the smallest missing element from a sorted array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/c-programming-exercises/array/c-array-exercise-42.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics