Friday, July 31, 2009

C++ question,plz tell me coding to print a pyramid???

the output shoule be:





************%26amp;


*********%26amp;***%26amp;


*******%26amp;*******%26amp;


*****%26amp;***********%26amp;


***%26amp;***************%26amp;


%26amp; %26amp; %26amp; %26amp; %26amp; %26amp; %26amp; %26amp; %26amp; %26amp;





asterisks(*) are not to be printed in real pyramid.


asterisks are just the spaces.





i have made the program but the output is not right....


if i enter 10 lines, output comes only as 5 lines


and if i enter 8, results is only 4 lines:


plz help me as wt can i do?


3 minutes ago





the program i made is:


#include%26lt;iostream.h%26gt;


#include%26lt;conio.h%26gt;


int main()


{


clrscr();


int i,j,n,m=1,p=-1;


cout%26lt;%26lt;"enter the no. of rows: ";


cin%26gt;%26gt;n;


n=n+4;


cout%26lt;%26lt;"\n";


for(i=1; i%26lt;=n; i++)


{


for(j=0; j%26lt;=n; j++)


{ cout%26lt;%26lt;" "; }


n-=2;





for(j=1; j%26lt;=(2*i-m); j++)


{ cout%26lt;%26lt;"%26amp;"; }


m+=2;





for (j=1; j%26lt;=p; j++)


{ cout%26lt;%26lt;" "; }


p+=4;


if(j%26gt;1)


{ cout%26lt;%26lt;"%26amp;"%26lt;%26lt;"\n"; }


cout%26lt;%26lt;"\n";


}


getch();


return 0;


}

C++ question,plz tell me coding to print a pyramid???
The reason you're not getting the number of lines you expect, is because you're using n in the test of your for loop, and then also modifying n in the loop itself.





For example, Say you enter 10 as the number of rows you want. n gets set to 14 before the loop starts.





So for the first iteration, i is 1 and n is 14, 1 %26lt;= 14 is true.





Second iteration, n has been decremented by 2, so i is 2 and n is now 12. 2 %26lt;= 12 is true, so it continues.





Third iteration, i is 3, n is 10





Forth iteration, i is 4, n is 8





Fifth iteration, i is 5, n is 6





Sixth iteration, i is 6, n is 4. 6 is not smaller than or equal to 4, so the loop stops.





You probably need to use a separate variable there.


No comments:

Post a Comment