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...)
 
(Add category.)
 
(3 intermediate revisions by 2 users not shown)
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")
0.upto(N-1) do | i |
0.upto(N-1) do | i | # Making a loop running from 0 to N-1 using loop variable i
0.upto(N-1-i) do | k |
0.upto(N-1-i) do | k | # This is a nested loop
print " "
print " "
end
end
Line 36: Line 37:
print "*"
print "*"
0.upto(i-1) do | j |
0.upto(i-1) do | j | # This is a nested loop
print(" *")
print(" *")
end
end


print("\n")
print("\n")
end # End of outer loop
end
</pre>
</pre>

== Solution in C==

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

int main(void)
{
int i,j,k,n=0;
clrscr();
printf("Enter the height of the pyramid\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>
[[Category: Hackety Lesson Plan]]

Latest revision as of 04:59, 6 April 2008

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 |            # Making a loop running from 0 to N-1 using loop variable i
	
	0.upto(N-1-i) do | k |  # This is a nested loop
	print " "
	end
	
print "*"
	
	0.upto(i-1) do | j |    # This is a nested loop
	print(" *")
	end

print("\n")
end                             # End of outer loop

Solution in C

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

 int main(void)
 {
  int i,j,k,n=0;
  clrscr();
  printf("Enter the height of the pyramid\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);
}