The for loop is the third type of loop in C++. It is used more frequently because of its intuitive and strong control capabilities. Its general form is as follows:
for (initialization expression 1; judgment expression 2; update expression 3) {loop body statement}
After the program encounters a for loop, it first executes the initialization expression 1, and then executes the judgment expression 2. It determines whether the loop body is executed based on whether it is true or false. If it is not true, it jumps out and ends the loop. If it is true, execute the statement in the loop body, then execute update expression 3, and then return to judgment expression 2. Repeat the above process. You can see that the three basic conditions of the loop are not separated like the while and do while loops. Instead, they are all concentrated in the parentheses after for, separated by two commas, which looks more intuitive! It is not easy to forget to write "i++", so the for loop is more convenient to use!
Next, in order to enhance everyone's understanding, we start with a practical problem, such as question 1149, to find the sum of odd numbers within N. The idea is very simple, that is, control the loop through for, and then add the odd numbers by judging the odd and even conditions of the numbers. We can try to achieve this using a for loop.
The reference code is as follows:
#include<iostream>usingnamespacestd;intmain(){intn,i;intsum=0;cin>>n;for(i=1;i<=n;i++){if(i%2!=0)//replacement The effect of if(i%2) is the same as sum+=i;}cout<<sum;return0;}
Please try to solve it yourself first, and then refer to the answer after submitting it.