C++ gurus and learners, we program ourselves :P all work is CC licensed

Monday, November 11

Diamond Printing Problem from Uxama Ahmad

20:31 By

The problem was diamond did not print odd rows with required spaces and stars.
#include <iostream>
using namespace std;
int main()
{
 int num,i=1,j=1,k=1,space,star;
 cout<<"Enter odd number of rows: ";
 cin>>num;
 if(num%2==0)
  num=num-1;

 space=num/2;
 star=1;
 cout<<endl;
 do
 { 
  if(space!=0)
   do //prints spaces
   {

    cout<<" ";
    k++;
   }while(k<=space);
   k=1;
   do //prints stars
   {
    cout<<"*";
    j++;
   }while(j<=star);
   j=1;
   cout<<endl;

   i++; //current row number for diamond
   if(i==(num/2)+1)
   {
    space=0;
    star=num;
   }

   if(i<=num/2)
   {
    star=star+2;
    space--;

   }

   if(i>1+num/2)
   {
    star=star-2;
    space++;
   }

   //star=2*i-1;
 }while(i<=num);
 return 0; 
}
sample output

3 comments :

  1. sorry it printed itself as is :P


    #include

    using namespace std;

    void main()

    {

    int num,i=1,j=1,k=1,space,star;

    cout<<"Enter odd number of rows: ";

    cin>>num;

    if(num%2==0)

    num=num-1;

    space=num/2;

    star=1;



    do

    {

    do

    {

    cout<<"u";

    k++;

    }while(k<=space);

    k=1;

    do

    {

    cout<<"*";

    j++;

    }while(j<=star);

    j=1;

    cout<num/2)

    {

    star=star-2;

    space++;

    }

    star=2*i-1;

    }while(i<=num);



    }

    ReplyDelete
  2. The actual code with problem was:

    #include <iostream> using namespace std; void main() { int num,i=1,j=1,k=1,space,star; cout<<"Enter odd number of rows: "; cin>>num; if(num%2==0) num=num-1; space=num/2; star=1; do { do { cout<<"u"; k++; }while(k<=space); k=1; do { cout<<"*"; j++; }while(j<=star); j=1; cout<<endl; i++; if(i==num/2) { space=0; star=num; } if(i<num/2) { star=star+2; space--; } if(i>num/2) { star=star-2; space++; } star=2*i-1; }while(i<=num); }

    ReplyDelete
  3. The problems were in concept that odd when divided by 2 is truncated to highest lower natural number and the do loop to print space it first executed and then checks the condition :)

    ReplyDelete