Home > Net >  Declaring a variable in a loop and using it outside?
Declaring a variable in a loop and using it outside?

Time:03-19

I'm very new to c# and am trying to run this bit of code. I'm trying to make it so the question "How many miles were you able to travel in week {number}?" is repeated 4 times and this: int totalaverage = Convert.ToInt32(Console.ReadLine()); is repeated 4 times and each time added up. Then I need to use it outside the loop to make the finalaverage. Is there any way to do this?

    using System;

    namespace HelloWorld
    {
    class Program
    {
        static void Main()
        {
            Console.WriteLine("Whats your name?");
            string input = Console.ReadLine();
            Console.WriteLine($"Hi {input}");

            Console.WriteLine("What were you hoping to hit for your average?");
            int average = Convert.ToInt32(Console.ReadLine());

            int number = 1;

            while (number < 5)
            {
                Console.WriteLine($"How many miles were you able to travel in week {number}?");
                int totalaverage = Convert.ToInt32(Console.ReadLine());
 

                number = number   1;
            }

            int finalaverage = totalaverage / 4;
            Console.WriteLine($"{input} you have averaged {finalaverage} miles per week");
            if (finalaverage >= average)
            {
                Console.WriteLine("Congratulations you have met your target");
            }
            else
            {
                Console.WriteLine("Sorry you have not met your target");
            }
        }
    }
}

CodePudding user response:

You need to declare your variable outside of your loop, in order to use it outside of your loop, something like this:

int number = 1;
int totalaverage = 0;

    while (number < 5)
    {
        Console.WriteLine($"How many miles were you able to travel in week {number}?");
        totalaverage = Convert.ToInt32(Console.ReadLine());
        number = number   1;
    }

    int finalaverage = totalaverage / 4;
    Console.WriteLine($"{input} you have averaged {finalaverage} miles per week");
    if (finalaverage >= average)
    {
        Console.WriteLine("Congratulations you have met your target");
    }
    else
    {
        Console.WriteLine("Sorry you have not met your target");
    }
  •  Tags:  
  • c#
  • Related