N
N
Nikikez2021-10-14 20:16:07
C++ / C#
Nikikez, 2021-10-14 20:16:07

How to get value out of while loop?

Help to make it so that after the While loop, the value obtained directly in it is displayed.

class Program
{
    static void Main(string[] args)
    {
        double N;
        Console.WriteLine("Введите N: ");
        N=Convert.ToInt64(Console.ReadLine());
        int i = -1;
        while (i < N)
        {
            i = i+1;
            Console.WriteLine(i);
        }
        Console.WriteLine(i); // Мне нужно, чтобы здесь выводилось значение из цикла while
    }   
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
WSGlebKavash, 2021-10-14
@WSGlebKavash

While loop variables are stored only while it is running and data is deleted after completion of work. Therefore, it is necessary to initialize the variable BEFORE the loop, and then assign a value to it.
For example like this:

class Program
{
    static void Main(string[] args)
    {
        double N;
        double M;
        Console.WriteLine("Введите N: ");
        N=Convert.ToInt64(Console.ReadLine());
        int i = -1;
        while (i < N)
        {
            i = i+1;
            M = i; //Выводим значение из цикла while
            Console.WriteLine(i);
        }
        Console.WriteLine(M); // Мне нужно, чтобы здесь выводилось значение из цикла while
    }  
}

G
Griboks, 2021-10-14
@Griboks

Console.WriteLine(N);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question