Exercises (Part 1)
Now that you know the theory, it's time for some practice!
In this section you'll find a collection of exercises on what we have done so far (the basics of programming with C++). For each exercise one or multiple solutions are provided, but try to make the program yourself first. Sometimes there will be and hint to help you if you are struggling.
For simplicity, we will (almost always) assume for these exercises that the input of the user is valid. If you want to handle the case of invalid inputs, you may want to use a do-while loop.
A difficulty is assigned to each exercise using a 3-star rating. The difficulty is calibrated for beginners. Keep in mind that it is a subjective parameter, therefore may not be accurate.
Compare two numbers (★☆☆)​
Compare two numbers entered by the user and print which one is bigger and lower.
Show solution(s)
- Solution 1
- Solution 2
#include <iostream>
using namespace std;
int main() {
int n1, n2;
cout << "enter the first number: ";
cin >> n1;
cout << "enter the second number: ";
cin >> n2;
if (n1 == n2) {
cout << "both numbers are equal" << endl;
} else if (n1 > n2) {
cout << "the first number is bigger" << endl;
} else {
cout << "the second number is bigger" << endl;
}
return 0;
}
#include <iostream>
using namespace std;
int main() {
int n1, n2;
cout << "enter the first number: ";
cin >> n1;
cout << "enter the second number: ";
cin >> n2;
if (n1 > n2) {
cout << "the first number is bigger" << endl;
} else if (n1 < n2) {
cout << "the second number is bigger" << endl;
} else {
cout << "both numbers are equal" << endl;
}
return 0;
}
Multiplication loop (★☆☆)​
Write a program to multiply a number entered by the user 10 times and print each multiplication to the console.
Show solution(s)
#include <iostream>
using namespace std;
int main() {
int n1, n2;
cout << "enter the first number: ";
cin >> n1;
cout << "enter the second number: ";
cin >> n2;
if (n1 > n2) {
cout << "the first number is bigger" << endl;
} else if (n1 < n2) {
cout << "the second number is bigger" << endl;
} else {
cout << "both numbers are equal" << endl;
}
return 0;
}
Repeated sum (★☆☆)​
Write a program that repeatedly asks for integers and adds them together until 0 is entered, then prints the sum.
Show solution(s)
#include <iostream>
using namespace std;
int main () {
int input, sum = 0;
do {
cout << "Enter a number" << endl;
cin >> input;
sum += input;
} while (input != 0);
cout << "Sum: " << sum << endl;
return 0;
}
Numbers in range (★☆☆)​
Write a program that asks for the lower and upper limit of a numerical range, then accepts n numbers and checks if they are between that range or outside of it, printing the information on screen. The program keeps track of how many numbers are inside the range with a counter.
Show solution(s)
#include <iostream>
using namespace std;
int main() {
int n;
int min;
int max;
int value;
int count = 0;
cout << "How many numbers do you want to enter?";
cin >> n;
cout << "Enter the minimum range limit: ";
cin >> min;
cout << "Enter the maximum range limit: ";
cin >> max;
for (int i = 1; i <= n; i++) {
cout << "Enter a value: " << endl;
cin >> value;
if (value >= min and value <= max) {
count += 1;
}
}
cout << "You entered " << count << " values included in the interval" << endl;
return 0;
}
Triangle categorizer (★★☆)​
Write a program to check if a triangle is equilateral, isosceles or scalene given the 3 sides.
Note:
- An equilateral triangle has all three sides the same length
- An isosceles triangle has exactly two sides of the same length
- A scalene triangle has all sides of different lengths
Remember: any side of a triangle must be shorter than the other two sides added together. If a side is equal to the other two sides or greater, the triangle is not valid.
Criteria for a valid triangle:
- a + b > c
- a + c > b
- b + c > a
Show solution(s)
#include <iostream>
using namespace std;
int main() {
int a, b, c;
bool isValidTriangle;
cout << "Enter the three side lengths (integers): " << endl;
cin >> a;
cin >> b;
cin >> c;
// check validity of the triangle
if (a + b > c && a + c > b && b + c > a) {
isValidTriangle = true;
} else {
isValidTriangle = false;
}
// determine the type of triangle
if (a == b && b == c) {
cout << "The triangle is equilateral" << endl;
} else if (a == b && b != c ||
a == c && b != c ||
b == c && a != c) {
cout << "The triangle is isosceles" << endl;
} else {
cout << "The triangle is scalene" << endl;
}
return 0;
}
Even or odd? (★☆☆)​
Write a program that, given a number num, determines if it's even or odd.
Show solution(s)
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
if (num % 2 == 0) {
cout << "The number is even" << endl;
} else {
cout << "The number is odd" << endl;
}
return 0;
}
Prime numbers (★★☆)​
Write a program that checks whether a number entered by the user is prime or not.
Show solution(s)
- Solution 1
- Solution 2
- Solution 3 👑
Incomplete solution:
#include <iostream>
using namespace std;
int main() {
int n;
bool isPrime = true;
cout << "Enter a number: ";
cin >> n;
// loop to check if n is prime
for (int i = 2; i < n; i++) {
if (n % i == 0) {
isPrime = false;
}
}
if (isPrime == false) {
cout << "The number is not prime" << endl;
} else {
cout << "The number is prime" << endl;
}
return 0;
}
Incomplete solution alternative:
#include <iostream>
using namespace std;
int main() {
int n, count = 0;
cout << "Enter a number: ";
cin >> n;
// loop to check if n is prime
for (int i = 2; i < n; i++) {
if (n % i == 0) {
count = count + 1;
}
}
if (cont <= 2)
cout << "The number is prime" << endl;
else
cout << "The number is not prime" << endl;
return 0;
}
Complete and efficient solution:
#include <iostream>
using namespace std;
int main() {
int n;
bool isPrime = true;
cout << "Enter a number: ";
cin >> n;
// 0 and 1 are not prime numbers
if (n == 0 || n == 1) {
isPrime = false;
}
// loop to check if n is prime
for (int i = 2; i <= n/2; i++) { // there are no integer factors for n beyond n/2
if (n % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
cout << "The number is not prime" << endl;
} else {
cout << "The number is prime" << endl;
}
return 0;
}
Full explanation with code: Programiz.com
Maximum number (non-negative) (★☆☆)​
Write a program that asks for 10 numbers and finds the maximum. Use a while loop with a counter.
Show solution(s)
#include <iostream>
using namespace std;
int main() {
int num;
int count = 0, max = 0, sum = 0;
while (count < 10) {
cout << "Enter a non-negative number: " << endl;
do {
cin >> num;
} while (num < 0);
if (num > max) {
max = num;
}
sum += num;
count += 1;
}
cout << "The maximum number is: " << max << endl;
return 0;
}
Maximum and minimum number (★★☆)​
Write a program that asks the user for n numbers (either positive, negative or null) and saves which one is the biggest and the smallest of them. Print max and min to the console.
Show solution(s)
#include <iostream>
using namespace std;
int main() {
int n;
int input;
int max = INT_MIN; // minimum possible number for signed int type in C++ (-2^31)
int min = INT_MAX; // minimum possible number for signed int type in C++ (2^31 - 1)
cout << "How many numbers do you want to enter?" << endl;
cin >> n;
for (int i = 0; i < n; i++) {
cout << "Enter a number: " << endl;
cin >> input;
if (input >= max)
max = input;
else if (input <= min)
min = input;
}
cout << "The maximum number is: " << max << endl;
cout << "The minimum number is: " << min << endl;
return 0;
}
Quadratic equation solver (★★☆)​
Make a program that solves a quadratic equation using the formula , where is the delta . Use the <cmath>
header for performing the exponentiation and the square root (pow()
and sqrt()
function respectively).
Show solution(s)
#include <iostream>
#include <cmath> // #include <math.h> for C
using namespace std;
int main() {
float a;
float b;
float c;
cout << "Enter the quadratic coefficient for the equation: " << endl;
cin >> a;
if (a == 0) {
cout << "It's not a quadratic equation";
return 0;
}
cout << "Enter the linear coefficient: " << endl;
cin >> b;
cout << "Enter the constant coefficient/free term: " << endl;
cin >> c;
float delta = pow(b, 2) - 4*a*c;
if (delta < 0)
cout << "The equation has no solutions" << endl;
else if (delta == 0) {
cout << "The equation has one solution" << endl;
float x = -b / (2*a);
cout << "The solution is: " << x << endl;
} else {
cout << "The equation has two solutions" << endl;
float x1 = (-b + sqrt(delta)) / (2*a);
cout << "The first solution is: " << x1 << endl;
float x2 = (-b - sqrt(delta)) / (2*a);
cout << "The second solution is: " << x2 << endl;
}
return 0;
}
Month duration & leap year (★★☆)​
Write a program that, given a month as a number between 1 and 12, informs the user of how many days that month consists of. It's suggested to use a switch-case statement. Handle the leap year case, knowing that a year is a year is "leap" when it is divisible by 4 and not by 100 or it is divisible by 400 (explanation with code).
Show solution(s)
#include <iostream>
using namespace std;
int main() {
int month;
int year;
cout << "Enter the month: " << endl;
cin >> month;
switch (month) {
case 4:
case 6:
case 9:
case 11:
cout << "30 days" << endl;
break;
case 2:
cout << "Enter the year: " << endl;
cin >> year;
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
cout << "29 days" << endl;
else
cout << "28 days" << endl;
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
cout << "31 days" << endl;
break;
default:
cout << "Not a month" << endl;
break;
}
return 0;
}
Basic calculator (★☆☆)​
Write a program that simulates a simple calculator with the operators +, -, * and /. The user enter two numbers and an operator. Use a char
for storing the operator.
Show solution(s)
#include <iostream>
using namespace std;
int main() {
int x, y;
float result;
char op;
cout << "Enter the first number: " << endl;
cin >> x;
cout << "Enter the second number: " << endl;
cin >> y;
cout << "\nEnter the operator (+, -, *, /): " << endl;
cout << "\n+ addition" << endl;
cout << "- subtraction" << endl;
cout << "* multiplication" << endl;
cout << "/ division" << endl;
cout << "\nOperator: ";
cin >> op;
switch (op) {
case '+':
result = x + y;
break;
case '-':
result = x - y;
break;
case '*':
result = x * y;
break;
case '/':
if (y == 0)
cout << "You can't divide by 0" << endl;
else
result = (float) (x / y);
break;
default:
cout << "Incorret operation" << endl;
}
cout << "\nThe result is: " << result << endl;
return 0;
}
Factorial (★★☆)​
Write a program that calculates the factorial of a number n entered by the user (n!).
Show solution(s)
#include <iostream>
using namespace std;
int main() {
int n;
int fact = 1;
cout << "Enter a positive integer: " << endl;
cin >> n;
for (int i = 1; i <= n; i++) {
fact *= i;
}
cout << "The factorial of " << n << "is: " << fact << endl;
return 0;
}
Fibonacci sequence (★★★)​
Write a program that calculates the Fibonacci sequence up to n number of number of terms.
Show solution(s)
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter the number of terms for the Fibonacci sequence: ";
cin >> n;
int num1 = 0, num2 = 1, sum = 0;
for (int i = 1; i <= n; i++) {
if (i == 1) {
cout << num1<< endl;
continue;
}
if (i == 2) {
cout << num2 << endl;
continue;
}
sum = num1 + num2;
num1 = num2;
num2 = sum;
cout << sum << endl;
}
return 0;
}
Pythagorean table (★★☆)​
Write a program that prints on the console the Pythagorean table.
Show solution(s)
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
cout << i * j << "\t";
}
cout << endl;
}
return 0;
}
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
Sum till 50 (★☆☆)​
Write a program that, given a number num between 1 and 10, adds its first 10 successors to the number, interrupting the sum prematurely the first time it exceeds the value 50. Print the sum and the index for each iteration and use break
to interrupt the loop.
Show solution(s)
#include <iostream>
using namespace std;
int main() {
int num;
int sum = 0;
do {
cout << "Enter a number: " << endl;
cin >> num;
} while (num < 1 || num > 10);
for (int i = num; i <= num + 10; i++) {
sum += i;
cout << "Iteration " << i - sum + 1 << endl;
cout << "Sum: " << sum << endl;
if (sum > 50)
break;
}
}
Rectangle pattern (★☆☆)​
Write a program that asks for two integers, a base b and a height h, and prints the pattern of a rectangle using asterisks/stars (" ") with b stars for the base and h stars for the height (check that both b and h* are numbers between 1 and 10). For example, if b = 5 and h = 3 the output is:
* * * * *
* * * * *
* * * * *
Show solution(s)
#include <iostream>
using namespace std;
int main() {
int b, h;
do {
cout << "Enter the base: " << endl;
cin >> b;
} while (b < 1 || b > 10);
do {
cout << "Enter the height: " << endl;
cin >> h;
} while (h < 1 || h > 10);
for (int i = 0; i < h; i++) {
for (int j = 0; j < b; j++) {
cout << "* ";
}
cout << endl;
}
return 0;
}
Right triangle pattern (★☆☆)​
Write a program that asks for the number of rows (integer) and prints the pattern of a right triangle (with the right angle on the bottom left) using numbers (use the number if the loop index). For example, if rows = 5 the output is:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Show solution(s)
#include <iostream>
using namespace std;
int main() {
int rows;
cout << "Enter the number of rows: ";
cin >> rows;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < i; j++) {
cout << "* ";
}
cout << endl;
}
return 0;
}
Pyramid pattern (★★☆)​
Write three programs that print these patterns to the console:
*
***
*****
*******
*********
*
* *
* * *
* * * *
* * * * *
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
Each pyramid has 5 rows, but for the last pattern, ask the user how many rows are going to be generated.
Show solution(s)
- Solution 1
- Solution 2
- Solution 3
First pattern:
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
for (int j = 5; j > i; j--)
cout << ' ';
for (int k = 1; k < 2 * i; k++)
cout << '*';
cout << endl;
}
}
Second pattern:
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
for (int j = 5; j > i; j--)
cout << ' ';
for (int k = 1; k <= i; k++)
cout << "* ";
cout << endl;
}
}
Third pattern:
#include <iostream>
using namespace std;
int main() {
int rows;
cout << "Enter number of rows: ";
cin >> rows;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= rows - i; j++) {
cout << " ";
}
for (int k = 0; k != 2 * i - 1; k++) {
cout << "* ";
}
cout << endl;
}
return 0;
}
Painting value predictor (★☆☆)​
Write a program that prompts the user to enter the amount they paid for a painting and the number of years until they plan to resell it. Assuming that its value increases by 5% each year, the program estimates the painting's value for each year and displays the result for every year.
Show solution(s)
#include <iostream>
#include <iomanip> // for setprecision()
using namespace std;
int main() {
float value;
int years;
do {
cout << "How much did you pay the painting?" << endl;
cin >> value;
} while (value <= 0);
do {
cout << "In how many years will you be reselling the painting?" << endl;
cin >> years;
} while (years <= 0);
for (int i = 1; i <= years; i++) {
value *= 1.05;
cout << "The painting in " << i << " years will be worth $" << setprecision(2) << value << endl;
}
return 0;
}
Pendulum oscillation (★☆☆)​
A pendulum oscillates with a period p expressed in seconds which is a function of the length l in meters of the suspension thread according to the following formula: where the constant g is the acceleration of gravity, which on Earth is 9.81 m/s^2. Write a C++ program that determines the oscillation period of the pendulum, given its length l in centimeters.
Show solution(s)
#include <iostream>
#include <cmath>
#define PI 3.1416
#define G 9.81
using namespace std;
int main() {
float l;
do {
cout << "What is the length of the pendulum in cm? " << endl;
cin >> l;
if (l <= 0)
cout << "Invalid length. Try again" << endl;
} while (l <= 0);
l /= 100;
float p = 2 * PI * sqrt(l / G);
cout << "The pendulum has a period equal to " << p << " seconds" << endl;
return 0;
}
BMI calculator (★☆☆)​
Write a program that calculates the BMI given a height and weight. The BMI formula is the following:
Show solution(s)
#include <iostream>
#include <cmath>
using namespace std;
int main() {
float height;
float weight;
cout << "Enter height: " << endl;
cin >> height;
cout << "Enter weight: " << endl;
cin >> weight;
float bmi = weight / pow(height, 2);
cout << "The BMI is " << bmi << endl;
if (bmi < 18.5)
cout << "Underweight";
else if (bmi >= 18.5 && bmi < 24.9)
cout << "Healthy";
else if (bmi >= 24.9 && bmi < 30)
cout << "Overweight";
else if (bmi >= 30)
cout << "Obese";
return 0;
}
Time in seconds (★☆☆)​
Write a program that converts a time expressed in hours, minutes and seconds in only seconds.
Show solution(s)
#include <iostream>
using namespace std;
int main() {
int hours, minutes, seconds;
do {
cout << "Hours: " << endl;
cin >> hours;
} while (hours < 0);
do {
cout << "Minutes: " << endl;
cin >> minutes;
} while (minutes < 0);
do {
cout << "Seconds: " << endl;
cin >> seconds;
} while (seconds < 0);
hours = hours * 60 * 60;
minutes = minutes * 60;
int total = hours + minutes + seconds;
cout << "The conversion in seconds is: " << total << endl;
return 0;
}
Fraction simplifier (★★☆)​
Write a program that prompts the user to enter a fraction as a numerator and denominator. It checks if the denominator is not equal to zero and displays the fraction, then simplifies the fraction and displays the result. Indicate whether the fraction was simplified or not.
Show solution(s)
#include <iostream>
using namespace std;
int main() {
int n, d;
cout << "Enter the numerator: " << endl;
cin >> n;
do {
cout << "Enter the denominator: " << endl;
cin >> d;
if (d == 0)
cout << "The denominator of a fraction can't be null. Try again" << endl;
} while (d == 0);
cout << "Fraction entered: " << n << " / " << d << endl;
bool r = false;
int min;
if (d < n)
min = d;
else
min = n;
for (int i = min; i >= 2; i--) {
if (n % i == 0 && d % i == 0) {
r = true;
n /= i;
d /= i;
}
}
if (d == 1)
cout << "Apparent fraction of value: " << n << endl;
else
cout << "Simplified fraction: " << n << " / " << d << endl;
if (r)
cout << "Fraction simplified" << endl;
else
cout << "The fraction is not simplifiable" << endl;
return 0;
}