C + + Basic Tutorials-while Loop statements

Source: Internet
Author: User
Tags exit first row

In the previous lesson we introduced the For loop in C + +, and this tutorial introduces you to another loop statement while loop.

Let's look at another loop, which differs from the for loop in that the for loop generally knows the number of loops, which is indicated in the first row, while the while loop does not know the number of cycles, let's take a look at an exercise;

1, start Geany

1 point Menu "application-programming-geany" Start Geany, create a new C + + source program;

2 Point Menu "file-Save as" command, with "while" as the filename, save the file to its own folder;

2, input program code

1 Enter a sum of the program, when the input for the end of 0 o'clock;

#include <iostream>

using namespace Std;

int main (int argc, char** argv)

{

int a = 0;

int sum = 0;

cout << "Input a number:";

Cin >> A;

while (a!= 0)

{

sum = Sum +a;

cout << "Input a number:";

Cin >> A;

}

cout << "sum =" << sum;

return 0;

}

2 The first paragraph is the definition of two variables, storing inputs and sums,

The second paragraph is prompted to enter a value,

The third paragraph is the loop, the parentheses to determine the value of a, not 0 sum, and then continue to enter, judge, sum, until the condition does not meet the exit cycle,

The following paragraph is the result of the final sum of the output;

3 save, compile, generate, run, from the keyboard continuously input number, finally lose a 0, get the result of summation;

3 while and for loops, the while loop must first judge the condition, satisfy the recycle, generally used in reading the file, read the end of the file to exit;

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.