C# program to find missing number in integer array of 1 to 20
To find the missing number in an integer array ranging from 1 to 20 using C#, you can iterate through the array and check which number is missing. Here's an example program that finds the missing number:
using System;
public class Program {
public static void Main(string[] args) {
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
int missingNumber = FindMissingNumber(numbers);
Console.WriteLine("The missing number is: " + missingNumber);
}
public static int FindMissingNumber(int[] nums) {
int n = 20;
int expectedSum = (n * (n + 1)) / 2;
int actualSum = 0;
foreach (int num in nums) {
actualSum += num;
}
return expectedSum - actualSum;
}
}
In this program, we have an array of integers called numbers with values ranging from 1 to 20, except for one missing number. We use the FindMissingNumber method to find the missing number. The method calculates the expected sum of numbers from 1 to 20 using the formula (n * (n + 1)) / 2, where n is the maximum number in the range. Then, it calculates the actual sum of the numbers in the array. The missing number can be found by subtracting the actual sum from the expected sum.
The program outputs the missing number:
The missing number is: X
Replace X with the actual missing number in the array.
For example, if the array is { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20 }, the program will output:
The missing number is: 15
In this case, the missing number in the array is 15.