Group
C# Arrays, Structures and Strings
Objective
1. Create an array to store 10 integer numbers.
2. Ask the user to input 10 integers (within the range of -1000 to 1000).
3. Sort the array of integers in ascending order.
4. Display the sorted integers in the output.
Write a C# program to ask the user for 10 integer numbers (from -1000 to 1000), sort them and display them sorted.
Example C# Exercise
Show C# Code
using System;
class Program
{
static void Main()
{
// Declare an array to store 10 integers
int[] numbers = new int[10];
// Ask the user to input 10 integers
Console.WriteLine("Please enter 10 integers (between -1000 and 1000):");
// Collect the integers from the user
for (int i = 0; i < numbers.Length; i++)
{
Console.Write($"Enter number {i + 1}: ");
numbers[i] = int.Parse(Console.ReadLine());
// Validate that the number is within the range
while (numbers[i] < -1000 || numbers[i] > 1000)
{
Console.WriteLine("Number must be between -1000 and 1000.");
Console.Write($"Enter number {i + 1} again: ");
numbers[i] = int.Parse(Console.ReadLine());
}
}
// Sort the array in ascending order
Array.Sort(numbers);
// Display the sorted numbers
Console.WriteLine("\nThe sorted numbers are:");
foreach (int num in numbers)
{
Console.Write(num + " ");
}
}
}
Output
Please enter 10 integers (between -1000 and 1000):
Enter number 1: 25
Enter number 2: -100
Enter number 3: 450
Enter number 4: 999
Enter number 5: 10
Enter number 6: -999
Enter number 7: 0
Enter number 8: 500
Enter number 9: 12
Enter number 10: 0
The sorted numbers are:
-999 -100 0 0 10 12 25 450 500 999