So I am currently pretty confused (keep in mind im new to coding). I am currently trying to create a program which creates allows the user to input the amount of numbers they would like to enter in the array (it then creates an array based on that length), asks the user to input the numbers into their desired position. My code currently looks like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Arrays
{
class Program
{
static void Main(string[] args)
{
//Variables
int[] array1 = new int[0];
int TotalArray, position, Number;
//Main Program
Console.WriteLine("Hello, welcome to creating your own array!");
Console.WriteLine("How many numbers do you wish to add to the array?: ");
TotalArray = int.Parse(Console.ReadLine());
Console.ReadKey();
{
Console.WriteLine("What position would you like to add your number to?: ");
position = int.Parse(Console.ReadLine());
if (position < TotalArray)
{
Console.WriteLine("What number would you like to add to position " + position);
Number = int.Parse(Console.ReadLine());
array1[position] = Number;
Console.WriteLine("Testing: " + array1[position]);
Console.ReadKey();
}
else
{
Console.WriteLine("Error! You entered your position higher than your total array!");
}
}
}
}
}
However, I do not understand how to create an array length based on the users input. I have to tried to do this:
Console.WriteLine("Hello, welcome to creating your own array!");
Console.WriteLine("How many numbers do you wish to add to the array?: ");
TotalArray = int.Parse(Console.ReadLine());
int i = Convert.ToInt32(TotalArray);
int[] array1 = new int[i];
But get this error:
A local variable or function named 'array1' is already defined in this scope
I don't really understand what this piece of code does:
int i = Convert.ToInt32(TotalArray);
int[] array1 = new int[i];
However, I saw it mentioned on stackoverflow and thought id try an implement it. I kinda understand the 2nd line but don't really get the whole converting thing.
Any help would greatly be appreciated!
array1. Just create a new array and assign it to the existing reference:array1 = new int[i];Convert.ToInt32(TotalArray);means "take this string called TotalArray, and try to convert the text in that string into an integer." If the string is"13", that'll return integer 13. If the text is "my cat's breath smells like Fred Flintstone", it'll throw an exception. However,TotalArrayis already an integer. You parsed a string from the user on the previous line. So just createnew int[TotalArray], and omitientirely.