2014.8.18for Loop

Source: Internet
Author: User

For Loop

1. Initial status

2. Cyclic Conditions

3. Loop body

4. Status Change

Syntax for (Initial State; cyclic condition; state change)

{

Loop body;

}

Eg:

1 for (int i = 1; i <= 10; i++)2 {3      Console.Write(i);4 }

The output result is

 

1 // sum of all numbers within 100 and 2 int sum = 0; 3 for (INT I = 1; I <= 100; I ++) 4 {5 sum = sum + I; 6} 7 console. writeline (SUM );
1 // There is a monkey and a pile of peaches in the park. Every time I eat ordinary Peaches, I will throw the rest of them to a bad one. On the seventh day, I open my eyes and find that there is only one peach, how many peaches are there in the park at the beginning? 2 int sum = 1; 3 for (INT I = 1; I <7; I ++) 4 {5 sum = (sum + 1) * 2; 6} 7 console. writeline ("there are {0} peaches in the park at the beginning. ", Sum );
1 // a rabbit was born every month from the first 3rd months after birth. After the third month, a rabbit was born every month. If the Rabbit does not die, what is the total number of rabbits in 24th months? 2 int n1 = 1, n2 = 1, num = 1; 3 for (INT I = 3; I <= 24; I ++) 4 {5 num = N1 + N2; // Number of rabbits in the nth month = number of rabbits in the first two months and 6 n1 = n2; 7 n2 = num; 8} 9 console. writeline (Num );

 

1 // use 2 for (INT I = 1; I <= 6; I ++) 3 {4 for (Int J = 1; j <= 6-I; j ++) 5 {6 console. write (""); 7} 8 for (int K = 1; k <= I + I-1; k ++) 9 {10 console. write ("★"); 11} 12 console. Write (" \ n "); 13}

The output result of the above Code is

// Diamond for (INT I = 1; I <= 6; I ++) {for (Int J = 1; j <= 6-I; j ++) {console. write ("") ;}for (int K = 1; k <= I + I-1; k ++) {console. write ("★");} Console. write ("\ n") ;}for (int l = 7; L <= 11; l ++) {for (int m = 1; m <= L-6; M ++) {console. write ("") ;}for (INT n = 1; n <= 2 * (12-l)-1; n ++) {console. write ("★");} Console. Write (" \ n ");}

The above code shows the result and illustration

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.