Recursive printing in triangle format

Asked

Viewed 144 times

3

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

Ex: if the number given was 3, show:

1
1 2
1 2 3

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

Be able to do that.

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; 
}
  • the statement is confused...what is the ratio of 3 to 1 1 2 1 2 3 ? this is not clear...

  • actually, the editing went wrong.

  • but be able to solve

  • the output is to look like 1 " n" 1 2 " n" 1 2 3 " n"

  • @Denilsonsilva Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already done so. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site

2 answers

3

All I had to do was 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);   
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

There’s just been a mix-up of concepts, either you do recursive or you do iterative and what you did was, rightly, iterative, it’s not an ideal problem for recursive, although it can be used, and clearly you see that it’s more complicated, especially if you do double recursive.

  • as soon as I asked the question, I saw that I was making a mistake, but it was still worth Maniero

1

Normally I wouldn’t put a full answer, but this is an interesting exercise because of the 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 test:

[zv@localhost so]$ ./so339810
1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 
[zv@localhost so]$ 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.