Write a C language program: enter an n, calculate the sum from 1 to n

Write a C language program: enter an n, and calculate the sum from 1 to n. Write the program as follows:

This is using the while statement

#include"stdio.h"
void main()
{
    
    
    int i=1,n;
    int sum=0;
    printf("please input the n:\n");
    scanf("%d",&n);
    while(i<=n)
    {
    
    
        sum+=i;
        i++; 
    }
    printf("the result is :%d\n",sum);
 }

My first thought was to use a for loop, as follows:

#include"stdio.h"
void main()
{
    
    
    int i,n;
    int sum=0;
    printf("please input the n:\n");
    scanf("%d",&n);
    for(i=1;i<=n;i++)
    	sum+=i;
    printf("the result is:%d\n",sum);
    
 }

To summarize: for loops and while statements, I personally think that for loops may be more useful and better understand. There is a good saying, a for loop can not solve the problem, then another for loop.

Guess you like

Origin blog.csdn.net/m0_54624966/article/details/112857932
Recommended