I am a beginner in C and want to create a program using for loop which gives the following output:
* * * * * * *
* * * * * *
* * * *
* *
I am a beginner in C and want to create a program using for loop which gives the following output:
* * * * * * *
* * * * * *
* * * *
* *
How far have you got with it yourself? Do you know how to write a for loop and print statement? What output do you have so far?
Programming is (partly) about giving your best shot at solving a problem, however roughly or incompletely, then considering what you've been able to do and refining your code incrementally. So unless I know where you've got to already, I risk spoiling the learning experience by revealing to much.
How about showing us your code so far?
Here's a cheap version, it does the job but doesn't offer much flexibility.
#include <stdio.h>
int main (int argc, char *argv[])
{
char *strings[4] = { "* * * * * * *",
"* * * * * *",
"* * * *",
"* *" };
int i;
for (i = 0; i < 4; i++)
{
puts (strings[i]);
}
return 0;
}
You're apparently doing this as homework. Here is the solution. But the point of the homework is that you need to understand how this works, what it's doing, etc. Just copying my code won't help you learn.
There are two loops here. The loop using r
is for the rows. The loop using c
is for the columns. There are 7 columns which are either stars or spaces. On the first row, they're all stars. On the second row, column 3 is a space (bear in mind we're numbering from zero). This is achieved because on the second row, r
is 1. The if
condition is therefore if (c>3-1 && c<3+1)
, or if (c>2 && c<4)
- so when c
is 3, a space will be printed. For the other columns, a star is printed. On the next row, it ends up as if (c>1 && c<5)
- so if c is 2, 3 or 4, spaces get printed.
Try playing around with the program, changing the numbers, changing what gets printed in order to get a good understanding of what it's doing.
#include <stdio.h>
int main(void)
{
int r,c;
for (r=0; r!=4; r++)
{
for (c=0; c<7; c++)
{
if (c>3-r && c<3+r)
printf(" ");
else
printf("* ");
}
printf("\n");
}
return 0;
}
Are you stuck with the algorithm or how to implement it in C? The algorithm looks like this:
Let `n` be the width of the rectange
Print n stars followed by a newline
For i from n/2 to 1 (counting down in steps of 1):
Print i stars, then n-2*i spaces, then i stars, then a newline
To implement this in C you need a for-loop and some output function like printf.
I like to write one-liners to solve simple problems like this. ;)
for(int i=0;i<60;i++)putchar(" *\r\n"[i%15>=11?i%15-11:abs(i%15-6)>(i/15)*2-1&&i%15%2==0?1:0]);