Hackety Hacking Problem Pyramid NestedLoops: Difference between revisions

From OLPC
Jump to navigation Jump to search
(Add category.)
 
(One intermediate revision by one other user not shown)
Line 29: Line 29:
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 37: 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>


Line 77: Line 77:


</pre>
</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);
}