Use while and do...while to compute the sum

/*
while loop to calculate the sum of 1-100
Algorithm: 1. Define the variable i to traverse the integers, and define the variable sum to calculate the sum
2. The structure of the while loop
*/
#include <stdio.h>
int main ()
{
int i= 1 , sum= 0 ; //Define the initial value of the variable i to 1, traverse the integers, sum is used to calculate the sum, and the initial value of sum is 0
while (i<= 100 )
{
sum = sum+i;
i++;
}
printf ( "The sum is: %d \n " ,sum);
return 0 ;

}


/*
Use the do...while loop structure to calculate the sum of integers from 1-100
Algorithm: 1. Define the initial value of the variable i to 1, the initial value of the variable sum to 0, and sum is used to calculate the sum
2. do...while loop structure
*/
#include <stdio.h>
int main ()
{
int i= 1 ,sum= 0 ;
do
{
sum =sum+i;
i++;
}
while(i<= 100);
printf( "总和为:%d \n ",sum);
return 0;
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325382123&siteId=291194637