Tuesday, July 28, 2009

How to refresh variables in C# or can I update them??

well I'm a beginner I have a problem with my C# code





int a = 0, b = a * a, c = a * a * a;


Console.WriteLine("Number\tSquare\tCube"...


while (a %26lt; 11)


{


Console.WriteLine(a + "\t" + b + "\t" + c);


a++;


}


my problem is the value of b and c doesn't change at all.... is there any way to refresh my variables

How to refresh variables in C# or can I update them??
Your issue is with the "scope" of the variable b and c and are being initialized only but are later not changed by the change in a within the loop.





You might also be interested in the Math namespace.





int a = 0;


Console.WriteLine("Number\tSqu...


while (a %26lt; 11)


{


Console.WriteLine(a + "\t" + Math.Pow(a,2) + "\t" + Math.Pow(a,3));


a++;


}
Reply:When you initialize b, you are setting it to a * a, which means you are setting it to 0 * 0. Same with c. Obviously, this is going to be 0 and it's not going to change. c# does not support lambdas (at least not that way) - int variable is a value type.





If you want to change the value of b and c on every iteration, you need to set them inside the while loop:





b = 0, c = 0;


while (a %26lt; 11)


{


b = a * a;


c = a * a * a;


Console.WriteLine(a + "\t" + b + "\t" + c);


a++;


}


No comments:

Post a Comment