Summary of the differences between for cycle and while cycle in C++
- 2020-11-20 06:11:39
- OfStack
The difference between for and while cycles in C++
The biggest difference between the two is that the for loop 1 is applied to situations where the number of cycles is known, while the while loop 1 is applied to situations where the number of cycles is unknown. In general, the two can be converted to each other.
Take a simple example: take the sum of 1-100.
#include<bits/stdc++.h>
using namespace std;
int main(){
int sum=0;
for(int i=1;i<=100;i++){
sum+=i;
}
cout<<sum;
}
This is an example of using the for loop. The while loop is applied to solve this problem.
#include<bits/stdc++.h>
using namespace std;
int main(){
int sum=0;
int i=100;
while(i--){
sum+=i;
}
cout<<sum;
}
And you can do the same thing.
For beginners to C++, most of the while cycle can be achieved through the for cycle.
Here's a handy example of using the while loop:
Find the sum of the digits of the input integer.
Input:
1 row 1 integer
Output:
An integer
Sample input:
2147483646
Sample output:
45
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,sum=0;
cin>>n;
while(n!=0){
sum+=n%10;
n/=10;
}
cout<<sum;
}
This example is a good example of an while loop.
conclusion