Sums in a Triangle using C

c
newbie
recursion
sumtrian

#1

I started learning C today and am struggling to implement my approach to SUMTRIAN ( http://www.codechef.com/problems/SUMTRIAN ) using it. I want to make my 2D array representing the triangle accessible to all methods so that I can solve it recursively but can’t figure out how.

In Java, I simply made the array static, saved values of the triangle, then computed the solution recursively.

How do you do this in C? I initialize the 2D array but can’t find anyway to overwrite/update it when it’s outside of any methods. And using my recursive approach, I can’t constantly keep passing in the triangle (I’m finding passing a 2D array through a method challenging…)

Thanks!
Code:

#include <stdio.h>
#include <math.h>

int main()
{
int tests;
scanf("%d", &tests);

while(tests-->0){
	int levels;
	scanf("%d", &levels);
	
	int triangle[levels][levels];
	int y, x, value;
	for(y = 0; y < levels; y += 1){
		for(x = 0; x < 1 + y; x += 1){
			scanf("%d", &value);
			triangle[y][x] = value;
		}
	}//triangle is stored
	/*here i would call a recursive method on the triangle without having to pass it*/
}//all tests processed
return 0;

}


#2

If the previous values of the “triangle” array are not required after the array has been modified by your recursive function, then just make the triangle array global. That means, you’ll have to declare your array before you define your recursive function as well as the main function. Pseudocode:

//include your libraries here

int triangle[MAX_LEVELS][MAX_LEVELS];

//define your recursive function and the main function

Substitute MAX_LEVELS with the maximum value the levels variable can take and don’t re-declare the “triangle” array inside your main function.