## C# program to find the largest and smallest numbers in an user given array:

In this post, we will learn how to find the *largest* and *smallest* numbers in an user given array. Our program will ask the user to enter the size of the array. It will then take the numbers as inputs from the user one by one. Finally, we will iterate through the array one more time to find the *largest* and *smallest*.

### C# program:

Below is the complete *C#* program:

```
using System;
public class Program
{
public static void Main()
{
//1
Console.WriteLine("Enter the size of the array :");
int size = int.Parse(Console.ReadLine());
//2
int[] arr = new int[size];
//3
for(int i =0 ; i<size; i++){
Console.WriteLine("Enter value for index "+i+" : ");
arr[i] = int.Parse(Console.ReadLine());
}
//4
int largest = arr[0];
int smallest = arr[0];
//5
for(int i=1; i<size; i++){
if(arr[i] > largest){
largest = arr[i];
}
if(arr[i] < smallest){
smallest = arr[i];
}
}
//6
Console.WriteLine("Smallest value : "+smallest+", and largest value : "+largest);
}
}
```

### Explanation:

*The commented numbers in the above program denote the step numbers below :*

- Ask the user to enter the size of the array. Read it and store it in the integer variable
*size*. - Create one new
*integer array**arr*to store the user input values. It is of size*size*. - Run one
*for loop*to read the values for the array. Ask the user to enter the value for each index of the array. Read it and store it in that index of the array. - Create two
*int*variables to hold the largest and smallest values in the array. Assign the first element of the array to both of these variables. We will compare all other elements of the array with the current value of these variables to find out the*largest*and*smallest*. - We are running one more
*for loop*to find the smallest and largest numbers in the array. We are comparing the current value of*smallest*and*largest*with all elements from index*1*to the*end*. If we find any element that is smaller than*smallest*, we assign it as*smallest*. Again, if we find any element that is greater than*greatest*, we assign it as*largest*. - Finally, we are printing the smallest and largest values of the array.

### Sample output:

```
Enter the size of the array :
5
Enter value for index 0 :
1
Enter value for index 1 :
10
Enter value for index 2 :
20
Enter value for index 3 :
30
Enter value for index 4 :
13
Smallest value : 1, and largest value : 30
```

### You might also like:

- How to compare two strings in C sharp
- How to build and run c sharp project from the terminal
- How to reverse a string in C sharp
- Check if a number is odd or even in C sharp
- C sharp program to check if a number is positive, negative or zero
- C# program to find the area of a circle
- C# program to find the largest of three numbers