C ++ basic tutorial-for Loop statements

Source: Internet
Author: User

For Loop

Sometimes we need to deal with repetitive work. At this time, using cyclic statements is a good method. Let's take a look at this 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 "for" as the file name;

2. Enter the program code.

1) First, let's look at an integer code that shows up to 10;

For (int I = 0; I <10; I ++)

{

Cout <I <"";

}

2) There are three for statement brackets. The first sentence is to define a loop variable. The initial value is 0, and the middle sentence is a loop condition. When I is less than 10, execute the loop statement. The following content must be enclosed in braces,

The next sentence is the step size, I ++ is I = I + 1, plus one increment operation;

3) Save, compile, generate, and run the command, and display 10 records ranging from 0 to 9;

4) Because I starts from 0 and must be smaller than 10, it cannot be equal to, so the two ends are 0 and 9;

5) Okay. Enter another accumulate program, from 1 to 100 (1 + 2 + 3 +... + 100 );

Int sum = 0;

For (int I = 1; I <= 100; I ++)

{

Sum = sum + I;

}

Cout <"sum =" <sum;

6) This I <= 100, which can be added to 100. sum is the variable for storing and adding an I to it each time,

Sum = sum + I, this sentence is cumulative, Like stacked wooden boxes;

7) Save, translate, generate, and run, and the accumulated results are displayed;

# Include <iostream>

Using namespace std;

Int main (int argc, char ** argv)

{

For (int I = 0; I <10; I ++)

{

Cout <I <"";

}

Cout <endl;

Int sum = 0;

For (int I = 1; I <= 100; I ++)

{

Sum = sum + I;

}

Cout <"sum =" <sum;

Return 0;

}

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.