Mega Code Archive

 
Categories / C / Code Snippets
 

Nested for

#include <stdio.h> void main() { long sum = 0L; int x = 1; /* Outer loop control variable */ int j = 1; /* Inner loop control variable */ int count = 10; /* Number of sums to be calculated */ for( x = 1 ; x <= count ; x++ ) { sum = 0L; /* Initialize sum for the inner loop */ /* Calculate sum of integers from 1 to x */ for(j = 1 ; j <= x ; j++ ) sum += j; printf("\n%d\t%ld", x, sum); /* Output sum of 1 to x */ } }