Practice Exercise: Pyramid Patterns
Let's practice different pyramid patterns using nested loops.
We'll cover the following
In this lesson, we will practice creating more pyramid patterns.
So let’s begin!
1. Pattern of numbers
Implement a function that takes the height as the input and prints the following:
Sample output
Height: 5
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Good luck! 👍
#include <iostream>using namespace std;void patternA(int h){// Add code here.}
If you have solved the problem, congratulations! 🎉
Now, implement a function that takes the height as the input and prints the following:
Sample output
Height: 5
11 12 13 14 15
7 8 9 10
4 5 6
2 3
1
Good luck! 👍
#include <iostream>using namespace std;void patternB(int h){// Add code here.}
2. Pattern of alphabets
Implement a function that takes the height as the input and prints the following:
Sample output
Height: 5
A
B C
D E F
G H I J
K L M N O
Good luck! 👍
#include <iostream>using namespace std;void patternC(int h){// Add code here.}
Implement a function that takes height as input and prints the following:
Sample output
Height: 5
K L M N O
G H I J
D E F
B C
A
Good luck! 👍
#include <iostream>using namespace std;void patternD(int h){// Add code here.}
3. Pattern of primes
Implement a function that takes the height as the input and prints the prime numbers line-by-line as follows:
Sample output
Height: 5
2
3 5
7 11 13
17 19 23 29
31 37 41 43 47
Good luck! 👍
#include <iostream>#include <cmath>using namespace std;void patternE(int h){// Add code here.}
If we look at the solution above, two things are happening.
Inside the patternE()
function, we print the first prime number (which is 2), and then find the next prime number
by calling the function nextPrime()
. This in turn calls the function isPrime()
to check whether or not a number is a prime number.
We have two loops inside the patternE()
function. The outer for
loop runs h
times. The inner loop runs ln
(number of lines) times.