Number of sub-classes · C language-cyclic statements, C language statements
Previously, we talked about three structures in programming (sequence, condition, and loop). Now let's take a look at how to compile the loop statements.
1. while loop Statement (first judgment and then execution)
1 # include <stdio. h> 2 int main (void) 3 {4 int sum = 0, I = 1; // defines the value of sum as 0, the variable I value is 1 5 while (I <= 100) // when I is less than or equal to 100, it enters the loop 6 {// while (){}: conditional expressions in parentheses and cyclic bodies 7 sum = sum + I in curly brackets; // use sum as the accumulators 8 I ++; // I ++ is I = I + 1, where 1 is step 9} 10 printf ("1 + 2 + 3 + ...... + 100 = % d \ n ", sum); // Finally, output 1 + 2 + 3 + ...... + 100 Results 11 return 0; 12}
2. do ...... While loop Statement (first executed and then judged)
1 # include <stdio. h> 2 int main (void) 3 {4 int sum = 0, I = 1; // defines the value of sum as 0, the variable I value is 1 5 do // do followed by {}, and the Circular body 6 {7 sum = sum + I is in curly brackets; // use sum as the accumulators 8 I ++; // I ++ is I = I + 1, where 1 is step 9} 10 while (I <= 100 ); // when I is less than or equal to 100, enter the loop 11 printf ("1 + 2 + 3 + ...... + 100 = % d \ n ", sum); // Finally, output 1 + 2 + 3 + ...... + Result 12 return 0; 13} of 100}
PS: When 10th of the 100 rows is changed to 0, the final output result will be 1. In the while LOOP statement, the final output result will be 0; this is the while and do ...... While.
3. for Loop statements (this is my favorite one)
1 # include <stdio. h> 2 int main (void) 3 {4 int sum = 0, I; // defines the value of sum as 0, variable I does not set its value 5 for (I = 1; I <= 100; I ++) // I = 1 is the initial value assigned to the cyclic variable, I <= 10 is a circular condition, and I ++ is a Circular Variable plus 6 {7 sum = sum + I; // use sum as the accumulators 8} 9 printf ("1 + 2 + 3 + ...... + 100 = % d \ n ", sum); // Finally, output 1 + 2 + 3 + ...... + 100 Results 10 return 0; 11}
PS: the cyclic elements in for (changes to cyclic variables, cyclic conditions, and cyclic variables) can be multiple variables. for example, we can change the 5th rows to "for (I = 1, sum = 10; I <= 100; I ++) ", the final output result is 5060.