C Program to Find Missing Numbers in Array

This C program finds missing numbers in an array. It takes an array as input and prints the numbers that are missing from the array. The program uses a simple nested loop approach to check each number from 1 to n and compares it with the elements of the array.

Problem statement

Given an array of integers, find and print the missing numbers in the range from 1 to n, where n is the size of the array plus 1.

C Program to Find Missing Numbers in Array

#include <stdio.h>

void findMissingNumbers(int arr[], int n) {
    int i, j, found;

    printf("Missing numbers: ");

    // Check each number from 1 to n
    for (i = 1; i <= n; i++) {
        found = 0;

        // Check if the number is present in the array
        for (j = 0; j < n; j++) {
            if (arr[j] == i) {
                found = 1;
                break;
            }
        }

        // If the number is not found, print it
        if (found == 0) {
            printf("%d ", i);
        }
    }

    printf("\n");
}

int main() {
    int arr[] = {4, 2, 1, 6, 5};
    int size = sizeof(arr) / sizeof(arr[0]);

    printf("Array: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    findMissingNumbers(arr, size + 1);

    return 0;
}

How it works?

  1. The program initializes an array arr and its size size.
  2. The contents of the array are printed.
  3. The findMissingNumbers function is called with the array and its size incremented by 1.
  4. In the findMissingNumbers function, a nested loop is used to iterate through numbers from 1 to n.
  5. For each number, it checks if it is present in the array by comparing it with each element in the array.
  6. If a number is not found in the array, it is considered missing and printed.
  7. After checking all the numbers, the function returns to the main function.
  8. The program terminates.

Input/Output

C Program to Find Missing Numbers in Array

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C program calculates the volume and surface area of a sphere using its radius. A sphere is a three-dimensional...
This C program converts a Roman numeral to a decimal number. Roman numerals are a system of numerical notation used...
This C program calculates the value of sin(x) using the Taylor series expansion. The Taylor series expansion is a mathematical...