Question

What is the CS50 "Print Pyramid" problem?

Answer and Explanation

The "Print Pyramid" problem is a classic programming exercise often found in introductory computer science courses, including Harvard's CS50. The goal is to write a program that prompts the user for a positive integer (height) and then prints a pyramid made of hash symbols (#) of that height. The pyramid is right-aligned, so it also includes spaces before the hash symbols on each row.

Here's a breakdown of the problem:

1. Input:

- The program must prompt the user for a non-negative integer that represents the height of the pyramid.

2. Validation:

- It must validate the input, ensuring that the height is a non-negative integer. If the input is invalid, the program should re-prompt the user until a valid input is provided.

3. Output:

- The program must print a pyramid with the specified height, composed of hash symbols and spaces. The pyramid should be right-aligned, meaning that the rightmost hash symbol on each row should align with the right edge of the pyramid.

Here's an example of the expected output for a height of 4:

   #
  ##
 ###
####

Here is an example solution in C:

#include <stdio.h>
#include <cs50.h>

int main(void)
{
   int height;
   do
   {
       height = get_int("Height: ");
   } while (height < 0 || height > 8);

   for (int i = 0; i < height; i++)
   {
       for (int j = 0; j < height - i - 1; j++)
       {
           printf(" ");
       }
       for (int k = 0; k < i + 1; k++)
       {
           printf("#");
       }
       printf("\\n");
   }
}

Explanation of the C code:

The code uses nested loops to construct the pyramid. The outer loop iterates through each row of the pyramid. The first inner loop prints spaces to achieve the right alignment, and the second inner loop prints the hash symbols. The number of spaces decreases as the row number increases, while the number of hash symbols increases.

Key concepts involved:

- Loops: Used to iterate through rows and columns.

- Conditional Statements (Validation): Checks if the input height is valid.

- Input/Output: Getting input from the user and printing the pyramid.

This problem reinforces basic programming concepts like loops, conditional statements, and input/output operations. It helps build a foundation for solving more complex algorithmic problems. Understanding the “Print Pyramid” problem is an excellent step in learning fundamental programming skills.

More questions