汇总整数的程序为基础
嵌套循环中的计算
//Sum of successive integer sequences
#include <stdio.h>
int main()
{
unsigned long sum = 0;
unsigned int count = 0;
//Prompt for,and read the input count
printf("\nEnter the number of integers you want to sum: ");
scanf("%u",&count);
for (int i = 1; i <= count; ++i)
{
sum = 0UL;
//Calculate sum of integers from 1 to i
for (int j = 1; j <= i; ++j)
{
sum += j;
}
printf("\n%u\t%5lu", i, sum);
}
printf("\n");
return 0;
}
1 —-> 1
2 —-> 2
3 —-> 6
4 —-> 10
5 —-> 15
在for循环内嵌套while循环
#include <stdio.h>
int main()
{
unsigned long sum = 1UL;
unsigned int j = 1U;
unsigned int count = 0;
printf("\nEnter the number of integers you want to sum: ");
scanf(" %u", &count);
for (unsigned int i = 1; i < count; ++i)
{
sum = 1UL;
j = 1;
printf("\n1");
while (j < i)
{
sum += ++j;
printf(" + %u",j);
}
printf(" = %lu",sum);
}
printf("\n");
return 0;
}
1 = 1
1 + 2 = 3
1 + 2 +3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15