4

I need to display the squares of the numbers 1-10 using a for loop. This is what I have so far. I don't know what I am missing. Any help would be much appreciated.

        for (int counter = 1; counter <= 10; counter++)
        {                          
            Console.WriteLine(counter * counter);                
        }
        Console.ReadLine();
Cœur
  • 37,241
  • 25
  • 195
  • 267
  • The code is perfectly fine. It is producing the output as expected. Can you put a BreakPoint and see if it is getting executed? – Tilak Nov 27 '12 at 05:46
  • One more question, how would I do 1 = sqaure and then 2 = square and so on – Vinnie Centofanti Nov 27 '12 at 05:53
  • `Console.WriteLine("Number :{0}, Square : {1}", counter,counter * counter);` – Tilak Nov 27 '12 at 05:59
  • or else `Console.WriteLine(counter = (counter * counter));` . go with some tutorials http://msdn.microsoft.com/en-us/library/aa288436(v=vs.71).aspx – Mr_Green Nov 27 '12 at 06:00

5 Answers5

4

Have a look at your code

for (int counter = 1; counter <= 10; counter++)
{
   if ((counter * counter) == 0) // this will never evaluate to true
   {
       Console.WriteLine(counter);
   }
}

Since you are starting off with 1 your if condition is never true, so nothing would be printed

you just need to use counter * counter printed in your for loop

or you can use Math.Pow(counter, 2.0) to get your squares

V4Vendetta
  • 37,194
  • 9
  • 78
  • 82
3

Try this

    for (int counter = 1; counter <= 10; counter++)
    {          
            Console.WriteLine(counter*counter);
    }
Tilak
  • 30,108
  • 19
  • 83
  • 131
2

For an integer counter having any value other than 0, counter * counter will never evaluate to 0.

canon
  • 40,609
  • 10
  • 73
  • 97
1

if ((counter * counter) == 0) This will not satisfy for any value..Try if ((counter * counter) != 0) ..Try this..

Subburaj
  • 5,114
  • 10
  • 44
  • 87
0

Since you start with 1, that counter * counter can not be 0. So, having that in mind, here's the whole code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication21
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 1; i <= 10; i++)
                Console.WriteLine(i * i);
        }
    }
}

I am sure that this was helpful.