[C Language] Introduction to three types of loop statements-while statement, do-while statement, and for statement

Table of contents

while statement

 do-while statement

  for statement

Application of three kinds of loop statements  


while statement

Grammatical structure of while statement

while( expression )

{

    program block

}

Flow chart of while statement

 do-while statement

 Grammatical structure of do-while statement

do

{

    program block

} while( expression); 

 Flowchart of do-while statement

  for statement

Grammatical structure of for statement

for( expression1 ; expression2 ; expression3 )

    program block 

Flowchart of for statement

Application of three kinds of loop statements 

Calculate the cumulative sum s=1+2+……+n

1.While statement implementation

#include<stdio.h> 
int main()
{
	int i=1,n,sum=0;
	printf("n:");
	scanf("%d",&n); 
	while(i<=n)
	{
		sum=sum+i;
		i++;
	 } 
	printf("sum=%d",sum);
	return 0;
}

2.Do-while statement implementation

#include<stdio.h> 
int main()
{
	int i=1,n,sum=0;
	printf("n:");
	scanf("%d",&n); 
	do
	{
		sum=sum+i;
		i++;
	 } while(i<=n);
	printf("sum=%d",sum);
	return 0;
}

3.for statement implementation

#include<stdio.h> 
int main()
{
	int i,n,sum;
	printf("n:");
	scanf("%d",&n); 
	for(i=1,sum=0;i<=n;i++)
	{
		sum=sum+i;		
	 }
	printf("sum=%d",sum);
	return 0;
}

What I have learned on paper is ultimately shallow, and I know that I have to do it in detail.

Guess you like

Origin blog.csdn.net/studyup05/article/details/130337481