I want to make a list of numbers and their squares in C# using a for loop.
Right now I have:
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
int counter;
int square = 1;
const int maxValue = 10;
Console.WriteLine("Number Square");
Console.WriteLine("-------------------");
{
for (counter = 1; counter <= maxValue; counter++)
square = counter ^ 2;
Console.WriteLine("{0} {1}", counter, square);
}
}
}
}
But my output is just an 11 and an 8.
When I put "square = counter ^ 2" right under the variable declarations, I end up with a column of numbers 1-10 but the second row is just a bunch of threes, if they are set to 0 they are twos. It also gives me an error to declare the counter variable if I don't set it to something.
When I put the equation in the position it is now, it asks for the square variable to be declared as something(in here it is at 1).
Also I am a beginner I haven't learned about classes yet, so I'd prefer any corrections not to include them.
EDIT: fixed, gosh I didn't make this mistake last time, yeah I need more practice. Sorry
The placement of braces is important:
Console.WriteLine("Number Square");
Console.WriteLine("-------------------");
for (counter = 1; counter <= maxValue; counter++)
{
square = counter * counter;
Console.WriteLine("{0} {1}", counter, square);
}
Note: It's good practice to always use enclosing braces for for
loops and if
statements precisely for this reason.
Also note that ^
is not 'to the power of' but exclusive OR