Hi Frank,
Thanks. I couldn't remember exactly what I had done, and now I can't seem
to recreate what I did wrong. All I remember is I had the "x = x /
list.Length;" on the outside of a " { " and it gave me some sort of error
about the "x" not being allowed there. I still don't understand why in the
foreach loop that the line after the x += i; doesn't execute until the
iteration is done.
With your help I figured out the for loop as well, but still not sure why
division runs after the loop.
public static void Average(params int[] list)
{
int x = 0;
for (int i = 0; i < list.Length; i++)
x += list[i];
x /= list.Length;
Console.WriteLine(x);
}
[quoted text, click to view] "news.microsoft.com" <fe@[nospam]frankeller.de> wrote in message
news:ukWOp4$yFHA.3188@TK2MSFTNGP14.phx.gbl...
> Hi Gen,
>
> I agree with Jon. The foreach-loop works for sure ... this here works for
> me:
>
> public static void Average( params int[] list ) {
>
> int x = 0;
>
> foreach ( int i in list )
> x += i;
>
> x = x / list.Length;
>
> Console.WriteLine( x );
> }
>
> static void Main() {
>
> Average( 2, 5, 8 );
>
> }
>
> Regards,
>
> Frank Eller
>
>
> "Gen" <wishing2b@microsoft.com> schrieb im Newsbeitrag
> news:OYlciD9yFHA.2792@tk2msftngp13.phx.gbl...
>> 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[i];
>> }
>> 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);
>> }
>>
>
>