Diamond with for loop | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula gr√°tis
+ 2

Diamond with for loop

Hey, How can i write a program that gets number of horizontal stars and displays a diamond. for example, input 5 , output : * *** ***** *** *

19th Dec 2018, 6:06 AM
Amir
Amir - avatar
7 Respostas
+ 20
//For upper triangle ‚óŹ run an outer loop for k from 1 to n [for number of rows] ‚óŹ inside it run a loop for initial spaces [from 1 to k] ‚óŹ make 1 more loop inside outer loop for stars[from 1 to 2*k-1] ‚óŹ go to next line Similarily, U can form logic for lower triangle ūüĎć
19th Dec 2018, 7:43 AM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 18
Amir For main row stars, these are visible to appear odd number of times //so its better to use 2n-1 Or 2n+1 form. ‚ėļ //good, code works fine ūüĎć
19th Dec 2018, 8:06 AM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 5
I recommend reviewing this thread to further understand recommended alternatives to scanf(). https://stackoverflow.com/questions/865284/what-is-the-easiest-way-to-get-an-int-in-a-console-app
19th Dec 2018, 8:35 AM
David Carroll
David Carroll - avatar
+ 4
You just completed the C tutorial (congratulations ūüéą), so you should at least have some idea what to do. Please show your attempt first before you ask others to write the code for you.
19th Dec 2018, 7:34 AM
Anna
Anna - avatar
+ 4
#include <stdio.h> int main () { int X=3 ; // Totalrows int x , y , z; // x = Rows , y = Space z = Stars for (x = 1;x <= X ; x++) { for (y = X - x;y >= 1 ;y--) { printf(" "); } for (z = 1;z<=2*x-1;z++) { printf("*"); } printf("\n"); // First half of triangle we need to go the next line } for (x = X -1;x>=1;x--) { for (y = 1; y <= X - x ; y++) { printf(" "); } for (z = 1;z<=2*x-1;z++) { printf("*"); } printf("\n"); } } Dear friends, This is how i done the diamond , but i want to how it is possible to enter the number of main row stars
19th Dec 2018, 8:00 AM
Amir
Amir - avatar
+ 3
I was able to use your code mostly as it was by adding lines 4 and 5 and making a slight change to line 7. https://code.sololearn.com/c4gjkz7qx62v/?ref=app
19th Dec 2018, 8:25 AM
David Carroll
David Carroll - avatar
+ 3
Thank you David. You actually solved my problem.
19th Dec 2018, 8:34 AM
Amir
Amir - avatar