I am trying to solve an exercise in C# as follows:
Write a program that generates 20 random integers between 0 and 9 and displays the count for each number. Use an array of ten integers, say counts, to store the counts for the number of 0s, 1s, ..., 9s.)
This is what i come up with which kind of work but i have a problem with the 0's counting 1 extra all the time.
using System.Collections.Generic;
using System.Text;
namespace ArrayExercises
{
class TaskFive
{
public static void FindNumberCount()
{
int c0=0,c1=02,c2=0,c3=0,c4=0,c5=0,c6=0,c7=0,c8=0,c9=0;
int[] arr = new int[20];
Random rand = new Random();
Console.WriteLine("Numbers generated ");
for (int i = 0; i < 19; i++)
{
arr[i] = rand.Next(0, 10);
Console.WriteLine(arr[i]);
}
foreach(int number in arr)
{
if (number == 0) { c0++; }
else if (number == 1) { c1++; }
else if (number == 2) { c2++; }
else if (number == 3) { c3++; }
else if (number == 4) { c4++; }
else if (number == 5) { c5++; }
else if (number == 6) { c6++; }
else if (number == 7) { c7++; }
else if (number == 8) { c8++; }
else if (number == 9) { c9++; }
}
Console.WriteLine
(
$"Number of 0's: {c0} \n" +
$"Number of 1's: {c1} \n" +
$"Number of 2's: {c2} \n" +
$"Number of 3's: {c3} \n" +
$"Number of 4's: {c4} \n" +
$"Number of 5's: {c5} \n" +
$"Number of 6's: {c6} \n" +
$"Number of 7's: {c7} \n" +
$"Number of 8's: {c8} \n" +
$"Number of 9's: {c9}"
);
}
}
}
Thanks in advance :)
Aucun commentaire:
Enregistrer un commentaire