G
Gen
Hi - I'm a c# student, as a small class exercise we were asked to write a
program that uses an Average function using the params keyword. My
problem was with the loop, I could only get the Do loop to work. When
trying the for and foreach I got errors (explained below)
for (int i = 0; i < list.Length; i++)
{
x = x + list;
}
but when i put x = x/list.Length out here it said something like I couldn't
use x here.
The Do loop below worked. But can someone show me how to do this using for
or foreach? I just want to know why I couldn't get it to work.
public static void Average(params int[] list)
{
int x = 0;
int i = 0;
do
{
x = x + list[i++];
}
while(i < list.Length);
x = x / list.Length;
Console.WriteLine(x);
}
static void Main()
{
Average(2, 5, 8);
}
program that uses an Average function using the params keyword. My
problem was with the loop, I could only get the Do loop to work. When
trying the for and foreach I got errors (explained below)
for (int i = 0; i < list.Length; i++)
{
x = x + list;
}
but when i put x = x/list.Length out here it said something like I couldn't
use x here.
The Do loop below worked. But can someone show me how to do this using for
or foreach? I just want to know why I couldn't get it to work.
public static void Average(params int[] list)
{
int x = 0;
int i = 0;
do
{
x = x + list[i++];
}
while(i < list.Length);
x = x / list.Length;
Console.WriteLine(x);
}
static void Main()
{
Average(2, 5, 8);
}