0

How can I removed the limit in declaring array?

I'm trying to let the user input for the length of the array. Then the user will input the elements 1 by 1. https://code.sololearn.com/cq68XkOX66AR/?ref=app

25th Nov 2022, 3:00 AM
Mozzie
Mozzie - avatar
5 odpowiedzi
+ 2
What do you mean by removing the limit? Arrays have fixed size that cannot change. If you need to adjust the size dynamically, you should use a List<int> instead.
25th Nov 2022, 3:29 AM
Tibor Santa
Tibor Santa - avatar
+ 2
I want the user to set the size of the array. I see thank you.
25th Nov 2022, 3:35 AM
Mozzie
Mozzie - avatar
+ 2
you get user input and you save it at elemNum. Why not use that? int[] arr = new int[elemNum];
25th Nov 2022, 5:03 AM
Giannis
Giannis - avatar
+ 2
How could I miss that. HAHAHA thanks
25th Nov 2022, 5:23 AM
Mozzie
Mozzie - avatar
+ 2
or use List and eliminate the problem of knowing how many items are going to be entered beforehand. using System; using System.Collections.Generic; namespace Program { class Test { public static void Main() { List<int> li1 = new List<int>(); while(true) { string i = Console.ReadLine(); if(i == null) break; else{ try{ li1.Add(int.Parse(i));} catch{ //ignore invalid entries continue;} } } li1.ForEach(i => Console.Write("{0}, ", i));; } } }
25th Nov 2022, 6:22 AM
Bob_Li
Bob_Li - avatar