Click here to Skip to main content
15,881,092 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
As the PrintPattern function is only being called twice, it prints just 2 exclamation marks '!' instead of 3. Its not a very difficult problem but I am stuck at it. Please help ASAP.

What I have tried:

#include <stdio.h>

char PrintPattern(int n)
{
    
    if(n>0)
    {
        printf("*");
         n--;
        PrintPattern(n);
      
    }
    if(n!=0)
        printf("!");

}

int main()
{
    int n;
    n = 3;
  
    PrintPattern(n);
    return 0;
}
Posted
Updated 12-Aug-21 3:55am

Try
C++
char PrintPattern(int n) // function should be void instead of char.
{
    if(n>0)
    {
        printf("*");
         n--;
        PrintPattern(n);
        printf("!");
    }
    if(n!=0)
        printf("!");
}

As KarstenK suggested, try the debugger, it is an invaluable tool to help you understand what is going on in your code.
 
Share this answer
 
Comments
Hemil Shah 2021 12-Aug-21 9:06am    
I actually tried couple of approaches and hence changed the return type to char, but forgot to revert it back to void while posting the original code I tried. But thanks a lot, mates! I'll try using debugger from now on in such cases.
Greg Utas 12-Aug-21 9:27am    
But do you know why your code failed? When you first called the function, n was 3. But what was n when you reached your if(n != 0) line?
Patrice T 12-Aug-21 9:38am    
I have let this bug to have it understood with debugger :)
Greg Utas 12-Aug-21 9:57am    
I doubt it'll be debugged after you fixed it. But I gave you a 5.
Patrice T 12-Aug-21 10:09am    
Thank you
Use the debugger to find out how often your function is called. I bet 3 times :-O
 
Share this answer
 
Comments
Hemil Shah 2021 12-Aug-21 8:45am    
But then what is the problem? How do I resolve it ? I want x asterisk followed by x examination marks.
Dave Kreskowiak 12-Aug-21 9:44am    
D E B U G G E R ! ! ! ! USE IT!
The debugger is there to debug YOU, not the code. It's there to help you understand what your code is really doing instead of you assuming what it's doing. It will help you find the logic errors in your code.
KarstenK 12-Aug-21 10:58am    
when you are too lazy to use the debugger than you shouldnt code. I was debugging these days some internet socket code ...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900