2019-05-30 12:17:34

I wanted to ask, is it possible to print patterns through functions in c?

In the case it is possible, then please tell me what mistake am I making in the program below. (for the first time perhaps, I am trying to create something without my teacher's asking.)

#include <stdio.h>
int pattern(int);
void main()
{
int n, r;
printf("Enter the value of n:");
scanf("%d",&n);
r=pattern(n);
printf("%d",r);
}
int pattern(int n)
{
int i, j;
for(i=1;i<=n;i++)
{
for(j=1;j<i;j++)
{
return j;
}
}
}

Thanks.

Thumbs up

2019-05-30 23:02:14

I think the problem might be that your trying to return multiple values with a single call one at a time. When you use the return function, it ends that function call. Full stop. So it'll likely only get through the first number, hit return, then exit the whole function instead of continuing the loop, and since you only call pattern() once, you likely only get one value. To fix this, you could make it so instead of returning the value right away, you could store it in a list, and then return the list when its finished to print it, or better still, print the value right there instead of returning it.

-BrushTone v1.3.3: Accessible Paint Tool
-AudiMesh3D v1.0.0: Accessible 3D Model Viewer

Thumbs up

2019-06-02 15:27:44

@magurp:

From the list, I am asuming you are talking about arays?

Unfortunately, I have to restart with those, since dew to the exams my programming stopped for two months right where I was starting to learn arays.

"Print it right there," I am asuming again that you ment print from the function itself?

If yes, then would you mind telling me how can I do that? since the functions I have written so far and seen, do return something to the main(), and then the values are printed.

Thumbs up

2019-06-03 08:16:10

Yes, an array is what I meant. Printing it in the function should be fairly straight forward, just replace return j; with printf("%d",j), like so:

#include <stdio.h>
int pattern(int);
void main()
{
int n, r;
printf("Enter the value of n:");
scanf("%d",&n);
pattern(n);
}
int pattern(int n)
{
int i, j;
for(i=1;i<=n;i++)
{
for(j=1;j<i;j++)
{
printf("%d",j);
}
}
}
-BrushTone v1.3.3: Accessible Paint Tool
-AudiMesh3D v1.0.0: Accessible 3D Model Viewer

Thumbs up

2019-06-05 08:38:18

Hi everyone,
I'm also learning C language these days. I've almost completed the course and I have been given a few programs related to functions. I am not able to understand the logic of Fibonacci series, I know that I have to use recursion method, but what is the logic behind it?

Best regards
Pranam
Don't forget to give me a thumbs up!

Thumbs up +1