C Codes

Missing Array Intermediates – C code

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;
}

3 thoughts on “Missing Array Intermediates – C code

  1. 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?

    Liked by 1 person

    1. 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.. 🙂

      Like

Let me Know What you Think!