The control structure of C + + Enlightenment

Source: Internet
Author: User

Statements are executed sequentially: The first statement in the same function executes first, then executes the second ... Of course, a handful of programs--including the program we need to write to solve the bookstore problem--can be executed in just one order. Instead, the programming language provides a variety of control structures that allow for more complex execution paths. This section will briefly describe some of the control structures that C + + provides.

Exercise 7:

Compile a program that contains the wrong nested annotations.

Exercise 8:

Indicate which of the following output statements are valid:

std::cout << "/*";
std::cout << "*/";
std::cout << /* "*/" */;

After you have made your judgment, compile these three statements to test your answers. Correct the mistakes you've encountered.

1, while statement

The while statement is used for iterative execution. We can use a while to write a program to compute the number between 1 and 10:

#include <iostream>
int main()
{
int sum = 0, val = 1;
// 持续执行
while
until
val
is greater than 10
while (val <= 10) {
sum += val; // 赋值 sum + val 赋给sum
++val; // 增加 给val加1
}
std::cout << "Sum of 1 to 10 inclusive is "
<< sum << std::endl;
return 0;
}

After the program is compiled and executed, it prints out:

Sum of 1 to 10 inclusive is 55

As in the previous example, we first included the iostream header file and defined a main function. In the main function we have defined two integer variables: sum holds numbers and Val represents values from 1 to 10. We gave sum an initial value of 0,val starting at 1.

An important part of this is the while statement. While forms the following

while (condition) while_body_statement;

While periodically test the condition (condition) and execute the related statement until the condition is false.

Related Article

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.