Cant use the value out of the while loop

Cameron Ganesh

I want to validate if they enter numbers and then after that validate if the number is between 20 - 50 and then calculate the sum of all positive numbers before that.

int i, sum = 0;

var valid = false;
while (!valid)
{
    Console.ForegroundColor = ConsoleColor.Green;
    Console.WriteLine("Please enter a number between 20 and 50(50 is included)");
    Console.WriteLine("Only Numbers will be accepted");
    Console.ForegroundColor = ConsoleColor.White;
    Console.WriteLine("---------------------");
    Console.ForegroundColor = ConsoleColor.Yellow;

    var val = Console.ReadLine();
    valid = !string.IsNullOrWhiteSpace(val) &&
        val.All(c => c >= '0' && c <= '9');
    Console.WriteLine(val + " is what you entered");
}

Int16 num = int.Parse(val);
if (num > 20 && num <= 50)
{
    for (i = 0; i <= num; i++)
    {
        sum = sum + i;
    }
    Console.ForegroundColor = ConsoleColor.White;
    Console.WriteLine("---------------------");

    Console.ForegroundColor = ConsoleColor.Cyan;
    Console.WriteLine("Sum of all numbers before "+ Convert.ToString(num) + " is " + Convert.ToString(sum));

    Console.ForegroundColor = ConsoleColor.White;
    Console.WriteLine("---------------------");
    Console.ForegroundColor = ConsoleColor.Green;
}
else
{

    Console.ForegroundColor = ConsoleColor.White;
    Console.WriteLine("---------------------");

    Console.ForegroundColor = ConsoleColor.Red;
    Console.WriteLine("Number is not within the limits of 20-50!!!");

    Console.ForegroundColor = ConsoleColor.White;
    Console.WriteLine("---------------------");
    Console.ForegroundColor = ConsoleColor.Green;
}
Foxenstein

First: Have a look at this : https://en.wikipedia.org/wiki/Gauss_sum for the summation.

Second: The code:

static void Main(string[] args)
        {
            var valid = false;

            while (!valid)
            {
                var line = Console.ReadLine();

                if(Int16.TryParse(line, out var numericValue))
                {
                    if(numericValue >= 20 && numericValue <= 50)
                    {
                        int sum = Calculate(numericValue);
                        valid = true;
                    }
                }
                else
                {
                    // It was not a number or outsinde the range of Int16
                }
            }
        }

        private static int Calculate(int num)
        {
            return (num * (num + 1) / 2);
        }

Int16.TryParse checks softly wether the value from Console.ReadLine() is a numeric in the range of Int16 or not. I use the Gauss Sum in Calculate() for the summation.

Also have a look at class and object variables.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related