I am trying to develop a C code that generates * a pattern by given input. First it must print star descending by 2 and after ascending by 2. like:
input
enter number: 8
output
********
******
****
**
****
******
********
here is what i did so far:
#include <stdio.h>
int printpattern(int n){
if(n==0)return 0;
printf("*");
printpattern(n-1);
}
int pattern(int n){
if(n==0)return 0;
puts("\n");
printpattern(n);
pattern(n-2);
}
int main(){
int n;
puts("number: ");
scanf("%d", &n);
if(n%2==1){
puts("must be even");
main();
}
pattern(n);
return 0;
}
thanks..
CodePudding user response:
Calling the function main recursively will result in executing these statements in each invocation of main
puts("number: ");
scanf("%d", &n);
So it is not a good idea to call main recursively.
I would write the function the following way as it is shown in the demonstration program below.
#include <stdio.h>
void print_pattern( unsigned int n )
{
if ( n )
{
putchar( '*' );
print_pattern( n - 1 );
}
}
void pattern( unsigned int n )
{
if ( n )
{
print_pattern( n );
putchar( '\n' );
if ( n > 2 )
{
pattern( n - 2 );
print_pattern( n );
putchar( '\n' );
}
}
}
int main(void)
{
while ( 1 )
{
printf( "Enter a non-negative number (0 - exit): " );
unsigned int n;
if ( scanf( "%u", &n ) != 1 || n == 0 ) break;
putchar( '\n' );
pattern( n );
putchar( '\n' );
}
return 0;
}
The program output might look like
Enter a non-negative number (0 - exit): 8
********
******
****
**
****
******
********
Enter a non-negative number (0 - exit): 7
*******
*****
***
*
***
*****
*******
Enter a non-negative number (0 - exit): 6
******
****
**
****
******
Enter a non-negative number (0 - exit): 5
*****
***
*
***
*****
Enter a non-negative number (0 - exit): 4
****
**
****
Enter a non-negative number (0 - exit): 3
***
*
***
Enter a non-negative number (0 - exit): 2
**
Enter a non-negative number (0 - exit): 1
*
Enter a non-negative number (0 - exit): 0
Of course you can call the function only for even numbers though the function is more general and can be called for any non-negative number.
The function itself should not depend on whether an even or odd number was passed to it.
CodePudding user response:
I think if the question states you must use recursion, it makes a lot more sense to use recursion this way:
#include <stdio.h>
static void printstars(int n)
{
for (int i = 0; i < n; i ) {
printf("*");
}
printf("\n");
}
static void printpattern(int n)
{
printstars(n);
if (n > 4) {
printpattern(n - 2);
} else {
printstars(2);
}
printstars(n);
}
int main(void)
{
int n;
puts("number: ");
scanf("%d", &n);
if (n & 1) {
fprintf(stderr, "must be even\n");
return 1;
}
printpattern(n);
return 0;
}