C - Hình Thoi #2

C - Hình Thoi #2

 

Question:


Needs to be a C program.  Write a function displayRhombus(diagonal, fillCharacter) that displays a solid rhombus out of character which is passed to the function (as the second argument). The value diagonal is always odd value (e.g., 3, 5, 7 etc) which determines the diagonal of the rhombus. For example, if the function call is displayRhombus(3, ‘#’), then it should display: # ### # Or, if the function call is displayRhombus(5, ‘$’), then it should display: $ $$$ $$$$$ $$$ $ Use this function in a program that asks the user to enter diagonal of the rhombus and also the character and display the rhombus accordingly (by calling the function displayRhombus). 


Answer:


Here is the code for you:

#include <stdio.h>
//Displays a solid rhombus out of character which is passed to the function (as the second argument)
void displayRhombus(int diagonal, char fillCharacter)
 {
  int n = diagonal / 2 + 1;
  for(int i = 0; i < n; i++)    //For each row of the upper half.
   {
    for(int j = 0; j < n - i; j++)    //Loop to print spaces in upper half.
     printf("  ");
    for(int j = 0; j < 2*i+1; j++)        //Loop to fill characters in upper half.
     printf("%c ", fillCharacter);
    printf("\n");                    //Move on to next line.  
   }
  n--;
  for(int i = 0; i < n; i++)    //For each row of the lower half.
   {
    for(int j = 0; j <= i+1; j++)    //Loop to print spaces in lower half.
     printf("  ");
    for(int j = 0; j < 2*(n - i - 1)+1; j++)        //Loop to fill characters in upper half.
     printf("%c ", fillCharacter);
    printf("\n");                    //Move on to next line.  
   } 
 }
int main()
 {
  int dgnl;
  char ch;
  printf("Enter the display character to fill: ");
  scanf("%c", &ch);
  printf("Enter the diagonal length: ");
  scanf("%i", &dgnl);
  displayRhombus(dgnl, ch);
 } 

And the output screenshot is:

image



If you need any refinements, just get back to me.

Previous Post
Next Post

post written by:

Related Posts

0 Comments: