Visual Studio keeps saying Use of unassigned variable
for iVal
and iNumber
. Can anyone tell me where I'm going wrong?
This is designed to be a code to ask the user to keep entering integers and adding them up until the user wants to stop. The sum of the integers is then displayed on the console.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AddFive
{
class Program
{
static void Main(string[] args)
{
int iNumber;
int iVal;
int iTotal = 0;
while (iVal > 0)
{
Console.WriteLine("Enter number " + iNumber);
iVal = Convert.ToInt32(Console.ReadLine());
iTotal = iTotal + iVal;
}
if (iNumber <= 0)
{
Console.WriteLine("Total = " + iTotal);
iVal = Convert.ToInt32(Console.ReadLine());
iTotal = iTotal + iVal;
}
Console.WriteLine("Total = " + iTotal);
Console.WriteLine();
Console.WriteLine("Press any key to close");
Console.ReadKey();
}
}
}
Assign values to those variables. You need to assign values to local variables before using them
int iNumber = 0;
int iVal = 0;
when you wrote while (iVal > 0)
, the value of iVal
has not been set
You can get away with that only with instance/class variable, as they are initialized to default value
public class Program
{
int i; //this was not implicitly initialized to zero (0)
public Program()
{
int j; //need to initialize this before use
Console.Write(j); //this throws "Use of unassigned variable" error
Console.Write(i); //this prints 0, the default value
}
}
Visual Studio is correct, you're trying to reference an uninitialized variable.
Try this:
int iNumber = 0;
int iVal = 0;
This way, your are initializing the variables to an initial value of 0. The original problem occurs on these lines:
while (iVal > 0)
and
if (iNumber <= 0)
In which you try to access the variables before giving them a value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With