C ++ basic tutorial-while loop statements

Source: Internet
Author: User

In the previous lesson, we introduced the for Loop in C ++. This tutorial introduces another loop statement While loop.

Let's look at another loop. The difference between it and the For loop is that the For loop generally knows the number of loops, which is indicated in the first line, while the while LOOP generally does not know the number of loops, let's take a look at an exercise;

1. Start Geany

1) Click "Application-programming-Geany" in the menu to start Geany and create a c ++ source program;

2) Click the "file-save as" command in the menu and save the file to your folder with "while" as the file name;

2. Enter the program code.

1) enter a program for summation. The process ends when the input is 0;

# Include <iostream>

Using namespace std;

Int main (int argc, char ** argv)

{

Int a = 0;

Int sum = 0;

Cout <"input a number :";

Cin>;

While (! = 0)

{

Sum = sum +;

Cout <"input a number :";

Cin>;

}

Cout <"sum =" <sum;

Return 0;

}

2) The first section defines two variables to store the input and sum,

The second paragraph first prompts you to enter a value,

The third part is a loop. In the brackets, first judge the value of a. If it is not 0, the sum is obtained. Then, enter, judge, and sum until the condition is not met and exit the loop,

The following section shows the final sum result;

3) Save, compile, generate, run, input the number continuously on the keyboard, and enter 0 at last to obtain the sum result;

3) The difference between the while loop and the for loop is that the while LOOP must first judge the condition and meet the recycling condition. It is generally used to read files and exit after reading the end Of the file;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.