Before we talked about the three structures in programming (order, condition, loop), let's look at how loop statements are written.
One, while Loop statement (first judgment after execution)
1#include <stdio.h>2 intMainvoid)3 {4 intsum=0, i=1;//The value of the definition variable sum is 0, and the value of the variable i is 15 while(i<= -)//when I is less than or equal to 100, enter the loop6{//while () {}: The conditional expression is inside the parentheses and the loop body inside the curly braces7Sum=sum+i;//use sum to make accumulators8i++;//i++ is i=i+1, 1 of which is the stride length9 }Tenprintf"1+2+3+......+100=%d\n", sum);//Finally, the result of the output 1+2+3+......+100 One return 0; A}
Second, Do......while Loop statement (after the first execution of judgment)
1#include <stdio.h>2 intMainvoid)3 {4 intsum=0, i=1;//The value of the definition variable sum is 0, and the value of the variable i is 15 Do //Do Follow {}, the loop body inside the curly braces6 {7Sum=sum+i;//use sum to make accumulators8i++;//i++ is i=i+1, 1 of which is the stride length9 }Ten while(i<= -);//when I is less than or equal to 100, enter the loop Oneprintf"1+2+3+......+100=%d\n", sum);//Finally, the result of the output 1+2+3+......+100 A return 0; -}
PS: When the 10th line of 100 is changed to 0, the result of the final output will be 1, and in the while loop to change this, the final output will be 0; this is the difference between the while and the Do......while.
Three, for loop statements (this is my favorite)
1#include <stdio.h>2 intMainvoid)3 {4 intsum=0I//The value of the definition variable sum is 0, and the variable i does not set its value5 for(i=1; i<= -; i++)//I=1 is the cyclic variable assignment initial value, i<=10 is the cyclic condition, i++ is the loop variable self-added6 {7Sum=sum+i;//use sum to make accumulators8 }9printf"1+2+3+......+100=%d\n", sum);//Finally, the result of the output 1+2+3+......+100Ten return 0; One}
The loop elements in ps:for (cyclic variables, loop conditions, and cyclic variables) can be multiple variables, for example, if we change the 5th line to "for (i=1,sum=10;i<=100;i++)", then the final output is 5060.
Number of children · C language--cyclic statements