Printing square using specified character and multiplying chars [closed]
Write a programme that prints a square pattern of side length M of any single character specified by the user using a single for loop and a single if else statement. You should define both M and the character constant C as preprocessor statements.
I actually did that but I wonder is there any easier way to solve this problem. Here's my code:
#include <stdio.h>
#include <string.h>
int
main()
{
int M, i = 1;
char C, G[1000];
printf("Input a value for side length:\n");
scanf("%d", &M);
printf("Input a character for pattern:\n");
scanf(" %c", &C);
for (; i <= M; i++) {
printf("%c", C);
if (i <= M) {
memset(G, C, (M - 1));
G[M - 1] = '\0';
puts(G);
}
}
return 0;
}
Something along these lines, perhaps:
int M1 = M + 1;
for (int i = 0; i < M*M1; ++i) {
if (i % M1 == M) putchar('\n');
else putchar(C);
}
You can do the memset
outside of the loop once.
You can just do puts
inside the loop:
#include <stdio.h>
#include <string.h>
int
main()
{
int M, i = 1;
char C, G[1000];
printf("Input a value for side length:\n");
scanf("%d", &M);
printf("Input a character for pattern:\n");
scanf(" %c", &C);
memset(G, C, M);
G[M] = '\0';
for (; i <= M; i++)
puts(G);
return 0;
}
For an input of 8
rows and a char of *
, the output is:
Input a value for side length:
8
Input a character for pattern:
*
********
********
********
********
********
********
********
********
UPDATE:
After rereading the requirements, if C
and M
must be macros, the code should be:
#include <stdio.h>
#include <string.h>
#ifndef M
#error M not defined
#endif
#ifndef C
#error C not defined
#endif
int
main()
{
int i = 1;
char G[1000];
memset(G, C, M);
G[M] = '\0';
for (; i <= M; i++)
puts(G);
return 0;
}
And, the program should be compiled with:
cc -o program -DM=8 -DC="'*'" program.c