Classic examples of for and do-while loop statements

do-while : The do-while loop will run once, because after the first do loop, when the value of the conditional expression is checked, the loop will exit when the value is not true. It is guaranteed to execute the statement in do{} at least once.

for: The first ";" in the parentheses of the for loop is a single expression that does not participate in the loop. It can be used as an initialization assignment statement for a variable to assign an initial value to the loop control variable. The conditional expression between the ";" signs is a relational expression. When the conditional expression is established, the intermediate loop body is executed. The executed intermediate loop body can be one statement or multiple statements. After the intermediate loop body is executed, the end loop body is executed. After the end of the loop body is executed, the condition will be judged again. If the condition is still satisfied, the above loop will continue to be repeated. When the condition is not satisfied, the current for loop will be jumped out

1. Use do-while statement to program, find the sum of natural numbers 1~100.

#include<iostream>
using namespace std;
void main()
{
    
    
       int i=1,s=0;
       do{
    
    
           s=s+i;
           i++;
          }
       while(i<=100);
              cout<<"s="<<s<<end;
 }

Output: s=5050

2. Use the for statement to find the sum of natural numbers from 1 to 100.

#include<iostream>using 
namespace std;
void main()
{
    
    	
int i,s=0;	
for(i=1;i<=100;i++)	
{
    
    s=s+i;}	
cout<<"s="<<s<<endl;
}

Output: s=5050

3. Use the do-while statement to program and find the value of the expression 1-2+3-4...+99-100

#include<iostream>
using namespace std;
void main()
{
    
    	
int i,s=0,t=0,n;	
for(i=0;i<=100;i++)	
 {
    
    		
  if(i%2==0)         
    s=i+s;		
  else 		
   t=t+i;	
  }         
    n=t-s;	
    cout<<"n="<<n<<endl;
}

Output: -50

4. Programming to calculate the area of ​​the graph.

#include <iostream>
using namespace std;
const float PI = 3.1416;
void main(){
    
    	
int i;	
float r,a,b,area;	
cout << "图形的类型为?(1-圆形 2-长方形 3-正方形):";
cin >> i;	
switch(i)	
{
    
    	
case 1:		
	cout<<"圆的半径为:";		
	cin>>r;		
	area=PI*r*r;		
	cout<<"面积为:"<<area<<endl;		
	break;	
case 2:		
	cout<<"矩形的长为:";		
	cin>>a;		
	cout<<"矩形的宽为:";		
	cin>>b;		
	area=a*b;	  
	 cout<<"面积为:"<<area<<endl;		
	 break;
case 3:		
	 cout<<"正方形的边长为:";		
	 cin>>a;		
	 area=a*a;    
	 cout<<"面积为:"<<area<<endl;
	 break;	}
}

Result: What is the type of figure? (1-Circle 2-Rectangle 3-Square): 1
The radius of the circle is: 3 The
area is: 28.2744

Guess you like

Origin blog.csdn.net/haha_7/article/details/108805313