Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing User Input Integers in an Array

Tags:

c#

I am trying to ask the user to input 10 numbers. After receiving the numbers, I am storing them in an array followed by printing the array. I came up with the following code to do the task but it is not printing the array.

Also feel that I may have rattled on way too much code for a simple task. Do note that I am very new to c# thus not familiar with advanced stuff or possibly even most of basic stuff. Even the "convert.toInt32", I adopted from reading around and not taught in class yet.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace test_Array
{
    class Program
    {
        static void Main(string[] args)
        {
            int a;
            int b;
            int c;
            int d;
            int e;
            int f;
            int g;
            int h;
            int i;
            int j; 

            Console.WriteLine("Please input 10 numbers. Press 'ENTER' after each number.");
            a = Convert.ToInt32(Console.ReadLine());
            b = Convert.ToInt32(Console.ReadLine());
            c = Convert.ToInt32(Console.ReadLine());
            d = Convert.ToInt32(Console.ReadLine());
            e = Convert.ToInt32(Console.ReadLine());
            f = Convert.ToInt32(Console.ReadLine());
            g = Convert.ToInt32(Console.ReadLine());
            h = Convert.ToInt32(Console.ReadLine());
            i = Convert.ToInt32(Console.ReadLine());
            j = Convert.ToInt32(Console.ReadLine());

            int[] newArray = {a,b,c,d,e,f,g,h,i,j};

            Console.WriteLine(newArray);

            Console.ReadLine();
        }
    }
}
like image 395
kar Avatar asked Dec 20 '22 23:12

kar


1 Answers

use a for loop.

int[] newArray = new int[10];
for (int i = 0; i < newArray.Length; i++)
{
    newArray[i] = Convert.ToInt32(Console.ReadLine());
}

You can use the same loop to display as well:

for (int i = 0; i < newArray.Length; i++)
{
    Console.WriteLine(newArray[i]);
}
like image 111
user2711965 Avatar answered Jan 01 '23 21:01

user2711965