RetailOn technical round question 2014


Write a (c/c++/java) program to create a pyramid based on the user's input.

  




Solution : 

As you know I do explain the easiest way to understand the concept.

Now how to make this program?  

before starting to write the program we should have to think about the concept and how we can make it in the most straightforward way.

If we look into this, this pattern is the combination of blank spaces(-) and *
Even if we give the input num = 3 then the output would be 


 And  if we enter num = 5 then the output would be   


As per the above examples, we can understand that these are the combination of blanks spaces and *


Now how we can make it into program?

we will use 2 for loop inside a loop, 1st loop for blank spaces and 2nd for * symbols.

So below I have written the code...

  
#include
#include

void main() {
  clrscr(); //using for clear the screen on beginning...
  int num;
  input_error: // reverse goto concept uses for validate the user input.

    printf("Enter number for pyramid: ");
  scanf("%d", & num); //here taking input from user.

  if (num <= 0) //this is first condition to check the user input
  {
    printf("\nInvalid Input\n"); //display this message
    goto input_error; //from here it will jump to input_error key and the again read the statements.
  }
  for (int i = 0; i < num; i++) //loop (1)
  {
    for (int j = 1; j < num - i; j++) //loop (2)
      printf(" ");
    for (int k = 1; k <= 2 * i + 1; k++) // loop (3)
      printf("*");
    printf("\n");
  }
  getch();
}

  

Explanation :

Let's assume enter value num = 3

 i=0 then for(int j=1;j<3-0;j++) means for(int j=1;j<3;j++) //it will print two blank spaces
 i=1 then for(int j=1;j<3-1;j++) means for(int j=1;j<2;j++) //it will print one blank spaces.
 i=2 then for(int j=1;j<3-2;j++) means for(int j=1;j<1;j++) //it will print zero blank spaces.

 Inner loop: for(int k=1;k<i*2+1;k++) this loop prints *
         
  i=0 then for(int k=1;k<=i*2+1;k++) means for(int k=1;k<=1;k++) //it will print one time *
  i=1 then for(int k=1;k<=i*2+1;k++) means for(int k=1;k<=3;k++) //it will print three times *
 i=2 then for(int k=1;k<=i*2+1;k++) means for(int k=1;k<=5;k++) //it will print five times *
  
so finally you will get the output like:




I hope this helps you to understand the concept of it. If this helps you please do like, subscribe and share this article with your friends. 

Comments

Post a Comment