Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Declaring a variable in a loop and using it outside?

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");
            }
        }
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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");
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading