You are not logged in. Please login at to post your questions!


Sums in a Triangle using C

I started learning C today and am struggling to implement my approach to 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);

    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;


asked 19 Jul '14, 12:51

gage's gravatar image

accept rate: 0%

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.


answered 19 Jul '14, 14:45

sniper6's gravatar image

accept rate: 50%

toggle preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here



Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text]( "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported
  • mathemetical formulas in Latex between $ symbol

Question tags:


question asked: 19 Jul '14, 12:51

question was seen: 978 times

last updated: 19 Jul '14, 14:45