Loops in C++ have not changed. There are still three types of while loops, do-while loops and for loops. There is no difference in the usage methods of break and continue, including the use of many break and continue . We still use the questions to learn and consolidate the concepts in this part. grammar.
Let’s look at question 1143 in the training ground, which is a question about determining prime numbers. After understanding the concept of prime numbers, it is obvious that for any number N, we must try it sequentially from 2 to N-1 to determine whether it is divisible by N. Find Find out whether there are factors that can be divided by N. If there is no factor, it is a prime number. Otherwise, it is not. Then it is obviously a loop traversal question. The C++ code is as follows:
#include<iostream>usingnamespacestd;intmain(){intn,i;cin>>n;for(i=2;i<n;i++){if(n%i==0)break;}if(i>= n)cout<<1<<endl;elsecout<<0<<endl;return0;}
The test run results are as follows:
The old rule is that it’s okay to type the code in person and test it locally, and then proceed after the submission is passed.
Next, let’s look at another question related to loops in C++. Since it is relatively common in ACM competitions, I will also list it for everyone. The question is question 1085 in the training ground. It is a simple question of finding the sum of A+B, but it is multiple sets of test data. The loop accepts continuously. The C++ writing method is as follows:
#include<iostream>usingnamespacestd;intmain(){inta,b;while(cin>>a>>b){cout<<a+b<<endl;}return0;}
The running effect is as follows:
Please note that the condition in the while loop is written as a cin statement. Why can it be written like this? The principle is exactly the same as the C language writing while(scanf(%d%d,&a,&b)==2). They all judge the return value, that is, the return value of cin . I told you earlier that cin returns an istream stream. Object, if a problem occurs and the reception fails, false is returned and the loop ends.
Please be sure to test it on the computer yourself and complete questions 1085~1092 in the training ground using C++.