Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

unassigned variable

Status
Not open for further replies.

akaballa

Programmer
Feb 2, 2007
8
CA
Hi,

Im new at C# programming....just practicing some programming concepts. I was working on a array program...when I encountered this error message: "Use of unassgined local variable 'avg'". I had already declared this variable previously. So Im not sure how to fix this error.

using System;

namespace ConsoleApplication1
{
class Array2
{
public static void Main()
{
int[] nums = new int[5];

nums[0] = 69;
nums[1] = 95;
nums[2] = 76;
nums[3] = 85;
nums[4] = 100;

int avg;

for (int i = 0; i < 5; i++)
{
avg = nums;
}

avg = avg / 10;//here is where the problem occurs

Console.WriteLine("Average: {0}", avg);
}
}
}
 
in your example avg will only ever equal 10 (100/10). set a break point on [tt]int[] nums[/tt] and step through your code to make sure your looping through the for loop.

If you want to calculate the average of the array change your loop to
Code:
int[] nums = new int[] {96, 59, 76, 85, 100 };
int avg = 0;
int cnt = nums.Length;
for(int i = 0; i < cnt; i++)
{
   avg +=nums[i];
}
Console.WriteLine("Average: {0}", (avg / cnt));
Console.WriteLine("Press any key to exit.");
Console.ReadKey();

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Try this:

Code:
using System;

namespace ConsoleApplication1
{
    class Array2
    {
        public static void Main()
        {
            int[] nums = new int[5];

            nums[0] = 69;
            nums[1] = 95;
            nums[2] = 76;
            nums[3] = 85;
            nums[4] = 100;

            int avg = 0;

            for (int i = 0; i < 5; i++)
            {
                avg = nums[i];
            }

            avg = avg / 10;//here is where the problem occurs

            Console.WriteLine("Average: {0}", avg);
        }
    }
}

Sunil
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top