Learn C ++> circular statements and circular Control

Source: Internet
Author: User
Tags case statement

Learn C ++> circular statements and circular Control

 

I. Cyclic statements
When the program needs to repeatedly execute an action, for example, repeatedly output 1000 rows "Hello, world! ", If you write one thousand lines of cout <" Hello, world! ";, Even if it takes time to copy and paste the Statement, the loop statement will be useful.

1. for Loop
The basic form of for loop:

For (initialization expression; conditional expression; Incremental expression) Statement; // loop body

Initialization is a value assignment statement that is used to assign an initial value to the loop control variable. A conditional expression is a relational expression that determines when to exit the loop; increment defines how the cyclic control variable changes after each loop. Separate the three parts with semicolons.

For example:

    int i ;    for( i = 0; i < 10; i++ )        cout<< i <<endl ;

The for loop statement first calculates the initialization expression, that is, the initial value of the loop control variable I is assigned 0; the conditional expression I <10; it indicates that the cout <I <endl; statement is executed when the I value is less than 10. The loop ends when the I value is greater than or equal to (> =) 10; I ++ indicates that the for loop control variable does not have a loop control variable. The value of I increases by 1, and then continues to execute the statements in the loop body, the loop ends until the I value is greater than or equal to 10.

Note:
1>. If multiple statements in the loop body need to be enclosed in braces {} to form a compliant statement;
2>. The initialization expressions, conditional expressions, and incremental expressions in the for loop can be default, but the semicolon (;) cannot be default, for example:

For (;) // an endless loop statement; for (I = 1; I + = 2) // 2 is added for each I, and the loop does not stop the statement; for (j = 5;) // j is 5, and the loop does not stop the statement;

3>. The for loop allows multi-layer nesting, for example:

For (;) {// loop body}
// Other statements}

 

Example: Use the for loop to calculate the sum of 1 + 2 +... + 100

# Include <iostream> using namespace std; int main () {int I; // The cyclic control variable int sum = 0; // stores the sum result, assign the initial value 0 for (I = 1; I <= 100; I ++) sum + = I;/* 1 + 2 +... + 100 */cout <sum <endl; // return 0 for the output summation result ;}

 

2. while Loop
The basic form of while loop:

While (judgment Expression) loop body

When the program executes a while loop, it first calculates the judgment Expression. When the judgment Expression value is true (not 0), it starts to execute the loop body, when the expression value is false (0), skip the loop body and continue executing the statements below the loop body.
For example:

    int i = 0 ;    while( i < 10 )    {        cout<< i << endl ;        i ++ ;    }

 
First, assign the initial value of the loop control variable I to 0, and then calculate I <10 when the program runs while. At this time, the value of I is 0, so I <10 is true, the program starts to execute the statement in the loop body: output the current I value, and then use I ++; To increase the I value by 1, after executing a loop, go to I <10 to check whether the value is true until the end of the loop when the I value is greater than or equal to 10.

Like the for loop, the while LOOP also allows multi-layer nesting.

Example: Use the for loop to calculate the sum of 1 + 2 +... + 100

# Include <iostream> using namespace std; int main () {int I = 1; // cyclic control int sum = 0; // calculates the result while (I <= 100) {sum + = I; I ++;} cout <sum <endl; return 0 ;}

 

3. do... while loop
Unlike A while LOOP, A while LOOP first checks whether the value in the expression is true and then determines whether to execute the loop body, while do... the while LOOP first executes the loop body and then determines whether to continue executing the loop body. An example is provided:

Int I = 0; // loop control do {cout <I <endl;} while (I> 0); // execute a loop when I> 0

 
In this Code, first assign the initial value 0 to the loop control variable I, and then enter do... in the while LOOP body, run the cout <I <endl; statement, and then judge whether I is greater than 0. If I is greater than 0, continue the loop; otherwise, end the loop, the I here is not greater than 0, so the loop ends after a loop body is executed.

That is to say, whether or not the execution conditions of do... while are met, the loop body is always executed once.

To sum up, the while loop line judges the loop condition and then executes the loop body. do... the while LOOP first executes the loop body and then judges whether to continue executing the loop body.

Note: The semicolon (;) after while in do... while cannot be omitted.

Example: Use do... while to calculate the sum of 1 + 2 +... + 100

# Include <iostream> using namespace std; int main () {int I = 1; // circular control int sum = 0; // calculation result do {sum + = I; I ++;} while (I <= 100); cout <sum <endl; return 0 ;}

 

Ii. Loop Control
1. break statement
Break statements are usually used in cyclic or switch statements. It jumps out of the current loop or the current switch statement to execute the next statement of the current statement.

For example, in the switch statement:

    int i = 1 ;    switch( i )    {        case 0:            cout<< "0" <<endl ;        case 1:            cout<< "1" <<endl ;        case 2:            cout<< "2" <<endl ;        default:            cout<< "Others" <<endl;    }

 
The break statement is not used here. Let's look at the output:

12Others

We can see that the program outputs all the subsequent statements from the satisfied case. If we only want to get one result, instead of executing all the case statements after the entry, we need the case statement, you can do this:

        case 0:            cout<< "0" <<endl ; break ;        case 1:            cout<< "1" <<endl ; break ;        case 2:            cout<< "2" <<endl ; break ;        default:            cout<< "Others" <<endl;

 
Add a break statement after each case statement. When a case statement that meets the conditions is executed, the statement block after the case statement is executed will exit the switch statement.

Here is an example of applying a break statement to a loop statement. Taking a while loop as an example:

    int i = 0 ;    while( true )    {        cout<< i <<endl ;        i ++ ;        if( i > 10 )            break ;    }

The while (true) statement is used here. true is one of the keywords of C ++ and represents truth. That is to say, if no other statement exists, this is an endless loop (never stops ), here we also define a variable I, using cout <I <; Output I value in the loop body, I ++; statement is I auto increment 1, next is the if statement. The conditional expression is used to execute the statement in the if statement block when I> 10. That is to say, when I increases to 10, the break statement is executed, thus jumping out of the while loop, in this way, while (true) is no longer an endless loop.

Note:
1>. The break statement does not work for the if-else Condition Statement.
2> in a multi-tier loop, a break statement only jumps one layer outward.

2. continue statement
The function of the continue statement is to skip the remaining statements in the current loop and execute the next loop. The continue statement is only used in loop bodies such as for, while, and do-while. It is often used together with the if Condition Statement to control the loop, but cannot be used to control the remaining statements in the if statement.

One instance: an integer within 100 that can be divisible by 3 at the same time and be divisible by 5 at the same time.

# Include <iostream> using namespace std; int main () {int I; for (I = 0; I <100; I ++) {if (I % 3! = 0 | I % 5! = 0) // when I does not meet the requirements, end this loop continue; cout <I <endl; // output I} return 0 ;}

 
The output result is 15, 30, 45, 60, 75, 90. From the if statement, we can see that when I cannot be divided into 3 or 5, the next loop is continued, so cout <I <endl; is not executed every time, this output statement can be executed only when the statement is not continue.

3. goto statement
When the nested loop is deep and all the loops need to jump out, using the goto statement should be a good choice, for example:

#include<iostream>using namespace std ;int main(){    int i, m, n;    for( i = 0; i < 100; i++ )    {        for( m = 0; m < 100; m++ )        {            for( n = 0; n < 100; n++ )            {                if( (i + m + n) == 256 )                {                    cout<<"i = "<< i <<endl;                    cout<<"m = "<< m <<endl;                    cout<<"n = "<< n <<endl;                    goto stop ;                }            }        }    }    stop: cout<<"Stop"<<endl;    return 0 ;}

Here we use three for loop nesting to calculate the sum of the numbers I, m, and n within three 100 and the sum is 256. Here we only get one result, that is to say, once the first qualified I, m, and n are output, the loop is exited. if break is used in the if statement, the loop where the current if statement is located can only be exited, but cannot exit the previous loop.

Use the goto statement to define a stop statement outside the loop. To exit all loops, go to the External Loop directly. This is equivalent to jumping out of three loops at a time.

 

--------------------

Wid, 2012.11.21

 

Previous Article: learning C ++> selecting structure programming

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.