Watch the full video on YouTube.
Hello aspiring developers! π¨βπ» So you're probably wondering how can you sort this variable mess, after maybe 10 or more added:
// Variables like this becomes messy.
string student1 = "John";
string student2 = "Michael";
string student3 = "Petra";
Here's how:
Just add the type and square brackets beside. Name it. Then put new and the type, then add its length inside these brackets.
// To solve this, you can make an array.
string[] students = new string[3];
And you can initialize this by adding each value based on index.
// To solve this, you can make an array.
string[] students = new string[3];
students[0] = "John";
students[1] = "Michael";
students[2] = "Petra";
Or, you can also initialize this in one go, by undoing the initialize values before. And remove the new, the type, and the length to not worry on how many values you will put inside.
Add a pair of curly braces, then put the values inside, each separated by a comma. Here you go! Much compact code using arrays. π
// To solve this, you can make an array.
string[] students = { "John", "Michael", "Petra" };
Calling a value in an Array
To call a value inside an array, we can use their index. Starting from 0 βtil the arrayβs length minus one.
Console.WriteLine("Student Name: " + students[students.Length - 1]);
You can also use other types aside from string.
Like int:
// You can also use other types aside from string.
int[] ages = new int[3];
ages[0] = 12;
ages[1] = 17;
ages[2] = 24;
And double:
double[] grades = new double[3];
grades[0] = 75.0;
grades[1] = 80.5;
grades[2] = 97.1;
Here's the final code you can view on GitHub Gist.
Thanks for reading! π
Check out my YouTube channel for more coding tutorials. Happy coding everyone! π§‘
Source(s):
Microsoft's documentation on C# Arrays
Top comments (0)