Ask Your Question
3

How can user input be added to an array using a loop in C# and then displayed through printing?

asked 2022-05-06 11:00:00 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-09-08 02:00:00 +0000

devzero gravatar image

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
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-05-06 11:00:00 +0000

Seen: 15 times

Last updated: Sep 08 '22