Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursion and printf in C

Tags:

c

My professor asked me to do this:

Input Number: 5
+++++
+++++
+++++
+++++
+++++

I've been trying so hard to get thi; I kept on ending up with a " + " with a huge blank and " + ".

Can you please help me fix this code in C?

#include <stdio.h>
#include <conio.h>
int space(int space1)
{
    if(space1 == 0)
    {
        return 1;
    }
    else
    {
        return printf("\n") && space(space1 - 1);
    }
}
int visual(int plus)
{
    if (plus == 0)
    {
        return 1;
    }
    else
    {
        return printf("+") && visual (plus - 1) && space(plus - 1);
    }
}

int main()
{
    int number;
    printf("Please give the number\n");
    scanf("%d",&number);
    visual(number);
    getch();
}

A new edit; frustrating for me. It gives me 5 rows of + and a big space.

like image 242
JuanDelCarlos Avatar asked Dec 01 '25 13:12

JuanDelCarlos


1 Answers

Inside the recursion function in the if (plus == 0) section you should print the \n character and then use a loop to call visual (number) for number times.

If you really want to do it only with recursions, you also need another recursive function. One recursion function will call the other, one will print "+++++\n" and the other will call this function for x times to produce x number of lines.

 function printpluses (int x){
     if (x==0){
         printf ("\n");
         return;
     }
     else {
          printf ("+");
          printpluses (x-1);
     }
 }

and the other function would be

  function printline (int x, int no_of_pluses){
       if (x==0){
          printf ("\n");
          return;
       }
       else{
           printpluses(no_of_pluses);
           printline (x-1, no_of_pluses);
       }
   }

you can make no_of_pluses global so yo don't pass it along in every call.

like image 180
andreadi Avatar answered Dec 04 '25 05:12

andreadi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!