Looping statements (while statements and Do...while statements)

Source: Internet
Author: User

1. While statement: If the condition is true, continue the loop until the condition is not established. The format is as follows:

while (condition)


Loop body (statement or statement block)

2, Do...while statement: If the condition is established, continue the cycle until the conditions are not established. The biggest difference between it and while is that the statements in the Do...while loop are executed at least once, while the statements in the while may not be executed one at a time. The format is as follows:

Do
{
Loop body
}
while (condition); Note Semicolon

Note: (1) The condition after the while must have ();

(2) If there is only one statement, {} can be omitted;

(3) The difference between the two is: while for the first judgment and then execute, and do...while for first execution after judgment.

For example: Ask 1. 100 and: s=1+2+3+...+100;

While statement usage:

#include <iostream>
using namespace Std;
int main ()
{
int n=1,s=0; Define N,s and assign initial values
while (n<=100)//When n<=100 executes the following loop body
{
S=s+n; Accumulate, be sure to figure out this cumulative method
n++; Equivalent to N=n+1
}

cout<<s<<endl; Output for each result s
return 0; The return value of the main function must be 0, otherwise there will be an error in some test systems
}

The following is the use of the Do...while statement:

#include <iostream>
using namespace Std;
int main ()
{
int n=1,s=0; Define N,s and assign initial values
Do
{
S=s+n; Accumulate, be sure to figure out this cumulative method
n++; Equivalent to N=n+1
}

while (n<=100); When n<=100 executes the following loop body, note that there is a semicolon

cout<<s<<endl; Output for each result s
return 0; The return value of the main function must be 0, otherwise there will be an error in some test systems
}

Looping statements (while statements and Do...while statements)

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.