Chapter 2 C # Basic Syntax 9. C # while loop

This article is transferred from: http://m.biancheng.net/view/2799.html

In the previous section " C # for loop " we explained the use method and case of for loop, in this section we will explain while loop.

C #  while loops are similar to for loops, but while loops are generally applicable to loops of a fixed number of times.

The syntax of the while loop is as follows.

while (Boolean expression)
{
    statement block;
}

The execution process of the while statement is that when the result of the Boolean expression in while is True, the content in the statement block is executed, otherwise it is not executed. Generally, statements that can be operated using a for loop can be completed using a while loop.

[Example] Use a while loop to output the number of 1 ~ 10 and output the sum of 1 ~ 10.

According to the title requirements, the code is as follows.

class Program
{
    static void Main(string[] args)
    {
        int i = 1;
        int sum = 0;//存放1~10的和
        while (i <= 10)
        {
            sum = sum + i;
            Console.WriteLine(i);
            i++;
        }
        Console.WriteLine("1~10的和为:" + sum);
    }  
}

Executing the above code, the effect is shown in the figure below, which is the same as the effect of Example 1 of the previous section " C # for Loop ".

Print numbers from 1 to 10 and sum

Guess you like

Origin www.cnblogs.com/hanguoshun/p/12729198.html