Search code examples
c#consoleconsole-input

For or While loop to end table entry


I'm working on a square root table, with a start and end point. However, my points aren't correlating with my table. It's only using the numbers I put for my integers. I need it to use my start number I enter as my first number on the table and the end number as the last number of the table.

On line 24 when I replace the numbers with the words start and end, it gives me an error message. How do I fix this to use my data entry points?

int counter;
int square = 5;
const int maxValue = 15;
//create start and end points for the loop.
Console.WriteLine ("Start: ");
Console.ReadLine();
Console.WriteLine("End: ");
Console.ReadLine();

//Print the table headings
Console.WriteLine("Number  Square");
Console.WriteLine("-------------------");

//loop through the numbers 1 through 100
for (counter = 1; counter <= maxValue; counter++)
{
square = counter * counter;
Console.WriteLine("{0}   {1}",  counter, square); 

Solution

  • It seems the real question is how to use user input. You need to store the input string into some variable before you can use it with. To use the input string as a number you need to parse it, with eg int.Parse:

    var start=int.Parse(Console.ReadLine());
    

    Eg :

    Console.WriteLine ("Start: ");
    var start=int.Parse(Console.ReadLine());
    Console.WriteLine("End: ");
    var stop=int.Parse(Console.ReadLine());
    
    //loop through the numbers 1 through 100
    for (counter = start; counter <= stop; counter++)
    {
        square = counter * counter;
        Console.WriteLine("{0}   {1}",  counter, square); 
    }
    

    Parse will throw an error if the input can't be parsed. You can use int.TryParse to check whether the input is an actual number :

    int start=0,stop=0;
    while(!int.TryParse(Console.ReadLine(),out start))
    {
        Console.WriteLine("Incorrect value, please type a number");
    }