1

I am still quite new to C sharp and right now I am trying to find out how to fill empty array using for loop. Program should ask how many numbers we want to add then it will ask for them with for loop. After that, program should write them all in console. I'm kinda stuck in the part where you need to join numbers to empty array. Thank you for possible help.

using System;

namespace ConsoleApp43
{
    class Program
    {
        static void Main(string[] args)
        {

        int[] numbers = new int[] { };
        int order = 1;
                   
       Console.Write("How many numbers do you want to enter?: ");
       int sum = Convert.ToInt32(Console.ReadLine());

      for (int i = 0; i<sum; i++)
        {    
            Console.Write("Enter {0}. number: ", order);
            int number = Convert.ToInt32(Console.ReadLine());
            number =+ numbers[i];      
        }

        Console.WriteLine(numbers);
    }
}

}

Rahul Sharma
  • 7,768
  • 2
  • 28
  • 54
Maxek
  • 13
  • 3
  • Also see [Add new item in existing array in c#.net](https://stackoverflow.com/questions/249452/add-new-item-in-existing-array-in-c-net) – gunr2171 Apr 01 '22 at 16:08

2 Answers2

0

Something like this should do it

using System;

class Program
{
    public static void Main() 
    {
        int[] nums;
        int len;
        Console.WriteLine("Enter the number of elements in Array");
        len = Convert.ToInt32(Console.ReadLine());
        nums = new int[len];
        for ( int i = 0; i < len; i++ ) {
            nums[i] = Convert.ToInt32(Console.ReadLine());
        }
        foreach ( int i in nums ) {
            Console.WriteLine(i);//This is assuming you want to print elements of the array, not it's type.
        }    
    }
}
         
    
Hiten Tandon
  • 64
  • 1
  • 5
0

You can use a List insted:

 var numbers = new List<int>();
 int order = 1;

 Console.Write("How many numbers do you want to enter?: ");
 int sum = Convert.ToInt32(Console.ReadLine());

 for (int i = 0; i < sum; i++)
 {
     Console.Write("Enter {0}. number: ", order);
     int number = Convert.ToInt32(Console.ReadLine());
     numbers.Add(number);
 }

 Console.WriteLine("You entered:");
 Console.WriteLine(string.Join(',', numbers));

it will write:

How many numbers do you want to enter?: 2
Enter 1. number: 1
Enter 1. number: 2
You entered:
1,2