C# Programming
03-02-2013, 09:40 PM
I'm trying to create a program that displays a table of all the even numbers within a range given by the user but im having some trouble making it work. the range has to be between 1 and 120. I would also like to incorporate the tryparse method. here is what I have so far:
using System;
public class Range
{
public static void Main(string[] args)
{
int[] range;
string firstNumber;
Console.Write("What is the initial number of the range: ");
firstNumber = Console.ReadLine();
Console.Write("What is the last number of the range: ");
string lastNumber;
lastNumber = Console.ReadLine();
int totalNumber;
int firstNum = Convert.ToInt32(firstNumber);
int lastNum = Convert.ToInt32(lastNumber);
if (firstNum < 1)
{
Console.WriteLine("Error: the firstNumber can't be less than 1.");
}
else if (lastNum > 120)
{
Console.WriteLine("Error: the lastNumber can't be higher than 120.");
}
else if (firstNum >= lastNum)
{
Console.WriteLine("Error: the first number can't be higher than the last number.");
}
totalNumber = lastNum - firstNum;
range = new int[totalNumber + 1];
int tally = 0;
for (int i = 0; i < totalNumber; i++)
{
range[i] = i + 1;
if (range[i] % 2 == 0)
{
Console.Write(range[i] + " ");
}
tally++;
if (tally > 10)
{
Console.WriteLine();
tally = 0;
}
}
Console.Write("\nPress any key to exit program: ");
Console.ReadKey();
}
}
using System;
public class Range
{
public static void Main(string[] args)
{
int[] range;
string firstNumber;
Console.Write("What is the initial number of the range: ");
firstNumber = Console.ReadLine();
Console.Write("What is the last number of the range: ");
string lastNumber;
lastNumber = Console.ReadLine();
int totalNumber;
int firstNum = Convert.ToInt32(firstNumber);
int lastNum = Convert.ToInt32(lastNumber);
if (firstNum < 1)
{
Console.WriteLine("Error: the firstNumber can't be less than 1.");
}
else if (lastNum > 120)
{
Console.WriteLine("Error: the lastNumber can't be higher than 120.");
}
else if (firstNum >= lastNum)
{
Console.WriteLine("Error: the first number can't be higher than the last number.");
}
totalNumber = lastNum - firstNum;
range = new int[totalNumber + 1];
int tally = 0;
for (int i = 0; i < totalNumber; i++)
{
range[i] = i + 1;
if (range[i] % 2 == 0)
{
Console.Write(range[i] + " ");
}
tally++;
if (tally > 10)
{
Console.WriteLine();
tally = 0;
}
}
Console.Write("\nPress any key to exit program: ");
Console.ReadKey();
}
}