Problem: Printing the missing array intermediates
As a input, collect a sorted array of integer elements from the user. The task is to print the intermediate missing elements.
Example: If the user enters the array elements as: {1, 4, 7, 9, 10, 11, 12, 15}
Then, output has to be: 2, 3, 5, 6, 8, 13, 14
(Merging both input and output should result in all the numbers from 1 to n)
The code below gives the basic C implementation.
#include<stdio.h> int main() { int a[100]; int n; int i; int j; printf("Enter the number of array elements\n"); scanf("%d", &n); printf("Enter input elements as conditioned\n"); for (i=0;i<n;i++) scanf("%d", &a[i]); int src; int dest; for (i = 0; i<n-1; i++) { src = a[i]; dest = a[i+1]; for(j = src+1; j< dest; j++) printf("%d\t",j); } return 0; }
Does this code hold true when the users start with a value other than 1?
What if they they begin with, say 5? The code looks like it would print the values from 5 to the last (src = a[i] i.e., the first number). Since, the requirement being “Merging both input and output should result in all the numbers from 1 to n”, may be we can tweak the for loop to:
int src = 0;
int dest = a[0];
for (i = 0; i<n-1; i++)
{
for(j = src+1; j<= dest; j++)
printf("%d\t",j);
if(i<n-2)
{
src = a[i];
dest = a[i+1];
}
}
That would print the numbers from 1 to n, regardless of the starting number. Thoughts?
LikeLiked by 1 person
True. You are right. That case has to be added explicitly.
The code only gives and works for minimal base condition. The corner cases have to be added. 🙂
Thank you for sharing.. 🙂
LikeLike
I guess, I missed an “equal to” at the “if” statement – should have been “if ( i <= n-2 )"… My bad…
LikeLiked by 1 person