How do I store my numbers in an array?
In my code, I am trying to generate 5 numbers. If any of the numbers are 4, I want to store that 4 into an array. I am currently in trouble and my code will not store 4 in an array.
static void Main()
{
Random rand = new Random();
int total = 0, randInt;
Console.WriteLine("The computer is now rolling their dice...");
int[] fours = new int[total];
for (int i = 0; i < 5; i++)
{
randInt = rand.Next(10);
Console.WriteLine("The computer rolls a {0:F0}", randInt);
if (randInt == 4)
{
total +=fours[i]; //Here I am trying to store the 4 into the array of 'fours'.
}
}
Console.WriteLine(total); //This currently prints to 0, regardless of any 4 the random number generator has generated. I want this to print out how many 4 I have rolled.
Console.ReadLine();
}
+3
source to share
1 answer
It:
total +=fours[i]
Will try to increment total
with the int
one found in the index of i
your array (which will currently be 0 as int defaults to 0).
It:
fours[i] = 4;
How do I assign 4 to the i-th index in your array.
Learn about how the assignment operator works in C #
The = operator is called the simple assignment operator. It assigns the value of the right-hand operand to the variable, property, or indexer element specified by the left-hand operand.
+3
source to share