Hackety Hacking Problem Pyramid NestedLoops: Difference between revisions

From OLPC
Jump to navigation Jump to search
(New page: == Problem Statement == Pyramid-shaped structures were built by many ancient civilizations. Here is then a problem for you? You have to design a two dimensional view of the pyramid. HIN...)
 
Line 25: Line 25:


<pre>
<pre>
#The following statement takes input from the user
print("Enter the values of lines to be printed")
print("Enter the height of the pyramid")
N=gets.to_i;
N=gets.to_i;
print("\n")
print("\n")
Line 42: Line 43:
print("\n")
print("\n")
end
end
</pre>

== Solution in C==

<pre>
#include <stdio.h>
#include <conio.h>

int main(void)
{
int i,j,k,n=12;
clrscr();
printf("Enter the value of lines to be printed\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
for(k=0;k<n-1-i;k++)
{
printf(" ");
}
printf("*");

for(j=0;j<(i);j++)
{
printf(" *");
}
printf("\n");

}
getch();
return(0);
}

</pre>
</pre>

Revision as of 22:24, 16 October 2007

Problem Statement

Pyramid-shaped structures were built by many ancient civilizations. Here is then a problem for you?

You have to design a two dimensional view of the pyramid.

HINT: Use Nested For loops

Sample Output

Enter the height of the pyramid: 4
   *
  * *
 * * *
* * * *

Curriculum Connections

This problem gives student help in understanding things mentioned below:

  • How to use nested loops.

Solution in Ruby

#The following statement takes input from the user
print("Enter the height of the pyramid")
N=gets.to_i;
print("\n")
0.upto(N-1) do | i | 
	
	0.upto(N-1-i) do | k |
	print " "
	end
	
print "*"
	
	0.upto(i-1) do | j |
	print(" *")
	end

print("\n")
end

Solution in C

 #include <stdio.h>
 #include <conio.h>

 int main(void)
 {
  int i,j,k,n=12;
  clrscr();
  printf("Enter the value of lines to be printed\n");
  scanf("%d",&n);
  for(i=0;i<n;i++)
  {
    	for(k=0;k<n-1-i;k++)
	    {
	     printf(" ");
	    }
    printf("*");

  	 for(j=0;j<(i);j++)
  	 {
  	   printf("  *");
  	 }
    printf("\n");

  }
  getch(); 
  return(0);
}