Reputation: 331
I am trying to print this arrow shape times the number of the first argument, horizontally. Right now it is working, but the code seems very redundant.. There must be a better way.. please help?
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
int i;
int a;
a = strtol(argv[1], NULL, 0);
for (i=0; i<a; ++i) {
printf(" * ");
}
printf("\n");
for (i=0; i<a; ++i) {
printf(" *** ");\
}
printf("\n");
for (i=0; i<a; ++i) {
printf(" ***** ");
}
printf("\n");
for (i=0; i<a; ++i) {
printf("*******");
}
printf("\n");
for (i=0; i<a; ++i) {
printf(" *** ");
}
printf("\n");
for (i=0; i<a; ++i) {
printf(" *** ");
}
printf("\n");
for (i=0; i<a; ++i) {
printf(" *** ");
}
printf("\n");
return 0;
}
current output looks like this:
./a.out 3
* * *
*** *** ***
***** ***** *****
*********************
*** *** ***
*** *** ***
*** *** ***
Upvotes: 1
Views: 164
Reputation: 726849
When your code repeats itself, good chances are that you are missing a loop. When the data used by your "would-be-loop" is too dissimilar across iterations, arrays often help.
You can make an array of C strings, and add an extra loop printing strings from it:
char *arrow[] = {
" * ",
" *** ",
" ***** ",
"*******",
" *** ",
" *** ",
};
for (int r = 0 ; r != 6 ; r++) {
for (int i = 0 ; i != 3 ; i++) {
printf("%s", arrow[r]);
}
printf("\n");
}
Upvotes: 3
Reputation: 32260
You can write a simple function to wrap printf
along with your loop . For example:
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
int xprintf(int x, const char *format, ...) {
assert(x >= 0);
int result = 0;
va_list args;
va_start(args, format);
for (int i=0; i<x; ++i) {
int ret = printf(format, args);
// Return early in case of error.
if (ret < 0)
return ret;
// Sum all written bytes.
result += ret;
}
va_end(args);
return result;
}
int main(int argc, char** argv) {
assert(argc == 2);
int x = strtol(argv[1], NULL, 0);
xprintf(x, " * "); printf("\n");
xprintf(x, " *** "); printf("\n");
xprintf(x, " ***** "); printf("\n");
xprintf(x, "*******"); printf("\n");
xprintf(x, " *** "); printf("\n");
xprintf(x, " *** "); printf("\n");
xprintf(x, " *** "); printf("\n");
return 0;
}
Upvotes: 0