Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Here is an example code in C# that will take user input and add it to an array using a loop, and then display the contents of the array through printing:

using System;

class Program {
    static void Main(string[] args) {
        // Initialize an array of size 5
        int[] arr = new int[5];

        // Loop through the array to take user input
        for (int i = 0; i < arr.Length; i++) {
            Console.Write("Enter a number: ");
            int input = Convert.ToInt32(Console.ReadLine());
            arr[i] = input;
        }

        // Display the contents of the array through printing
        Console.WriteLine("The array contains: ");
        for (int i = 0; i < arr.Length; i++) {
            Console.WriteLine(arr[i]);
        }
    }
}

Explanation:

  • We first initialize an array arr of size 5.
  • We use a for loop to loop through the array from index 0 to 4. Inside the loop, we prompt the user to enter a number and store it in the input variable. We then add the input value to the current index of the array arr[i].
  • After the loop is done, we use another for loop to loop through the array again from index 0 to 4. Inside the loop, we print out the value at each index of the array using Console.WriteLine(arr[i]).

Sample Output:

Enter a number: 10
Enter a number: 20
Enter a number: 30
Enter a number: 40
Enter a number: 50
The array contains:
10
20
30
40
50