-->





Translate

hollow diamond using for loop c++ code user enter input size of diamond

9 comments
write a c++ program which takes size of diamond and display hollow diamond using nested for loop and asterisk character.
Output should be look like bellow
hollow diamond using for loop c++ code user enter input size of diamond



 User can enter its desired size of diamond either even or odd

For Example
If user enters size of 3
3 lines of will be formed above middle and 3 lines will be formed below middle line
sample output for program hollow diamond using for loop c++ code user enter input size of diamond
Concept used:
c++ code:


#include<iostream>
using namespace std;
int main()
{
cout<<"Enter size of  Daimond:  ";

    int size;
  cin>>size;

    int z=1;
  for int i=0; i<=size; i++)
  {
    for (int j=size; j>i; j--)
    {
      cout<<" "// printing space here
    }

    cout<<"*";  // printing asterisk here

    if i>0)
    {
      for int k=1; k<=z; k++)
      {
        cout<<" ";
      }
      z+=2;
      cout<<"*";
    }
    cout<<endl; // end line similar  to \n
  }

  z-=4;

  for (int i=0; i<=size-1; i++)
  {
    for (int j=0; j<=i; j++)
    {
      cout<<" ";
    }

    cout<<"*";

    for (int k=1; k<=z; k++)
    {
      cout<<" ";
    }
    z-=2;

    if (i!=size-1)
    {
      cout<<"*";
    }
    cout<<endl;
  }
return 0;
}


If user enter size equal to 10
hollow diamond using for loop c++ code user enter input size of diamond size equal 10

Recommended: Dry run the code line by line it will help to understand quickly and also clear the working of nested for loop.

More C++ Shapes Here

9 comments:

  1. Please explain the program PLEASE!!!

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Hi Fahad Munir, I think I made a better code to make a diamond. I think it's better because it draws all the diamond at once and not in two parts as is the case of your code.

    Here it is:

    #include

    using namespace std;

    int main () {
    int n(0),lines(0),center(0),m1(0),m2(0),aux(1);

    cout << "Size of the diamond: ";
    cin >> n;
    lines = n*2 +1;
    center = n+1;
    m1 = center;
    m2 = center;

    for (int i = 1; i<=lines; i++) {
    if (i==center+1) {
    m1+=2;
    m2-=2;
    }
    for (int j = 1; j<=lines; j++) {
    if (j==m1 || j==m2) {
    cout << "*";
    } else {
    cout << " ";
    }
    }

    if (i>center) {
    aux = -1;
    }
    m1 = m1 - aux;
    m2 = m2 + aux;
    cout << endl;
    }

    return 0; }

    ReplyDelete
  5. pant ki type ki shape kis tarah banay gi>>>
    ****** ****** kuch i type ki
    **** ****
    ** ***

    ReplyDelete