C - Use Nested for Loops to sum successive integer sequences

Description

Use Nested for Loops to sum successive integer sequences

Demo

#include <stdio.h>

int main(void)
{
      unsigned long sum = 0UL;             // Stores the sum of integers
      unsigned int count = 0;              // Number of sums to be calculated

      // Prompt for, and read the input count
      printf("\nEnter the number of integers you want to sum: ");
      scanf(" %u", &count);

      for(unsigned int i = 1 ; i <= count ; ++i)
      {/*from  w  w w  .ja va 2 s  .co m*/
        sum = 0UL;                         // Initialize sum for the inner loop

        // Calculate sum of integers from 1 to i
        for(unsigned int j = 1 ; j <= i ; ++j)
          sum += j;

        printf("\n%u\t%5lu", i, sum);      // Output sum of 1 to i
      }
      printf("\n");
      return 0;
}

Result

The program calculates the sum of the integers for all values from 1 up to the value of count that you enter.

The inner loop completes all its iterations for each iteration of the outer loop.

The outer loop sets up the value of i that determines how many times the inner loop will repeat:

for(unsigned int i = 1 ; i <= count ; ++i)
{
  sum = 0UL;  // Initialize sum for the inner loop

  // Calculate sum of integers from 1 to i
  for(unsigned int j = 1 ; j <= i ; ++j)
    sum += j;

  printf("\n%u\t%5lu", i, sum);      // Output sum of 1 to i
}

The outer loop starts off by initializing i to 1.

Related Topic