Write a program that reads the number N of integers, then read N consecutive integers starting from 0 with one integer missing (integers could be entered in any random manner) and finds the missing value.
Example:
- Enter the number of elements: 9
- Enter the number of one line: 1 5 0 9 2 6 3 8 7
- Missing element 4
Hint: \(\sum_{i=0}^N=\frac{N\times(N+1)}{2}\)
Difficulty level
This exercise is mostly suitable for students
#include <stdio.h>
#define NBMAX 100
void main()
{
int N, sum=0 , i, nb;
do{
printf("Enter the number of elements: ");
scanf("%d", &N);
}while(N<=0 || N>NBMAX);
printf("Enter the number of one line: ");
i=1;
while(i<=N)
{
scanf("%d", &nb);
sum+=nb;
i++;
}
/*the sum from 0...N is(N*(N+1))/2*/
printf("\nMissing element %d.\n",((N*(N+1))/2)-sum);
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Sorting an array by minimum selection