99.5k views
1 vote
Write a program that reads an integer and displays, using asterisks, a filled diamond of the given side length. For example, if the side length is 4, the program should display[a diamond with the middle having 7 asterisks]

*

***

*****

*******

*****

***

*

User Sridhar
by
4.1k points

2 Answers

5 votes

Answer:

side = int(input("Please input side length of diamond: "))

# for loop that loop from 0 to n - 1

for i in range(side-1):

# inside the print statement we determine the number of space to print

# using n - 1 and repeat the space

# we also determine the number of asterisk to print on a line

# using 2 * i + 1

print((side-i) * ' ' + (2*i+1) * '*')

# for loop that loop from 0 to n - 1 in reversed way

for i in range(side-1, -1, -1):

# this print statement display the lower half of the diamond

# it uses the same computation as the first for loop

print((side-i) * ' ' + (2*i+1) * '*')

Step-by-step explanation:

The program is written in Python and well commented. The first for loop display the first half of the diamond while the second for loop display the lower half.

A screenshot of program output when the code is executed is attached.

Write a program that reads an integer and displays, using asterisks, a filled diamond-example-1
User Seth Duncan
by
4.4k points
3 votes

Answer:

  1. import java.util.Scanner;
  2. public class Main {
  3. public static void main(String[] args) {
  4. Scanner input = new Scanner(System.in);
  5. int n = input.nextInt();
  6. int l = 1;
  7. for(int i=1; i <= n; i++){
  8. for(int j=1; j<= l; j++){
  9. System.out.print("*");
  10. }
  11. System.out.println();
  12. l = l + 2;
  13. }
  14. l = l - 4;
  15. for(int i=1; i < n; i++){
  16. for(int j=1; j <= l; j++){
  17. System.out.print("*");
  18. }
  19. System.out.println();
  20. l = l-2;
  21. }
  22. }
  23. }

Step-by-step explanation:

The solution code is written in Java.

Firstly use a Scanner object to accept an input integer (Line 5-6).

Create the first set of inner loops to print the upper part of the diamond shape (Line 8-14). The variable l is to set the limit number of asterisk to be printed in each row.

Next, create another inner loops to print the lower part of the diamond shape (Line 17-23). The same variable l is used to set the limit number of asterisk to be printed in each row.

User Mardah
by
4.1k points