Recurring print in triangle format

3

I have to read an integer value and pass it as parameter to a function. This should show the number using the sample format.

Ex: if the number you entered was 3, show:

1
1 2
1 2 3

I can show the format that asks the question, but not exactly how it asks.

Get it done.

ps: The @ character is just for testing.

void triangulo(int n){
    int i, j;

    for(i = 1 ;i <= n; i++){
        for(j = 1 ;j <= i ; j++){
            printf("@");
        }
        printf("\n");
    }
}

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

     triangulo(n);   
     return 0; 
}
    
asked by anonymous 29.10.2018 / 23:51

2 answers

3

You just needed to put the number in place of the "@":

#include <stdio.h>

void triangulo(int n) {
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++) printf("%d ", j);
        printf("\n");
    }
}

int main() {
     int n;
     scanf("%d", &n);
     triangulo(n);   
}

See running on ideone . And in Coding Ground . Also I put it in GitHub for future reference .

There was only a confusion of concepts, or you make recursive or iterative, and what you did was aptly iterative, not an ideal problem for recursion, although it can be used, and it is clearly seen that it is more complicated, especially if you do double recursive.

    
29.10.2018 / 23:57
1

I would not normally put a complete answer, but this is an interesting exercise because of recursion.

#include <stdio.h>

static void rectri(int n)
{
  int i;

  if (n == 0)
    return;

  rectri(n-1);

  for (i = 0; i < n; i++)
    printf("%d ", i+1);

  printf("\n");

}

int main()
{
  rectri(5);
}

Terminal testing:

[zv@localhost so]$ ./so339810
1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 
[zv@localhost so]$ 
    
30.10.2018 / 00:59