I've just written some code in an online compiler, and since I'm very new to C#, I wanted to ask what could be improved about the code.
The task of the program is simply to add up the numbers the user entered before and then calculate the average.
public static void Main()
{
int input;
int sum = 0;
bool error = false;
int[] numbers = new int[5];
for(int i = 0; i < numbers.Length; i++)
{
if (!error)
Console.WriteLine("Please write a number:");
if(Int32.TryParse(Console.ReadLine(), out input))
{
numbers[i] = input;
sum += numbers[i];
error = false;
}
else
{
Console.WriteLine("An error occured, please try again:");
error = true;
i--;
continue;
}
}
Console.WriteLine("");
Console.WriteLine("Your typed in values:");
for(int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
Console.WriteLine("");
Console.WriteLine("The result of your numbers:");
Console.WriteLine(sum);
Console.WriteLine("The average of your numbers:");
Console.WriteLine((double)sum / (double)numbers.Length);
}
The code works fine, but maybe I could do some things more effectively.
Would be glad to get some help :)
Just to sum things up here is the console-output:
Please write a number:
> 4
Please write a number:
> 2
Please write a number:
> a
An error occured, please try again:
> 6
Please write a number:
> 4
Please write a number:
> 8
Your typed in values:
4
2
6
4
8
The sum of your numbers:
24
The average of your numbers:
4.8
('>' = User input)