Hackety Hacking Problem Pyramid NestedLoops
Jump to navigation
Jump to search
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); }