how can i create something of this sort:
*
***
*****
*******
*********
*******
*****
***
*
this is my source code:
#include <stdio.h>
int main()
{
int i;
i = 1;
while(i <= 5)
{
printf("*\n");
i++;
}
getchar();
}
how can i create something of this sort:
*
***
*****
*******
*********
*******
*****
***
*
this is my source code:
#include <stdio.h>
int main()
{
int i;
i = 1;
while(i <= 5)
{
printf("*\n");
i++;
}
getchar();
}
A compact, reliable way to produce the pattern is to compute how many stars belong on each row instead of printing a single '*' every loop. For an odd total row count n the top half uses 1, 3, 5, ... stars and the bottom half mirrors it. The example below reads a number of lines, forces an odd count if needed, computes the star count per row with a simple formula, and prints the left-aligned diamond shown in the original post.
#include <stdio.h>
int main(void) {
int lines;
if (scanf("%d", &lines) != 1 || lines <= 0) return 1;
/* make lines odd so there is a single middle row */
if (lines % 2 == 0) ++lines;
int mid = (lines + 1) / 2;
for (int row = 1; row <= lines; ++row) {
int stars = (row <= mid) ? (2 * row - 1) : (2 * (lines - row) + 1);
for (int s = 0; s < stars; ++s) putchar('*');
putchar('\n');
}
return 0;
} As suggested, nested loops are the usual mechanism; the key difference is the formula for the star count. Note that 's loop-based example increases by one per line (1,2,3...), so it produces a different shape — the formula above produces the odd counts 1,3,5,... and then descends. To center the diamond instead of left-aligning it, compute max = 2*mid - 1 and print (max - stars)/2 spaces before the stars.
Quick tips: validate the input (positive integer), prefer putchar in tight loops for speed, and avoid using getchar() as a program pause in production code. Complexity is O(n^2) where n is the number of lines (each row prints up to O(n) characters).
Jump to Post— Adak 419With two for loops, one nested inside the other. The outer for loop manages the rows, and the inner for loop manages the variables for the columns inside the row being printed.
Remember that the total width of the diagram, minus the number of stars you print on that …
With two for loops, one nested inside the other. The outer for loop manages the rows, and the inner for loop manages the variables for the columns inside the row being printed.
Remember that the total width of the diagram, minus the number of stars you print on that row, is the number of spaces that must be printed on the row.
#include<stdio.h>
#define LINES 9
int main()
{
int i,j;
for(i=1;i<=LINES;i++)
{
if(i-1<=LINES/2)
{
for(j=1;j<=i;j++)
printf("*");
}
else
{
for(j=LINES;j>=i;j--)
printf("*");
}
printf("\n");
}
getchar();
} Just change the define number as per the number of lines u require
thank you!
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.