This comprehensive guide provides 57 basic C++ programming exercises designed specifically for beginners.
Each exercise includes a clear practice problem, a helpful hint, a complete C++ solution, and a detailed explanation. This ensures you not only solve the problem but deeply understand why the solution works.
Also, See: C++ Exercises with 10 topic-wise sets and 300+ practice questions.
What You’ll Practice
The exercises and coding challenges cover the following fundamental C++ programming topics:
- I/O & Variables: Focuses on basic console input/output (
std::cin,std::cout), data types, and arithmetic. - Control Flow: Covers conditional logic using
if-else,switch, and logical operators. - Loops: Explores
forandwhileloops for accumulation, sequences (like Fibonacci), and number manipulation. - Arrays & Strings: Introduces arrays (1D/2D), basic array operations, and string manipulation.
- Functions & Pointers: Addresses code modularity (functions, overloading), pass by reference, basic structs, pointers, and file handling.
+ Table Of Contents
Table of contents
- Exercise 1: Arithmetic Operations
- Exercise 2: Area of a Rectangle
- Exercise 3: Average of Three
- Exercise 4: Data Type Sizes
- Exercise 5: ASCII Value
- Exercise 6: Swap Two Numbers
- Exercise 7: Swap Without Temp
- Exercise 8: Simple Interest
- Exercise 9: Even or Odd
- Exercise 10: Largest of Three
- Exercise 11: Leap Year Check
- Exercise 12: Simple Calculator
- Exercise 13: Grade Checker
- Exercise 14: Triangle Type
- Exercise 15: Natural Number Sum
- Exercise 16: Multiplication Table
- Exercise 17: Factorial
- Exercise 18: Fibonacci Series
- Exercise 19: Reverse a Number
- Exercise 20: Count Digits
- Exercise 21: Pattern Printing (Square)
- Exercise 22: Pattern Printing (Right Triangle)
- Exercise 23: GCD (Greatest Common Divisor)
- Exercise 24: Array Sum
- Exercise 25: Largest Element
- Exercise 26: Search Element
- Exercise 27: Count Occurrences
- Exercise 28: Reverse Array
- Exercise 29: Print Even Numbers
- Exercise 30: Swap First and Last
- Exercise 31: Replace All Zeros
- Exercise 32: Recursive Function
- Exercise 33: String Length
- Exercise 34: Palindrome String
- Exercise 35: Count Vowels/Consonants
- Exercise 36: Find Substring
- Exercise 37: Frequency of Characters
- Exercise 38: Matrix Addition (2×2)
- Exercise 39: Prime Number Check
- Exercise 40: Function Overloading (Area)
- Exercise 41: Declaration and Dereference
- Exercise 42: Pass by Reference (Swap)
- Exercise 43: NULL Pointer Check
- Exercise 44: Pointer-to-Pointer (Double Pointer)
- Exercise 45: Structure with Function
- Exercise 46: Pointers (Basic)
- Exercise 47: Pointer Arithmetic
- Exercise 48: Array of Structures (Books)
- Exercise 49: Basic Enum (Days of the Week)
- Exercise 50: Car Class With Attributes and Simple Behavior
- Exercise 51: Default/Parameterized Constructor
- Exercise 52: Destructor Demonstration
- Exercise 53: Create and Write
- Exercise 54: Read and Display
- Exercise 55: Append to File
- Exercise 56: Count Characters
- Exercise 57: Count Lines
Exercise 1: Arithmetic Operations
Practice Problem: Write a C++ program that takes two integer inputs from the user. Calculate and display the sum, difference, product, and integer quotient of these two numbers.
Expected Output:
Enter the first integer: 20
Enter the second integer: 10
Results:
Sum: 30
Difference: 10
Product: 200
Quotient (Integer Division): 2
+ Hint
- Use the standard arithmetic operators: addition (
+), subtraction (-), multiplication (*), and division (/). - Since both inputs are integers, the division operation (quotient) will automatically perform integer division, which is typically what is expected in basic exercises.
+ Show Solution
#include <iostream>
int main() {
int num1, num2;
std::cout << "Enter the first integer: "<< std::endl;
std::cin >> num1;
std::cout << "Enter the second integer: "<< std::endl;
std::cin >> num2;
// Perform and display arithmetic operations
std::cout << "\nResults:" << std::endl;
std::cout << "Sum: " << num1 + num2 << std::endl;
std::cout << "Difference: " << num1 - num2 << std::endl;
std::cout << "Product: " << num1 * num2 << std::endl;
// Check to prevent division by zero
if (num2 != 0) {
std::cout << "Quotient (Integer Division): " << num1 / num2 << std::endl;
} else {
std::cout << "Cannot calculate Quotient: Division by zero!" << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
- The program takes two integer inputs,
num1andnum2using thestd::cinobject along with the extraction operator>>to read the values. - It then uses the respective operators directly within the
std::coutstatements to perform the calculations. - The division operation
/is specifically handled with anifstatement to check if the second number is zero, preventing a runtime error (division by zero).
Exercise 2: Area of a Rectangle
Practice Problem: Write a C++ program that asks the user for the length and width of a rectangle. The program should calculate the area (Area equals Length multiplied by Width) and display the result.
Expected Output:
Enter the length of the rectangle: 10
Enter the width of the rectangle: 5.5
The area of the rectangle is: 55
+ Hint
- The dimensions of a rectangle can often be decimal values, so it’s best to use a floating-point data type like
doublefor the length, width, and the resulting area to ensure precision. - The formula is simply
Area = length * width.
+ Show Solution
#include <iostream>
int main() {
double length, width, area;
std::cout << "Enter the length of the rectangle: "<< std::endl;
std::cin >> length;
std::cout << "Enter the width of the rectangle: "<< std::endl;
std::cin >> width;
// Calculate the area
area = length * width;
// Display the result
std::cout << "The area of the rectangle is: " << area << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- Three variables of type
doubleare used to handle potential decimal values for the dimensions and the area. - The program reads the input for
lengthandwidth. The core calculation is straightforward multiplication. - Storing the result in the
areavariable before printing is good practice, though not strictly required in this simple case.
Exercise 3: Average of Three
Practice Problem: Develop a C++ program that calculates and displays the arithmetic average (mean) of three given numbers.
Given:
double num1 =4.5, num2=5.5, num3=6.5;Code language: Python (python)
Expected Output:
The average of the three numbers is: 5.5
+ Hint
- The average is calculated by summing the three numbers and then dividing the total sum by three.
- To ensure the average calculation results in a precise decimal value, make sure the sum or the divisor is treated as a floating-point number.
+ Show Solution
#include <iostream>
int main() {
double num1 =4.5, num2=5.5, num3=6.5;
double average;
// Calculate the average (sum divided by 3.0 to ensure float division)
average = (num1 + num2 + num3) / 3.0;
std::cout << "The average of the three numbers is: " << average << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- By declaring
num1,num2, andnum3asdouble, any input, including integers, is stored as a floating-point number. - The expression
(num1 + num2 + num3) / 3.0uses the literal3.0(a double) to force the entire division to be a floating-point operation, which ensures the resultingaveragevariable holds the accurate decimal value.
Exercise 4: Data Type Sizes
Practice Problem: Write a program that uses the C++ language feature to determine and print the size, in bytes, of the four fundamental data types: char, int, float, and double.
Given:
char c = 'C';
int a = 60;
float f = 15.5;
double d = 25.555;Code language: C++ (cpp)
Expected Output:
Size of char: 1 byte(s)
Size of int: 4 byte(s)
Size of float: 4 byte(s)
Size of double: 8 byte(s)
+ Hint
- C++ provides a special unary operator called
sizeof. - This operator, when applied to a data type or a variable, returns the size of that type or variable in bytes.
- Use
sizeof(dataType)for each of the required types.
+ Show Solution
#include <iostream>
int main() {
// Use the sizeof operator on fundamental data types
std::cout << "Size of char: " << sizeof(char) << " byte(s)" << std::endl;
std::cout << "Size of int: " << sizeof(int) << " byte(s)" << std::endl;
std::cout << "Size of float: " << sizeof(float) << " byte(s)" << std::endl;
std::cout << "Size of double: " << sizeof(double) << " byte(s)" << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- The
sizeofoperator is a compile-time operator that returns the size of its operand in memory, measured in bytes. - This program illustrates how the size of standard data types can vary between different architectures and compilers, though
charis guaranteed to be 1 byte, andintis typically 4 bytes on most modern systems
Exercise 5: ASCII Value
Practice Problem: Create a program that accepts a single character input from the user. It should then print the decimal integer value that corresponds to that character in the ASCII (American Standard Code for Information Interchange) table.
Expected Output:
Enter a single character: A
The ASCII value of 'A' is: 65
+ Hint
- When you store a character in a
charvariable, it is internally represented by its ASCII integer code. - To explicitly see this integer value, you can use type casting.
- Cast the
charvariable to anintbefore printing it using the syntax(int)variableName.
+ Show Solution
#include <iostream>
int main() {
char ch;
std::cout << "Enter a single character: "<< std::endl;
std::cin >> ch;
// Cast the char to an int to print its ASCII value
int asciiValue = (int)ch;
std::cout << "The ASCII value of '" << ch << "' is: " << asciiValue << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- The character is stored in the
char chvariable. - When we assign
(int)chtoasciiValue, we are performing an explicit type conversion or casting. - This tells the compiler to treat the character’s memory content not as a character symbol but as its underlying integer value, which is the ASCII code.
Exercise 6: Swap Two Numbers
Practice Problem: Write a C++ program to swap the values of variables A and B using a temporary variable.
Given:
int A = 10, B = 20;Code language: C++ (cpp)
Expected Output:
Before swap: A = 10, B = 20
After swap: A = 20, B = 10
+ Hint
The swap operation requires three steps:
- Save the value of
Ain a temporary variable. - Assign the value of
BtoA. - Assign the value in the temporary variable to
B.
+ Show Solution
#include <iostream>
int main() {
int A = 10, B = 20;
int temp; // The necessary temporary variable
std::cout << "\nBefore swap: A = " << A << ", B = " << B << std::endl;
// Step 1: Store A's value in temp
temp = A;
// Step 2: Assign B's value to A
A = B;
// Step 3: Assign temp's value (original A) to B
B = temp;
std::cout << "After swap: A = " << A << ", B = " << B << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- This is the standard and safest method for swapping values.
- The temporary variable,
temp, acts as a placeholder to prevent the original value ofAfrom being overwritten and lost whenB‘s value is assigned toAin the second step.
Exercise 7: Swap Without Temp
Practice Problem: Write a C++ program to swap the values of variables A and B without using a temporary variable.
Given:
int A = 10, B = 20;Code language: C++ (cpp)
Expected Output:
Before swap: A = 10, B = 20
After swap: A = 20, B = 10
+ Hint
You can use a sequence of arithmetic operations to achieve the swap.
A = A + B(A now holds the sum).B = A - B(B now holds the original A).A = A - B(A now holds the original B).
+ Show Solution
#include <iostream>
int main() {
int A = 10, B = 20;
std::cout << "Before swap: A = " << A << ", B = " << B << std::endl;
// Arithmetic Swap Logic
A = A + B; // A = (Original A + Original B)
B = A - B; // B = (Original A + Original B) - Original B = Original A
A = A - B; // A = (Original A + Original B) - Original A = Original B
std::cout << "After swap: A = " << A << ", B = " << B << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- This method uses arithmetic properties to achieve the swap.
- In the second step, the subtraction effectively isolates the original value of
Aand stores it inB. - In the third step, the subtraction isolates the original value of
Band stores it inA. - Note: This technique can sometimes cause overflow errors if the sum exceeds the capacity of the integer type.
Exercise 8: Simple Interest
Practice Problem: Write a C++ program to calculate the Simple Interest for a given principal amount, rate of interest, and time period.
Given:
double principal = 1000, rate = 10, time = 3;Code language: C++ (cpp)
Expected Output:
Simple Interest (SI) is: 300
+ Hint
The simple interest formula is SI = (P * R * T) / 100. Since the rate and time might include decimals, and the interest result itself will likely be a decimal, use the double data type for all variables: Principal, Rate, Time, and Simple Interest.
+ Show Solution
#include <iostream>
int main() {
double principal = 1000, rate = 10, time = 3, simpleInterest;
// Formula: SI = (P * R * T) / 100
simpleInterest = (principal * rate * time) / 100.0;
std::cout << "\nSimple Interest (SI) is: " << simpleInterest << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- All variables are declared as
doublefor precision. - The input is taken for Principal, Rate, and Time.
- The calculation implements the standard Simple Interest formula. Dividing by
100.0(a floating-point literal) ensures that the division operation is a floating-point division, correctly handling decimal results for the interest.
Exercise 9: Even or Odd
Practice Problem: Write a C++ program that determine whether the given number is even or odd.
Given:
int number = 10;Code language: C++ (cpp)
Expected Output:
10 is an EVEN number.
+ Hint
- An integer is even if it is perfectly divisible by 2. You can check for perfect divisibility using the modulo operator (
%), which returns the remainder of a division. - If the remainder of
number % 2is 0, the number is even; otherwise, it is odd. Use anif-elsestatement.
+ Show Solution
#include <iostream>
int main() {
int number = 10;
// Use the modulo operator to check for even/odd
if (number % 2 == 0) {
std::cout << number << " is an EVEN number." << std::endl;
} else {
std::cout << number << " is an ODD number." << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
- The
ifcondition checksnumber % 2 == 0. The modulo operator (%) calculates the remainder. If the remainder is 0, the number is perfectly divisible by 2, and the code inside theifblock executes, declaring the number as even. - If the remainder is anything else (for integers, it must be 1), the code inside the
elseblock executes, declaring it as odd.
Exercise 10: Largest of Three
Practice Problem: Write a C++ program to determine and display the largest number among the given three numbers.
Given:
int a = 10, b = 40, c = 30;Code language: C++ (cpp)
Expected Output:
40 is the largest number.
+ Hint
- You will need to use nested
ifstatements or combine conditions using the logical AND operator (&&). - A common approach is: check if
num1is greater thannum2ANDnum1is greater thannum3. - Repeat this structure for
num2andnum3.
+ Show Solution
#include <iostream>
int main() {
int a = 10, b = 40, c = 30;
if (a >= b && a >= c) {
std::cout << a << " is the largest number." << std::endl;
} else if (b >= a && b >= c) {
std::cout << b << " is the largest number." << std::endl;
} else {
// If A and B are not the largest, C must be the largest (or equal to one of the others)
std::cout << c << " is the largest number." << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
- The logical AND operator (
&&) is used to check two conditions simultaneously. - The first
ifchecks ifais greater than or equal to bothbandc. If true,ais the largest. - If false, the
else ifchecks the same forb. If both checks fail, the lastelseblock correctly identifiescas the largest. - Using
>=handles cases where two or all three numbers are equal.
Exercise 11: Leap Year Check
Practice Problem: Create a C++ program that determines whether a given year is a leap year. A leap year has 366 days. (e.g., 2024, 1900).
The rules for a leap year are:
- Divisible by 4: The year must be evenly divisible by 4.
- Exception for centurial years: If the year is divisible by 100, it is not a leap year.
- Exception to the exception: If the year is divisible by 100, it is a leap year if it is also divisible by 400.
Given:
int year = 2024;Code language: C++ (cpp)
Expected Output:
2024 is a Leap Year.
+ Hint
Use the logical OR (||) and logical AND (&&) operators with the modulo operator (%) to construct a single compound condition.
+ Show Solution
#include <iostream>
int main() {
int year = 2024;
// Leap year condition: (Divisible by 4 AND NOT divisible by 100) OR (Divisible by 400)
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
std::cout << year << " is a Leap Year." << std::endl;
} else {
std::cout << year << " is NOT a Leap Year." << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
- This solution translates the complex rule into a single, efficient boolean expression.
- The parentheses enforce the correct order of operations.
- The first part
(year % 4 == 0 && year % 100 != 0)covers most leap years. - The second part
(year % 400 == 0)handles the century exceptions. - The
||(OR) ensures that if either part is true, the year is a leap year.
Exercise 12: Simple Calculator
Practice Problem: Implement a basic calculator that takes two numbers and an operator (+, -, *, or /) from the user. Use a switch statement to perform the requested arithmetic operation and display the result.
Expected Output:
Enter first number: 10
Enter operator (+, -, *, /): *
Enter second number: 5
10 * 5 = 50
+ Hint
- Read two numbers (e.g., as
double) and the operator (aschar) from user - The
switchstatement should evaluate thecharoperator variable, withcaselabels for'+','-','*', and'/'. - Remember to include a
breakafter each case and adefaultcase for invalid operators.
+ Show Solution
#include <iostream>
int main() {
double num1, num2, result;
char op;
std::cout << "Enter first number: "<< std::endl;
std::cin >> num1;
std::cout << "Enter operator (+, -, *, /): "<< std::endl;
std::cin >> op;
std::cout << "Enter second number: "<< std::endl;
std::cin >> num2;
switch (op) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
} else {
std::cout << "Error! Division by zero is not allowed." << std::endl;
return 1; // Indicate error
}
break;
default:
std::cout << "Error! Invalid operator entered." << std::endl;
return 1;
}
std::cout << num1 << " " << op << " " << num2 << " = " << result << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- The
switchstatement is excellent for handling a single variable that can have many discrete values (the operator). - Each
caselabel matches one possible operator. - The division case includes an inner
ifstatement to safely check for and prevent division by zero. - The
defaultcase handles any operator not defined in the other cases.
Exercise 13: Grade Checker
Practice Problem: Read a student’s numerical score (0 to 100) and assign a letter grade based on the following criteria using an if-else if ladder: A (90-100), B (80-89), C (70-79), D (60-69), and F (below 60).
Expected Output:
Enter the student's score (0-100): 87
Grade: B
+ Hint
- Start checking from the highest grade range downwards. For example, the first condition should check
score >= 90. If that is false, theelse ifshould checkscore >= 80. - Because the previous condition failed, checking
score >= 80automatically implies the score is between 80 and 89.
+ Show Solution
#include <iostream>
int main() {
int score;
std::cout << "Enter the student's score (0-100): "<< std::endl;
std::cin >> score;
if (score < 0 || score > 100) {
std::cout << "Invalid score entered." << std::endl;
} else if (score >= 90) {
std::cout << "Grade: A" << std::endl;
} else if (score >= 80) {
std::cout << "Grade: B" << std::endl;
} else if (score >= 70) {
std::cout << "Grade: C" << std::endl;
} else if (score >= 60) {
std::cout << "Grade: D" << std::endl;
} else {
std::cout << "Grade: F" << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
- This uses a classic
if-else ifladder. The conditions are ordered from highest to lowest score. - Since conditions are checked sequentially, if the code reaches
else if (score >= 80), it means the previous check (score >= 90) was false, guaranteeing the score is between 80 and 89. - The initial
ifis a good way to handle unexpected input.
Exercise 14: Triangle Type
Practice Problem: Given the lengths of the three sides of a triangle. Determine and print the type of the triangle: Equilateral (all sides equal), Isosceles (exactly two sides equal), or Scalene (no sides equal).
Given:
double sideA = 10, sideB = 10, sideC = 8;Code language: C++ (cpp)
Expected Output:
The triangle is Isosceles.
+ Hint
- Before checking the type, first check if the side lengths form a valid triangle: the sum of any two sides must be greater than the third side.
- Use
if-else if-elseto check the side equalities: Equilateral is the most restrictive, so check for that first.
+ Show Solution
#include <iostream>
int main() {
double sideA = 10, sideB = 10, sideC = 8;
// First check: Is it a valid triangle?
if (sideA + sideB <= sideC || sideA + sideC <= sideB || sideB + sideC <= sideA) {
std::cout << "The given sides DO NOT form a valid triangle." << std::endl;
} else if (sideA == sideB && sideB == sideC) {
std::cout << "The triangle is Equilateral." << std::endl;
} else if (sideA == sideB || sideA == sideC || sideB == sideC) {
std::cout << "The triangle is Isosceles." << std::endl;
} else {
std::cout << "The triangle is Scalene." << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
- The main type checking then begins:
Equilateralis checked first (three equalities). - If that is false,
Isoscelesis checked (any two equalities using||). - If neither of the equality conditions is met, the triangle must be
Scalene, which is caught by the finalelse.
Exercise 15: Natural Number Sum
Practice Problem: Use a for loop to calculate and display the sum of all natural numbers from 1 up to and including a given number N.
Given:
int N = 10;Code language: C++ (cpp)
Expected Output:
The sum of natural numbers up to 10 is: 55
+ Hint
- Use a
forloop that initializes a counter variable to 1, continues as long as the counter is less than or equal to N and increments the counter by 1 in each iteration. - Inside the loop, add the current value of the counter to an accumulating sum variable, which should be initialized to 0.
+ Show Solution
#include <iostream>
int main() {
int N = 10;
int sum = 0;
// Loop from 1 up to N (inclusive)
for (int i = 1; i <= N; ++i) {
sum = sum + i; // Add the current number to the running sum
}
std::cout << "The sum of natural numbers up to " << N << " is: " << sum << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
The for loop is ideal here because the number of iterations (N) is known in advance.
- The loop control variable
istarts at 1. In each cycle, the value ofiis added tosum. - The loop stops once
iexceeds N, and the final calculatedsumis printed.
Exercise 16: Multiplication Table
Practice Problem: Given an integer N. Use a loop to generate and print the multiplication table for N up to 10 multiples (i.e., N*1, N*2, ….. N*10).
Given:
int N = 3;Code language: C++ (cpp)
Expected Output:
Multiplication Table for 3:
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
...
3 x 10 = 30
+ Hint
- Use a
forloop that iterates exactly 10 times, with the counter variable ranging from 1 to 10. - Inside the loop, print the format
N x i = Result, whereiis the loop counter andResultis the product of N andi.
+ Show Solution
#include <iostream>
int main() {
int N = 3;
std::cout << "\nMultiplication Table for " << N << ":" << std::endl;
// Loop 10 times, where i represents the multiplier (1 to 10)
for (int i = 1; i <= 10; ++i) {
int product = N * i;
// Output in the format: N x i = product
std::cout << N << " x " << i << " = " << product << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
- The
forloop iterates 10 times, representing the multipliers 1 through 10. - In each iteration, the product is calculated using
N *iand printed immediately.
Exercise 17: Factorial
Practice Problem: Write a C++ program that calculates the factorial of a non-negative integer N. The factorial of N (written as N!) is the product of all positive integers less than or equal to N (e.g., 5! = 5*4*3*2*1 = 120). Note that 0! = 1.
Given:
int N = 5;Code language: C++ (cpp)
Expected Output:
Factorial of 5 is: 120
+ Hint
- Use a loop that starts at N and counts down to 1. Initialize a
long longvariable (to prevent overflow for larger factorials) to 1. - In each loop iteration, multiply the running product by the current loop counter.
+ Show Solution
#include <iostream>
int main() {
int N = 5;
// Use long long for the result to handle larger factorials
long long factorial = 1;
if (N < 0) {
std::cout << "Factorial is not defined for negative numbers." << std::endl;
} else if (N == 0) {
std::cout << "Factorial of 0 is 1." << std::endl;
} else {
// Loop from N down to 1
for (int i = N; i >= 1; --i) {
factorial *= i; // Equivalent to: factorial = factorial * i;
}
std::cout << "Factorial of " << N << " is: " << factorial << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
- The program first handles edge cases (N < 0 and N = 0).
- For positive N, the
forloop runs in reverse order from N down to 1. - The
factorialvariable is repeatedly multiplied by the loop counteriin an accumulation process, resulting in the final factorial value.
Exercise 18: Fibonacci Series
Practice Problem: Generate and print the Fibonacci sequence up to N terms. The sequence starts with 0 and 1, and each subsequent number is the sum of the two preceding ones (e.g., 0, 1, 1, 2, 3, 5, 8, …).
Given:
int N = 8;Code language: C++ (cpp)
Expected Output:
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13
+ Hint
- You will need three variables: two to store the previous two numbers (
aandb) and one to store the next number (nextTerm). - Initialize
a = 0andb = 1. Use aforloop to iterate N-2 times (since the first two terms are already defined) and update the variables:nextTerm = a + b, thena = b, and finallyb = nextTerm.
+ Show Solution
#include <iostream>
int main() {
int N = 8;
long long a = 0, b = 1; // Start of the series
long long nextTerm;
std::cout << "Fibonacci Series: "<<std::endl;
if (N >= 1) {
std::cout << a;
}
if (N >= 2) {
std::cout << ", " << b;
}
// Loop starts at i=3 since the first two terms are printed already
for (int i = 3; i <= N; ++i) {
nextTerm = a + b;
std::cout << ", " << nextTerm;
// Update a and b for the next iteration
a = b;
b = nextTerm;
}
std::cout << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- The program handles the first two terms (0 and 1) outside the loop.
- The
forloop then calculates and prints the remaining terms. The key logic is the variable reassignment:atakes the value of the oldb, andbtakes the value of the newnextTerm. - This effectively shifts the “window” of the previous two numbers forward by one step in the sequence.
Exercise 19: Reverse a Number
Practice Problem: Write a C++ program to reverse a given integer number. For instance, if the input is 12345, the output should be 54321.
Given:
int N = 12345;Code language: C++ (cpp)
+ Hint
Use a while loop that continues as long as the original number is greater than 0. In each iteration:
- Remove the last digit from the original number using integer division:
number = number / 10. - Extract the last digit using the modulo operator:
digit = number % 10. - Build the reversed number:
reversed = (reversed * 10) + digit.
+ Show Solution
#include <iostream>
int main() {
int number = 12345, reversed = 0;
int originalNumber = number;
// Loop until the number becomes 0
while (number > 0) {
int digit = number % 10; // 1. Get the last digit
reversed = (reversed * 10) + digit; // 2. Add the digit to the reversed number
number /= 10; // 3. Remove the last digit (integer division)
}
std::cout << "The reverse of " << originalNumber << " is: " << reversed << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
The while loop is used because the number of iterations is unknown (it depends on the number of digits). In each iteration:
- Remove the last digit from the original number using integer division:
number = number / 10. - Extract the last digit using the modulo operator:
digit = number % 10. - Build the reversed number:
reversed = (reversed * 10) + digit.
Note: Integer division /= 10 truncates the last digit, bringing the loop closer to termination.
Exercise 20: Count Digits
Practice Problem: Write a C++ program to count a total number of digits in a number.
Given:
long long N = 4829;Code language: C++ (cpp)
Expected Output:
Given integer: 4829
The number of digits in 4829 is: 4
+ Hint
- Similar to reversing a number, use a
whileloop that continues as long as the number is greater than 0. - In each iteration, simply increment a counter variable and divide the number by 10 (integer division) to “remove” one digit.
- Remember to handle the special case where the input is 0.
+ Show Solution
#include <iostream>
int main() {
long long N = 4829;
int count = 0;
long long originalN = N;
if (N == 0) {
count = 1; // Special case: the number 0 has one digit
} else {
// Loop until the number becomes 0
while (N > 0) {
N /= 10; // Remove the last digit
count++; // Increment the counter
}
}
std::cout << "The number of digits in " << originalN << " is: " << count << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- This uses a
whileloop for counting iterations. - In each iteration, simply increment a counter variable and divide the number by 10 (integer division) to “remove” one digit.
- By repeatedly dividing N by 10 and incrementing
count, we essentially count how many times we can remove a digit before the number becomes zero or less than zero. - A separate check is included for the input N=0, which is a single digit.
Exercise 21: Pattern Printing (Square)
Practice Problem: Use nested loops to print a solid square pattern of asterisks (*) of size 4 * 4.
Expected Output:
Enter the side length N: 4
* * * *
* * * *
* * * *
* * * *
+ Hint
- You need two loops: an outer loop to control the rows (from 1 to N) and an inner loop to control the columns (from 1 to N).
- Inside the inner loop, print a single asterisk (
*). After the inner loop finishes (i.e., after one entire row is printed), usestd::endlto move to the next line for the next row.
+ Show Solution
#include <iostream>
int main() {
int N = 4;
// Outer loop controls the rows
for (int i = 1; i <= N; ++i) {
// Inner loop controls the columns (prints the stars in the current row)
for (int j = 1; j <= N; ++j) {
std::cout << "* ";
}
std::cout << std::endl; // Move to the next line after the row is complete
}
return 0;
}Code language: C++ (cpp)
Explanation:
- This exercise introduces nested loops.
- The outer loop iterates N times for the N rows. For every row, the inner loop iterates N times, printing one
*for each column. - The crucial
std::endlafter the inner loop ensures that each subsequent row starts on a new line, forming the square pattern.
Exercise 22: Pattern Printing (Right Triangle)
Practice Problem: Given an integer N representing the height. Use nested loops to print a right-angled triangle pattern of asterisks (*) where the i-th row has i asterisks.
Given:
int N = 4;Code language: C++ (cpp)
Expected Output:
Height N: 4
*
* *
* * *
* * * *
+ Hint
- The outer loop controls the row number,
i(from 1 to N). - The inner loop controls the number of stars printed in that row.
- The condition for the inner loop should depend on the outer loop’s variable.
- Specifically, the inner loop should run from
j=1up toj <= i.
+ Show Solution
#include <iostream>
int main() {
int N = 4;
// Outer loop controls the rows (i)
for (int i = 1; i <= N; ++i) {
// Inner loop controls the columns (j). It prints i stars.
for (int j = 1; j <= i; ++j) {
std::cout << "* ";
}
std::cout << std::endl; // Move to the next line
}
return 0;
}Code language: C++ (cpp)
Explanation:
- The outer loop variable
irepresents the current row number. - By setting the inner loop’s termination condition to
j <= i, the inner loop prints exactlyiasterisks for thei-th row. - This dynamic condition creates the triangular shape, as the number of stars increases by one in each subsequent row.
Exercise 23: GCD (Greatest Common Divisor)
Practice Problem: Given a two positive integers, A and B. Write a C++ program that calculates their Greatest Common Divisor (GCD), also known as the Highest Common Factor (HCF).
Given:
int A = 50, B = 15;Code language: C++ (cpp)
Expected Output:
The GCD of 50 and 15 is: 5
+ Hint
- A simple method is to use a loop that iterates from 1 up to the smallest of the two numbers.
- Inside the loop, check if both A and B are perfectly divisible by the loop counter
i. - The last value of
ithat divides both A and B will be the GCD. - Alternatively, consider using the more efficient Euclidean algorithm using a
whileloop.
+ Show Solution
#include <iostream>
#include <algorithm> // Needed for std::min (optional, can use if/else)
int main() {
int A = 50, B = 15;
int gcd = 1;
// Determine the minimum of A and B
int minimum = std::min(A, B);
// Loop from 1 up to the minimum number
for (int i = 1; i <= minimum; ++i) {
// Check if i divides both A and B evenly
if (A % i == 0 && B % i == 0) {
gcd = i; // Store the largest common divisor found so far
}
}
std::cout << "The GCD of " << A << " and " << B << " is: " << gcd << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- This solution uses a
forloop to check every number from 1 up to the smaller of A and B. - The
ifcondition uses the logical AND (&&) to ensure that the current loop counteriis a divisor of both numbers. Because the loop iterates in increasing order, the last value stored ingcdwill necessarily be the greatest common divisor.
Exercise 24: Array Sum
Practice Problem: Write a program that first asks the user for the number of elements, N, they wish to store. Then, read N integers into an array. Finally, use a loop to calculate and display the sum of all elements in the array.
Expected Output:
Enter the number of elements (N): 5
Enter 5 integers:
Element 1: 10
Element 2: 20
Element 3: 30
Element 4: 40
Element 5: 50
The sum of all elements in the array is: 150
+ Hint
- Use one
forloop to read the input values into the array elements. - Use a variable initialized to 0 to accumulate the sum of the elements.
+ Show Solution
#include <iostream>
#include <vector>
int main() {
int N;
long long sum = 0; // Use long long for the sum
std::cout << "Enter the number of elements (N): " << std::endl;
std::cin >> N;
// Use a vector for a dynamically sized array in modern C++
std::vector<int> arr(N);
std::cout << "Enter " << N << " integers:" << std::endl;
for (int i = 0; i < N; ++i) {
std::cout << "Element " << i + 1 << ": ";
std::cin >> arr[i];
sum += arr[i]; // Accumulate the sum inside the input loop
}
std::cout << "\nThe sum of all elements in the array is: " << sum << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
The program uses a std::vector to handle the dynamically sized array based on user input N.
- A single
forloop iterates from index 0 up to N-1. - In each iteration, the number is read into
arr[i], and immediately added to thesumvariable. - Using a data type like
long longfor the sum variable is recommended to prevent potential integer overflow.
Exercise 25: Largest Element
Practice Problem: Write a C++ program to traverse the entire array and find the single largest element (the maximum value) stored within it.
Given:
int arr[5] = {10, 30, 40, 60, 20};Code language: C++ (cpp)
Expected Output:
The largest element in the array is: 60
+ Hint
- Initialize a variable, say
max_val, with the value of the first element of the array. - Then, use a
forloop starting from the second element. - Inside the loop, use an
ifstatement to check if the current element (arr[i]) is greater thanmax_val. If it is, updatemax_val.
+ Show Solution
#include <iostream>
int main() {
const int N = 5; // Fixed size for simplicity
int arr[5] = {10, 30, 40, 60, 20};
// Assume the first element is the largest
int max_val = arr[0];
// Loop through the rest of the elements starting from index 1
for (int i = 1; i < N; ++i) {
if (arr[i] > max_val) {
max_val = arr[i]; // Update max_val if current element is larger
}
}
std::cout << "The largest element in the array is: " << max_val << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- The program initializes
max_valwith a value that is guaranteed to be in the array (arr[0]). - The
forloop then iterates through the remaining elements. The conditional checkif (arr[i] > max_val)is the core logic. - If a larger value is found,
max_valis updated. This ensures that after the loop finishes,max_valholds the maximum value encountered.
Exercise 26: Search Element
Practice Problem: Write a C++ program to search a target value in a given array. If it exists, print the index (position) where it was first found; otherwise, indicate that the element was not found.
Given:
int arr[5] = {10, 30, 40, 60, 20};
int target = 40;Code language: C++ (cpp)
Expected Output:
Array elements are: 10, 25, 40, 15, 30
Enter the element to search for: 40
Element 40 found at index: 2
+ Hint
- Use a
forloop to iterate through the array. Inside the loop, use anifstatement to check if the current array element (arr[i]) is equal to the target value. If a match is found, print the indexiand immediately use thebreakkeyword to stop the loop, as the first occurrence is sufficient. - Use a variable initialized to -1 to track the found index.
+ Show Solution
#include <iostream>
int main() {
const int N = 5;
int arr[N] = {10, 25, 40, 15, 30};
int target = 40;
int foundIndex = -1; // -1 indicates the element has not been found
std::cout << "Array elements are: 10, 25, 40, 15, 30" << std::endl;
// Linear search loop
for (int i = 0; i < N; ++i) {
if (arr[i] == target) {
foundIndex = i; // Store the index
break; // Stop searching immediately
}
}
if (foundIndex != -1) {
std::cout << "Element " << target << " found at index: " << foundIndex << std::endl;
} else {
std::cout << "\nElement " << target << " was not found in the array." << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
- This implements a linear search algorithm. The loop iterates through the array sequentially.
- The moment
arr[i]matches thetarget, the indexiis recorded, andbreakensures the program exits the loop instantly. - The final check on
foundIndexdetermines whether a successful match was ever recorded.
Exercise 27: Count Occurrences
Practice Problem: Given an array, write a program to count and print how many times the number 3 appears in the array.
Given:
int numbers[] = {10, 20, 30, 40, 50};
int target = 3;Code language: C++ (cpp)
Expected Output:
The number 3 occurs 3 times.
+ Hint
- Define a variable, let’s call it
count, initialized to zero. - Iterate through the array using a
forloop, and use anifstatement to check if the current element is equal to the target number (3). If the condition is true, increment thecountvariable.
+ Show Solution
#include <iostream>
int main() {
int arr[] = {1, 3, 2, 3, 4, 3, 5};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 3;
int count = 0; // Initialize counter
// Iterate through the array elements
for (int i = 0; i < size; ++i) {
if (arr[i] == target) {
count++; // Increment the counter when the target is found
}
}
std::cout << "The number " << target << " occurs " << count << " times." << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
This is another variation of the traversal pattern where an operation (incrementing a counter) is conditionally applied.
The count variable tallies the total number of times the target value (3) is found. Unlike the Linear Search, the for loop must continue until the end of the array to ensure every instance of the target is counted.
Exercise 28: Reverse Array
Practice Problem: Write a program to reverse the order of the elements in the array and then print the reversed array. (e.g., [1, 2, 3, 4] becomes [4, 3, 2, 1]).
Given:
int arr[N] = {10, 20, 30, 40, 50, 60};Code language: C++ (cpp)
Expected Output:
Original Array: 10, 20, 30, 40, 50, 60
Reversed Array: 60, 50, 40, 30, 20, 10
+ Hint
- The most efficient way to reverse an array in place is to swap elements.
- Use a single
forloop that iterates only up to half the length of the array (N / 2). - In each iteration i, swap the element at index i with the element at the corresponding opposite index, which is N – 1 – i. A temporary variable will be needed for the swap
+ Show Solution
#include <iostream>
// Helper function to print the array contents
void printArray(const int arr[], int size) {
for (int i = 0; i < size; ++i) {
std::cout << arr[i] << (i < size - 1 ? ", " : "");
}
std::cout << std::endl;
}
int main() {
const int N = 6;
int arr[N] = {10, 20, 30, 40, 50, 60};
std::cout << "Original Array: ";
printArray(arr, N);
// Swap elements from opposite ends of the array, iterating only halfway
for (int i = 0; i < N / 2; ++i) {
int temp = arr[i]; // 1. Store the front element
arr[i] = arr[N - 1 - i]; // 2. Overwrite front with back element
arr[N - 1 - i] = temp; // 3. Overwrite back with original front (temp)
}
std::cout << "Reversed Array: ";
printArray(arr, N);
return 0;
}Code language: C++ (cpp)
Explanation:
- The solution performs an in-place reversal by iterating only up to half the array size (
N / 2). - The key calculation
N - 1 - iprovides the index symmetrical toifrom the end of the array. - The three-step swap process (using
temp) is essential to prevent data loss when overwriting the first value.
Exercise 29: Print Even Numbers
Practice Problem: Given an integer array, write a C++ program that only prints the elements that are even numbers.
Given:
int arr[] = {1, 6, 3, 8, 5, 10, 7};Code language: C++ (cpp)
Expected Output:
The even numbers in the array are: 6 8 10
+ Hint
- Iterate through the array using a
forloop. Use the modulus operator (%) inside anifstatement to check for divisibility by 2. - If
arr[i] % 2is equal to 0, the number is even and should be printed.
+ Show Solution
#include <iostream>
int main() {
int arr[] = {1, 6, 3, 8, 5, 10, 7};
int size = sizeof(arr) / sizeof(arr[0]);
std::cout << "The even numbers in the array are: "<< std::endl;
// Iterate through the array
for (int i = 0; i < size; ++i) {
// Check if the number is perfectly divisible by 2
if (arr[i] % 2 == 0) {
std::cout << arr[i] << " ";
}
}
std::cout << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
This exercise introduces the concept of conditional printing during array traversal.
- The modulus operator (
%) is used to find the remainder of a division. If the remainder of dividing an element by 2 is 0 (arr[i] % 2 == 0), the number is an even number, and the program executes the printing action. - Otherwise, the number is skipped, effectively filtering the output to only show even values.
Exercise 30: Swap First and Last
Practice Problem: Write a C++ program to swap the value of the first element (index 0) with the value of the last element (index size - 1) in an array. Print the array before and after the swap.
Given:
int arr[] = {10, 20, 30, 40, 50};Code language: C++ (cpp)
Expected Output:
Array BEFORE swap: 10 20 30 40 50
Array AFTER swap: 50 20 30 40 10
+ Hint
You will need a temporary variable (e.g., temp) to hold the value of the first element before overwriting it. The steps are:
- store
arr[0]intemp - assign
arr[size - 1]toarr[0] - assign
temptoarr[size - 1].
+ Show Solution
#include <iostream>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int size = sizeof(arr) / sizeof(arr[0]);
std::cout << "Array BEFORE swap: "<< std::endl;
for (int i = 0; i < size; ++i) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
// Perform the swap
int temp = arr[0]; // Step 1: Store the first element
arr[0] = arr[size - 1]; // Step 2: Overwrite the first element with the last
arr[size - 1] = temp; // Step 3: Overwrite the last element with the stored first element
std::cout << "Array AFTER swap: "<< std::endl;
for (int i = 0; i < size; ++i) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
This exercise teaches the standard variable swap technique, which is crucial for sorting algorithms and in-place array modifications.
Without the temporary variable (temp), the value of the first element would be lost when the second step is executed, as it would be immediately overwritten by the value of the last element. The temporary variable preserves the data during the three-step exchange.
Exercise 31: Replace All Zeros
Practice Problem: Given an array, write a C++ program to replace all occurrences of the number 0 with the value -1. Print the modified array.
Given:
int numbers[] = {10, 20, 30, 40, 50};Code language: C++ (cpp)
Expected Output:
Original array: 1 0 5 0 8 0 2
Modified array: 1 -1 5 -1 8 -1 2
+ Hint
- Use a
forloop to iterate through every element of the array. - Inside the loop, use an
ifcondition to check if the current element is equal to 0. If it is, assign the new value, -1, to that array position.
+ Show Solution
#include <iostream>
int main() {
int arr[] = {1, 0, 5, 0, 8, 0, 2};
int size = sizeof(arr) / sizeof(arr[0]);
std::cout << "Original array: ";
for (int x : arr) {
std::cout << x << " ";
}
std::cout << std::endl;
// Loop to modify the array
for (int i = 0; i < size; ++i) {
if (arr[i] == 0) {
arr[i] = -1; // Replace 0 with -1
}
}
std::cout << "Modified array: ";
for (int x : arr) {
std::cout << x << " ";
}
std::cout << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
This exercise demonstrates in-place modification of an array.
The for loop iterates through the entire array. if the element meets the criteria (arr[i] == 0), its value is changed directly within the array’s memory location (arr[i] = -1). This process alters the array permanently for subsequent operations.
Exercise 32: Recursive Function
Practice Problem: Write a recursive function factorial(int n) to calculate n! (n factorial). Recall that n! = n * (n-1) *...*1, and the base case is 0! = 1.
To find the factorial of a number, you multiply it by every positive integer smaller than it until you reach 1. For example, 5! =5×4×3×2×1=120.
Given:
int number = 5;Code language: C++ (cpp)
Expected Output:
5! is: 120
+ Hint
The recursive step is n! = n * (n-1)!. The base case, which stops the recursion, is when n=0
+ Show Solution
#include <iostream>
// Recursive function definition
long long factorial(int n) {
// Base Case: stops the recursion
if (n == 0) {
return 1;
}
// Recursive Step: calls itself with a smaller input
return n * factorial(n - 1);
}
int main() {
int number = 5;
long long result = factorial(number);
std::cout << number << "! is: " << result << std::endl; // Output: 120
return 0;
}Code language: C++ (cpp)
Explanation:
- This is a classic example of Recursion, where a function calls itself.
- Every recursive function must have a base case (
if (n == 0)) to prevent infinite calls, and a recursive step (n * factorial(n - 1)) that moves the input closer to the base case. - The function breaks the problem (finding 5!) into a smaller problem (finding 4!) until it reaches the solvable base case (0!).
Exercise 33: String Length
Practice Problem: Read a string (a sequence of characters) from the user. Calculate and display the length (number of characters) of the string without using built-in C++ string methods like length() or size().
Expected Output:
Enter a string (may include spaces): PYnative.com
The length of the string (manually counted) is: 12
+ Hint
- If using a C-style character array, use a
whileloop that continues until it encounters the null terminator character (\0), which marks the end of the string. - In each iteration, increment a counter variable and advance the character pointer/index. If using
std::string, you must manually loop over its contents until the null terminator is conceptually reached.
+ Show Solution
#include <iostream>
#include <string>
int main() {
std::string inputStr;
int length = 0;
std::cout << "Enter a string (may include spaces): "<< std::endl;
// std::getline is used to read the whole line including spaces
std::getline(std::cin, inputStr);
// Manual length calculation loop
for (int i = 0; ; ++i) {
// Check if we reached the null terminator (for conceptual/C-style consistency)
// In std::string, accessing past the length() might be dangerous,
// but we assume standard string termination for this exercise.
if (inputStr[i] == '\0' || i >= inputStr.length()) {
break;
}
length++;
}
// A simpler, more compliant way to meet the spirit of the exercise:
// length = 0;
// for (char c : inputStr) {
// length++;
// }
std::cout << "The length of the string (manually counted) is: " << length << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- This solution uses a
forloop that iterates until it detects the end of the string. - While a C-style string uses
\0as a sentinel, thestd::stringversion relies on the bounds or the conceptual end. - By checking
inputStr[i] != '\0'(the sentinel) and incrementing the counter, the loop effectively counts the characters one by one, achieving the goal without callinglength().
Exercise 34: Palindrome String
Practice Problem: Write a C++ program to determine if the string is a palindrome, meaning it reads the same forwards and backwards (e.g., “level”, “madam”). The check should be case-sensitive for this basic exercise.
Given:
std::string str = "level";Code language: C++ (cpp)
Expected Output:
'level' IS a palindrome.
+ Hint
- Use two index pointers: one at the start (
i = 0) and one at the end (j = length - 1). - Use a
whileloop that continues as long asiis less thanj. - Inside the loop, compare
string[i]andstring[j]. - If they are different, set a boolean flag to
falseand break the loop. In each iteration, incrementiand decrementj.
+ Show Solution
#include <iostream>
#include <string>
int main() {
std::string str = "level";
bool isPalindrome = true;
int length = str.length();
int i = 0; // Start index
int j = length - 1; // End index
// Check characters symmetrically from the outside in
while (i < j) {
if (str[i] != str[j]) {
isPalindrome = false;
break; // Mismatch found, stop checking
}
i++; // Move inward from the left
j--; // Move inward from the right
}
if (isPalindrome) {
std::cout << "'" << str << "' IS a palindrome." << std::endl;
} else {
std::cout << "'" << str << "' is NOT a palindrome." << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
- The two-pointer approach one at the start (
i = 0) and one at the end (j = length - 1) efficiently checks for the palindrome property by comparing characters symmetrically. - The
while (i < j)condition ensures the loop runs until the pointers meet or cross, covering exactly half the string comparisons. - If the loop completes without setting
isPalindrometofalse, the string is confirmed to be a palindrome.
Exercise 35: Count Vowels/Consonants
Practice Problem: Write a C++ program to count and display the total number of vowels and the total number of consonants in the given string. Ignore all spaces, digits, and punctuation.
Given:
std::string str = "PYnative";Code language: C++ (cpp)
Expected Output:
Vowel Count: 3
Consonant Count: 5
+ Hint
- Iterate over every character in the string.
- Use the functions
std::tolower()andstd::isalpha()(from thecctypeheader) to simplify checking. - First, ensure the character is a letter. If it is, check if it matches ‘a’, ‘e’, ‘i’, ‘o’, or ‘u’. If it doesn’t match a vowel but is an alphabet character, count it as a consonant.
+ Show Solution
#include <iostream>
#include <string>
#include <cctype> // Required for tolower() and isalpha()
int main() {
std::string str = "PYnative";
int vowelCount = 0;
int consonantCount = 0;
// Iterate through each character in the string
for (char ch : str) {
// 1. Convert to lowercase for simplified comparison
ch = std::tolower(ch);
// 2. Check if the character is a letter of the alphabet
if (std::isalpha(ch)) {
// 3. Check if the letter is a vowel
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowelCount++;
} else {
// If it's a letter but not a vowel, it's a consonant
consonantCount++;
}
}
}
std::cout << "Vowel Count: " << vowelCount << std::endl;
std::cout << "Consonant Count: " << consonantCount << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- The use of
std::isalpha()ensures that only valid letters are processed, ignoring other symbols. - Converting the character to lowercase with
std::tolower()simplifies the vowel check, as only the five lowercase letters need to be tested. - The program correctly partitions the letters into the
vowelCountandconsonantCountvariables.
Exercise 36: Find Substring
Practice Problem: Write a C++ program to find the first occurrence of a given substring in a given string and print its starting index, or a message if it is not found.
Given:
std::string main_string = "PYnative c++ Exercises";
std::string sub_string = "c++";Code language: C++ (cpp)
Expected Output:
Substring found!
Starting index: 9
+ Hint
- Use the
std::stringmethodfind(). This method takes the substring as an argument and returns the zero-based index of where the match begins. - If the substring is absent, it returns the special value
std::string::npos.
+ Show Solution
#include <iostream>
#include <string>
int main() {
std::string main_string = "PYnative c++ Exercises";
std::string sub_string = "c++";
// Use the find() method
size_t found_index = main_string.find(sub_string);
if (found_index != std::string::npos) {
std::cout << "Substring found!" << std::endl;
std::cout << "Starting index: " << found_index << std::endl;
} else {
std::cout << "Substring not found in the main text." << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
- This exercise is efficiently solved using the built-in
std::string::find()method. - The method returns a
size_tvalue, which is an unsigned integer type used for sizes and indices. If the substring is found,found_indexholds the index. - If it is not found,
found_indexholds the static constantstd::string::npos. Theifstatement checks for this condition to determine the output.
Exercise 37: Frequency of Characters
Practice Problem: Write a C++ program that counts the frequency (number of occurrences) of every unique character in an input string and prints the result only for characters that appeared one or more times. Ignore case and non-alphabetic characters.
Given:
std::string str = "Programming in CPP";Code language: C++ (cpp)
Expected Output:
string: Programming in CPP
Character Frequencies:
'a': 1
'c': 1
'g': 2
'i': 2
'm': 2
'n': 2
'o': 1
'p': 3
'r': 2
+ Hint
- This is an ideal problem for using a Hash Map (
std::unordered_map) or a Map (std::map), where the character is the key and the count is the value. - Iterate through the string, convert each character to lowercase using
std::tolower(), and increment its corresponding count in the map.
+ Show Solution
#include <iostream>
#include <string>
#include <map> // Required for std::map
#include <cctype>
int main() {
std::string str = "Programming in CPP";
std::map<char, int> char_counts;
std::cout << "Analyzing string: " << str << std::endl;
// 1. Iterate through the string and populate the map
for (char c : str) {
if (std::isalpha(c)) {
// Convert to lowercase and use as the map key
char_counts[std::tolower(c)]++;
}
}
// 2. Iterate through the map and print the results
std::cout << "Character Frequencies:" << std::endl;
for (const auto& pair : char_counts) {
std::cout << "'" << pair.first << "': " << pair.second << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
- The
std::map<char, int>container is used to store the frequency. The loop processes the input string character by character. - If a character is a letter (
std::isalpha), it’s converted to lowercase (std::tolower) to ensure case-insensitivity (e.g., ‘A’ and ‘a’ count together). - When a character is used as an index into the map (e.g.,
char_counts['a']++), if the key doesn’t exist, the map automatically inserts it with a default value of 0 before incrementing, making the counting process very concise.
Exercise 38: Matrix Addition (2×2)
Practice Problem: Define two 2×2 integer matrices (two-dimensional arrays), Matrix A and Matrix B. Read the 4 elements of each matrix from the user. Calculate the sum of the two matrices and print the resulting 2×2 matrix, C, where C[i][j] = A[i][j] + B[i][j].
Expected Output:
Enter elements for Matrix A (2x2):
A[0][0]: 10
A[0][1]: 20
A[1][0]: 30
A[1][1]: 40
Enter elements for Matrix B (2x2):
B[0][0]: 5
B[0][1]: 15
B[1][0]: 25
B[1][1]: 35
Resulting Matrix C (A + B):
15 35
55 75
+ Hint
- Declare three 2D arrays:
A[2][2],B[2][2], andC[2][2]. - You will need nested for loops to iterate through the rows (i) and columns (j).
- Use the same set of nested loops to calculate the element-wise sum and print the resulting matrix C.
+ Show Solution
#include <iostream>
int main() {
const int ROWS = 2;
const int COLS = 2;
int A[ROWS][COLS], B[ROWS][COLS], C[ROWS][COLS];
// 1. Read Matrix A
std::cout << "Enter elements for Matrix A (2x2):" << std::endl;
for (int i = 0; i < ROWS; ++i) {
for (int j = 0; j < COLS; ++j) {
std::cout << "A[" << i << "][" << j << "]: ";
std::cin >> A[i][j];
}
}
// 2. Read Matrix B
std::cout << "Enter elements for Matrix B (2x2):" << std::endl;
for (int i = 0; i < ROWS; ++i) {
for (int j = 0; j < COLS; ++j) {
std::cout << "B[" << i << "][" << j << "]: ";
std::cin >> B[i][j];
}
}
// 3. Calculate and Print Matrix C (A + B)
std::cout << "\nResulting Matrix C (A + B):" << std::endl;
for (int i = 0; i < ROWS; ++i) {
for (int j = 0; j < COLS; ++j) {
C[i][j] = A[i][j] + B[i][j];
std::cout << C[i][j] << "\t"; // Use tab for neat alignment
}
std::cout << std::endl; // Newline after each row is complete
}
return 0;
}Code language: C++ (cpp)
Explanation:
- This exercise demonstrates handling multi-dimensional arrays using nested loops.
- The outer loop controls the row index (i), and the inner loop controls the column index (j).
- Matrix addition requires adding corresponding elements, which is performed by the simple element-wise summation
C[i][j] = A[i][j] + B[i][j]within the final set of nested loops.
Exercise 39: Prime Number Check
Practice Problem: Write a program that determines if a given integer N (greater than 1) is a prime number. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
Given:
int N = 23;Code language: C++ (cpp)
Expected Output:
23 is a PRIME number.
+ Hint
- A number N is prime if it is not divisible by any integer from 2 up to sqrt of N (or, for simplicity, up to
N/2). - Use a
forloop starting ati=2. Inside the loop, check if N is divisible by i using the modulo operator (%). - If a divisor is found, set a boolean flag to
trueand immediately exit the loop using thebreakkeyword.
+ Show Solution
#include <iostream>
#include <cmath> // Needed for sqrt()
int main() {
int N = 23;
bool isPrime = true;
if (N <= 1) {
isPrime = false;
} else {
// Only need to check divisors up to the square root of N
for (int i = 2; i <= sqrt(N); ++i) {
if (N % i == 0) {
isPrime = false; // Found a divisor, not prime
break; // Optimization: exit the loop immediately
}
}
}
if (isPrime) {
std::cout << N << " is a PRIME number." << std::endl;
} else {
std::cout << N << " is NOT a prime number." << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
- The program uses a boolean flag
isPrime, initialized totrue. - The loop iterates through potential divisors. If N is divisible by any
i(remainder is 0),isPrimeis set tofalse, andbreakstops the loop, saving computation time. - The use of
sqrt(N)is an optimization technique because any composite number N must have at least one divisor less than or equal to its square root.
Exercise 40: Function Overloading (Area)
Practice Problem: Demonstrate function overloading by creating two separate functions, both named calculateArea.
- The first function should accept a single
doubleargument (radius) and calculate the area of a circle (Area = pi * radius2). - The second function should accept two
doublearguments (length and width) and calculate the area of a rectangle (Area = length * width).
Expected Output:
Area of Circle (Radius 5.0) = 78.5397
Area of Rectangle (8.0 x 4.0) = 32
+ Hint
- Function overloading allows multiple functions with the same name, as long as they have different parameter lists (either the number or the type of parameters differs).
- Use
const double PI = 3.14159;inside your program.
+ Show Solution
#include <iostream>
const double PI = 3.14159;
// 1. Overloaded function for Circle Area (one double argument)
double calculateArea(double radius) {
return PI * radius * radius;
}
// 2. Overloaded function for Rectangle Area (two double arguments)
double calculateArea(double length, double width) {
return length * width;
}
int main() {
// Call the circle area function (Compiler chooses based on one double argument)
std::cout << "Area of Circle (Radius 5.0) = " << calculateArea(5.0) << std::endl;
// Call the rectangle area function (Compiler chooses based on two double arguments)
std::cout << "Area of Rectangle (8.0 x 4.0) = " << calculateArea(8.0, 4.0) << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- Function overloading allows a single function name (
calculateArea) to perform different tasks based on the signature (the number and type of arguments). - The compiler determines which version of the function to execute at compile time based on the arguments provided in the function call. This enhances code clarity by using a common name for related operations.
Exercise 41: Declaration and Dereference
Practice Problem: Declare an integer variable named value and initialize it to 100. Declare an integer pointer named ptr. Assign the memory address of value to ptr. Finally, print the integer stored in value by using only the pointer ptr and the dereference operator.
Expected Output:
The value is: 100
+ Hint
- Use the address-of operator (ampersand:
&) to get the memory location of the variable. - Use the dereference operator (asterisk:
*) to access the data stored at the memory location held by the pointer.
+ Show Solution
#include <iostream>
int main() {
int value = 100;
int* ptr;
// 1. Assign the address of 'value' to 'ptr'
ptr = &value;
// 2. Print the value using the pointer and dereference operator
std::cout << "The value is: " << *ptr << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- The line
int* ptr;declares a pointer variable namedptrthat is designed to hold the memory address of an integer. - The line
ptr = &value;uses the address-of operator (&) to load the actual memory address ofvalueinto the pointerptr. - Finally,
*ptris the dereference operation, which follows the pointer’s address to retrieve the data (the integer 100) stored at that location.
Exercise 42: Pass by Reference (Swap)
Practice Problem: Write a function named swapValues that takes two integer arguments. Implement the swapping logic inside this function. To ensure the original variables in main() are actually changed, the function must use pass by reference. Test the function by printing the values before and after the function call.
Given:
int x = 100;
int y = 200;Code language: C++ (cpp)
Expected Output:
Before swap: x = 100, y = 200
After swap: x = 200, y = 100
+ Hint
- To pass by reference, use the reference operator (
&) in the function parameter list:void swapValues(int &a, int &b). - Inside the function, use the classic three-step swap logic with a temporary variable.
+ Show Solution
#include <iostream>
// Function definition using pass by reference (&)
void swapValues(int &a, int &b) {
int temp = a;
a = b;
b = temp;
// Changes to a and b directly affect the variables passed from main
}
int main() {
int x = 100;
int y = 200;
std::cout << "Before swap: x = " << x << ", y = " << y << std::endl;
// Call the function, passing the variables by reference
swapValues(x, y);
std::cout << "After swap: x = " << x << ", y = " << y << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- Pass by reference (
&) is used here to avoid copying the large variables (though integers are small, the principle holds). - When
swapValuesis called, the variablesaandbinside the function become aliases for the variablesxandyinmain(). - Any modification to
aorbdirectly changes the original variables, allowing the function to successfully swap the values outside its own scope.
Exercise 43: NULL Pointer Check
Practice Problem: Declare an integer pointer named safe_ptr and initialize it to nullptr. Write a conditional statement to check if the pointer is null before attempting to dereference it. If it is null, print “Pointer is null, cannot dereference.” If it is not null, initialize a variable, assign its address to the pointer, and print the dereferenced value.
Expected Output:
Pointer is null, cannot dereference.
Pointer is now valid. Dereferenced value: 77
+ Hint
Always check if a pointer is not nullptr before using the dereference operator (*). Dereferencing a null pointer leads to undefined behavior, often a program crash.
+ Show Solution
#include <iostream>
int main() {
int* safe_ptr = nullptr;
if (safe_ptr == nullptr) {
std::cout << "Pointer is null, cannot dereference." << std::endl;
// Safely assign a valid address for the second check
int valid_data = 77;
safe_ptr = &valid_data;
}
// Now, we can safely check again and dereference if assigned
if (safe_ptr != nullptr) {
std::cout << "Pointer is now valid. Dereferenced value: " << *safe_ptr << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
- The initialization
int* safe_ptr = nullptr;explicitly sets the pointer to a known, invalid state. The firstifstatement checks this state usingsafe_ptr == nullptr. - This is a crucial safety check to prevent crashes. The second part demonstrates assigning a valid address (
&valid_data) and then safely using the pointer only after verifying it’s no longer null.
Exercise 44: Pointer-to-Pointer (Double Pointer)
Practice Problem: Declare an integer variable x initialized to 42. Declare an integer pointer p1 that points to x. Declare a double integer pointer (pointer to a pointer) p2 that points to p1. Access and print the initial value of x using the double pointer p2.
Expected Output:
The value accessed via double pointer is: 42
+ Hint
A double pointer requires two asterisks (**) in its declaration. To access the final value, you will need to apply the dereference operator (*) twice
+ Show Solution
#include <iostream>
int main() {
int x = 42;
int* p1 = &x; // p1 points to x
int** p2 = &p1; // p2 points to p1
// Access the value of x using the double pointer p2
std::cout << "The value accessed via double pointer is: " << **p2 << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- The pointer
p1holds the address ofx. The double pointerp2holds the address ofp1. - The expression
*p2dereferencesp2, which results in the content ofp1(the address ofx). - The expression
**p2then dereferences this result (the address ofx), which finally gives us the integer value 42 stored inx. - This structure is used in more complex data structures or when implementing pass-by-reference for pointers.
Exercise 45: Structure with Function
Practice Problem: Define a structure named Student with the following members: std::string name, int rollNumber, and double marks.
Write two functions:
readStudentData: Takes aStudentstructure variable as a reference argument and populates its members from user input.printStudentData: Takes aStudentstructure variable as a constant reference argument and prints its members. Use these functions inmain()to manage the student data.
Expected Output:
Enter student name: Jessa
Enter roll number: 24
Enter marks: 78
--- Student Record ---
Name:
Roll Number: 24
Marks: 78
+ Hint
- Pass the structure by reference (
Student &s) in the reading function so changes are permanent. - Pass the structure by constant reference (
const Student &s) in the printing function to avoid unnecessary copying and guarantee the function won’t change the data.
+ Show Solution
#include <iostream>
#include <string>
#include <limits>
// Structure definition
struct Student {
std::string name;
int rollNumber;
double marks;
};
// Function 1: Pass by reference to modify the original structure
void readStudentData(Student &s) {
std::cout << "Enter student name: ";
// Use cin.ignore() to clear potential newline character from previous inputs
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::getline(std::cin, s.name);
std::cout << "Enter roll number: ";
std::cin >> s.rollNumber;
std::cout << "Enter marks: ";
std::cin >> s.marks;
}
// Function 2: Pass by constant reference for efficiency and safety
void printStudentData(const Student &s) {
std::cout << "\n--- Student Record ---" << std::endl;
std::cout << "Name: " << s.name << std::endl;
std::cout << "Roll Number: " << s.rollNumber << std::endl;
std::cout << "Marks: " << s.marks << std::endl;
}
int main() {
Student s1;
readStudentData(s1);
printStudentData(s1);
return 0;
}Code language: C++ (cpp)
Explanation:
- By passing the structure by reference (
Student &s), thereadStudentDatafunction can modify thes1variable inmain()without creating a copy. - Passing by constant reference (
const Student &s) inprintStudentDataensures that the function is efficient (no copy) and read-only (guaranteed byconst).
Exercise 46: Pointers (Basic)
Practice Problem: eclare an integer variable named value and initialize it. Declare a pointer variable named ptr that is designed to hold the memory address of an integer. Store the address of value in ptr. Print the following
- The value of
value. - The memory address of
value(using the address-of operator&). - The address stored in
ptr. - The value pointed to by
ptr(using the dereference operator*).
Expected Output:
1. Value of the variable 'value': 42
2. Memory address of 'value' (&value): 0x7ffd8b641d34
3. Address stored in pointer 'ptr': 0x7ffd8b641d34
4. Value pointed to by 'ptr' (*ptr): 42
New value of 'value' after *ptr = 99: 99
+ Hint
- Use the syntax
int *ptr;to declare the pointer. Use the address-of operator (&) to get the address ofvalue:ptr = &value;. - Use the dereference operator (
*) to access the value at the address:*ptr.
+ Show Solution
#include <iostream>
int main() {
int value = 42;
int *ptr; // Declare an integer pointer
// Store the address of 'value' into 'ptr'
ptr = &value;
std::cout << "1. Value of the variable 'value': " << value << std::endl;
std::cout << "2. Memory address of 'value' (&value): " << &value << std::endl;
std::cout << "3. Address stored in pointer 'ptr': " << ptr << std::endl;
std::cout << "4. Value pointed to by 'ptr' (*ptr): " << *ptr << std::endl;
// Demonstrate dereference operation modifies the original value
*ptr = 99;
std::cout << "\nNew value of 'value' after *ptr = 99: " << value << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- This exercise introduces pointers, which are variables that store memory addresses. The address-of operator (
&) retrieves the address. - The dereference operator (
*) accesses the data stored at the address pointed to by the pointer. - The output shows that
&valueandptrhold the same memory address, andvalueand*ptrhold the same data value.
Exercise 47: Pointer Arithmetic
Practice Problem: Declare an integer array of size 3 and initialize it. Declare an integer pointer and initialize it to point to the first element of the array. Demonstrate basic pointer arithmetic by performing the following:
- Print the value and address of the first element using the pointer.
- Increment the pointer by 1
- Print the value and address of the next element using the incremented pointer.
Expected Output:
--- Initial State (arr[0]) ---
Value: 10 (arr[0])
Address: 0x7ffc27702dbc
--- After ptr = ptr + 1 (arr[1]) ---
Value: 20 (arr[1])
Address: 0x7ffc27702dc0
Address jump size (bytes): 4
+ Hint
When you increment an integer pointer by 1, it doesn’t move 1 byte forward; it moves forward by sizeof(int) bytes, automatically pointing to the next array element. Use array indexing to confirm the value change.
+ Show Solution
#include <iostream>
int main() {
int arr[3] = {10, 20, 30};
int *ptr = arr; // Pointer points to the first element (arr[0])
// 1. First element
std::cout << "--- Initial State (arr[0]) ---" << std::endl;
std::cout << "Value: " << *ptr << " (arr[0])" << std::endl;
std::cout << "Address: " << ptr << std::endl;
// 2. Increment the pointer by 1
ptr = ptr + 1;
// 3. Second element (after arithmetic)
std::cout << "\n--- After ptr = ptr + 1 (arr[1]) ---" << std::endl;
std::cout << "Value: " << *ptr << " (arr[1])" << std::endl;
std::cout << "Address: " << ptr << std::endl;
// Confirmation of address jump size (for explanation)
std::cout << "\nAddress jump size (bytes): " << sizeof(int) << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- Pointer arithmetic works based on the size of the data type the pointer is pointing to.
- When
ptris incremented by 1, the compiler addssizeof(int)bytes (usually 4 bytes) to the memory address stored inptr, causing it to correctly move from the address ofarr[0]to the address ofarr[1]. This is essential for iterating over arrays efficiently using pointers.
Exercise 48: Array of Structures (Books)
Practice Problem: Declare an array capable of storing information for 3 Book structures. Write a program to loop through the array, prompting the user to input the data (title, author, price) for each of the 3 books. Finally, loop through the array again to display the data for all 3 books.
Expected Output:
--- Enter data for Book 1 ---
Title: The C++ Programming Language
Author: Bjarne Stroustrup
Price: $10
--- Enter data for Book 2 ---
Title: Programming In C++
Author: Ashok N. Kamthane
Price: $9
--- Enter data for Book 3 ---
Title: C++ How To Program
Author: Paul Deitel & Harvey Deitel
Price: $11
===================================
ALL BOOKS INVENTORY
===================================
Book 1: The C++ Programming Language by Bjarne Stroustrup ($10)
Book 2: Programming In C++ by Ashok N. Kamthane ($9)
Book 3: C++ How To Program by Paul Deitel & Harvey Deitel ($11)
+ Hint
- Use a
forloop that iterates from 0 to 2. Inside the loop, you can access the members of the current book using array notation (e.g.,books[i].title). - You will need to handle the input buffer carefully if mixing
std::cinandstd::getlinein a loop by usingstd::cin.ignore().
+ Show Solution
#include <iostream>
#include <string>
#include <limits>
struct Book {
std::string title;
std::string author;
float price;
};
const int MAX_BOOKS = 3;
int main() {
Book books[MAX_BOOKS];
// Input loop
for (int i = 0; i < MAX_BOOKS; ++i) {
std::cout << "\n--- Enter data for Book " << i + 1 << " ---" << std::endl;
// Clear the input buffer if necessary from previous numeric input
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Title: ";
std::getline(std::cin, books[i].title);
std::cout << "Author: ";
std::getline(std::cin, books[i].author);
std::cout << "Price: $";
std::cin >> books[i].price;
}
// Output loop
std::cout << "\n===================================" << std::endl;
std::cout << " ALL BOOKS INVENTORY " << std::endl;
std::cout << "===================================" << std::endl;
for (int i = 0; i < MAX_BOOKS; ++i) {
std::cout << "Book " << i + 1 << ": " << books[i].title
<< " by " << books[i].author
<< " ($" << books[i].price << ")" << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
- An array of structures is a common way to manage collections of records.
- The
books[MAX_BOOKS]declaration creates a contiguous block of memory to store 3Bookobjects. - The
forloops iterate over the array, using the indexito access each individual book structure. The members are accessed via the dot operator applied to the array element, e.g.,books[i].title.
Exercise 49: Basic Enum (Days of the Week)
Practice Problem: Define an enumeration named Day for the days of the week, starting with Sunday and ending with Saturday. Write a program to declare a variable of type Day, assign it the value Wednesday, and then print the underlying integer value of that day to the console.
Expected Output:
The integer value of Wednesday is: 3
+ Hint
- By default, the first enumerator (
Sunday) is assigned 0, and each subsequent enumerator increments by 1. - You do not need to explicitly assign values unless you want to change this default behavior. When printing the enum value, you may need to cast it to an
int.
+ Show Solution
#include <iostream>
// Define the Day enumeration
enum Day {
Sunday, // 0
Monday, // 1
Tuesday, // 2
Wednesday, // 3
Thursday, // 4
Friday, // 5
Saturday // 6
};
int main() {
// Declare a variable and assign a value
Day today = Wednesday;
std::cout << "The integer value of Wednesday is: ";
// Cast the enum variable to an int to print its underlying value
std::cout << static_cast<int>(today) << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- C-style enumerations (
enum) provide a set of named integer constants. - By default, the constants are assigned values sequentially starting from 0.
- The program demonstrates declaration, assignment, and the use of
static_cast<int>to explicitly retrieve and print the integer value associated with the enumeratorWednesday(which is 3).
Exercise 50: Car Class With Attributes and Simple Behavior
Practice Problem: Create a Car class with public attributes std::string make, std::string model, and int year. Implement a public method start_engine() that simply prints the message: “[Year] [Make] [Model] engine started!”.
Expected Output:
2020 Toyota Corolla engine started!
+ Hint
For simplicity, use public attributes. The method should utilize the object’s own attributes within the print statement
+ Show Solution
#include <iostream>
#include <string>
class Car {
public:
std::string make;
std::string model;
int year;
// Constructor for easy initialization
Car(std::string mk, std::string md, int yr)
: make(mk), model(md), year(yr) {}
// Method demonstrating a simple action/behavior
void start_engine() {
std::cout << year << " " << make << " " << model << " engine started!" << std::endl;
}
};
int main() {
Car my_car("Toyota", "Corolla", 2020);
// Demonstrate interaction with attributes and method
std::cout << "My car is a " << my_car.year << " " << my_car.make << "." << std::endl;
my_car.start_engine();
return 0;
}Code language: C++ (cpp)
Explanation:
This exercise shows a basic OOP concept where an object models a real-world entity.
- The attributes (
make,model,year) describe the car’s state, and the method (start_engine) describes its capability or action. - Since the attributes are public in this case, they can be directly accessed and modified outside the class (though this is often discouraged in favor of encapsulation).
Exercise 51: Default/Parameterized Constructor
Practice Problem: Implement the Rectangle class (from Exercise 1). This time, include two public constructors: a default constructor that sets both length and width to 1, and a parameterized constructor that allows setting custom values for length and width.
Expected Output:
Custom Rectangle created (12x4).
R1 Area: 48
Default Rectangle created (1x1).
R2 Area: 1
+ Hint
- Define two public constructors. It called a constructor overloading (the concept of having multiple constructors).
- The default constructor takes no arguments.
- The parameterized constructor takes two arguments.
+ Show Solution
#include <iostream>
class Rectangle {
private:
int length;
int width;
public:
// 1. Default Constructor (no arguments)
Rectangle() : length(1), width(1) {
std::cout << "Default Rectangle created (1x1)." << std::endl;
}
// 2. Parameterized Constructor
Rectangle(int l, int w) : length(l), width(w) {
std::cout << "Custom Rectangle created (" << length << "x" << width << ")." << std::endl;
}
int get_area() const {
return length * width;
}
};
int main() {
// Uses the Parameterized Constructor
Rectangle r1(12, 4);
std::cout << "R1 Area: " << r1.get_area() << std::endl;
// Uses the Default Constructor
Rectangle r2;
std::cout << "R2 Area: " << r2.get_area() << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- This demonstrates Constructor Overloading, a form of Static Polymorphism.
- The compiler selects the correct constructor based on the number and type of arguments provided during object creation.
- A default constructor is essential for creating objects when no initial values are specified (e.g., in arrays or STL containers).
Exercise 52: Destructor Demonstration
Practice Problem: Create a simple class, e.g., Resource, with a private member std::string id which models acquiring and releasing a resource. Implement a constructor that prints “Resource [ID] acquired” and a destructor that prints “Resource [ID] released”. Use a local object inside a function to clearly show when the destructor is called.
+ Hint
The destructor is defined using the tilde (~) character followed by the class name (e.g., ~Resource()). It is automatically called when the object goes out of scope.
+ Show Solution
#include <iostream>
#include <string>
class Resource {
private:
std::string id;
public:
// Constructor
Resource(std::string name) : id(name) {
std::cout << ">> Resource '" << id << "' ACQUIRED (Constructed)" << std::endl;
}
// Destructor
~Resource() {
std::cout << "<< Resource '" << id << "' RELEASED (Destructed)" << std::endl;
}
};
void scope_test() {
std::cout << "\n--- Entering scope_test() ---" << std::endl;
Resource local_res("Local A"); // Object created
std::cout << "--- Exiting scope_test() ---" << std::endl;
// local_res is destroyed here
}
int main() {
std::cout << "--- Starting main() ---" << std::endl;
Resource main_res("Main B"); // Object created
scope_test();
std::cout << "--- Ending main() ---" << std::endl;
// main_res is destroyed here
return 0;
}Code language: C++ (cpp)
Explanation:
The Destructor (~Classname) is a special member function that is automatically called when an object’s lifetime ends, which occurs when it goes out of scope (as seen in scope_test() and main()):
- Its primary purpose is cleanup. It ensures that any dynamically allocated memory or external resources (files, network connections, etc.) are properly cleaned up when the object is no longer needed.
- This is fundamental to C++’s powerful RAII (Resource Acquisition Is Initialization) paradigm, which prevents memory leaks and resource exhaustion by tying resource lifetime to object lifetime.
Exercise 53: Create and Write
Practice Problem: Practice Problem Write a program to create a new text file named mydata.txt. Open the file for output and write the single line of text Hello, File Handling! into it. Ensure the program handles the closing of the file stream properly.
Expected Output:
Successfully wrote data to mydata.txt
mydata.txt File content:
Hello, File Handling!
+ Hint
- Use the
std::ofstreamclass, which is specialized for writing to files. - The file is created automatically if it does not exist when you declare the
ofstreamobject with the filename. - You can use the insertion operator
<<just like you do withstd::cout.
+ Show Solution
#include <fstream>
#include <iostream>
#include <string>
int main() {
// 1. Declare an output file stream object
std::ofstream outFile;
// 2. Open the file (creates it if it doesn't exist)
outFile.open("mydata.txt");
// 3. Check if the file was successfully opened
if (outFile.is_open()) {
// 4. Write data to the file
outFile << "Hello, File Handling!" << std::endl;
std::cout << "Successfully wrote data to mydata.txt" << std::endl;
// 5. Close the file stream
outFile.close();
} else {
std::cerr << "Unable to open file mydata.txt" << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
- This exercise introduces the file writing:
std::ofstream. We declare an object,outFile, and call itsopen()method with the desired filename. - The crucial step is the error check using
is_open(); if this fails, the program reports an error. - The output is written using the standard stream insertion operator
<<. - Finally,
outFile.close()is called to flush any remaining buffer data and release the file handle back to the operating system.
Exercise 54: Read and Display
Practice Problem: Read the entire content from the existing file mydata.txt (created in Exercise 1) and display it line by line on the console. Report an error if the file cannot be opened.
Expected Output:
--- Content of mydata.txt ---
Hello, File Handling!
+ Hint
- Use the
std::ifstreamclass for reading. - A common way to read line by line is to use the
std::getline()function, which takes the file stream and astd::stringvariable as arguments, and reads until a newline character is encountered.
+ Show Solution
#include <fstream>
#include <iostream>
#include <string>
int main() {
// 1. Declare an input file stream object
std::ifstream inFile("mydata.txt");
std::string fileLine;
// 2. Check if the file was successfully opened
if (inFile.is_open()) {
std::cout << "--- Content of mydata.txt ---" << std::endl;
// 3. Read the file line by line
while (std::getline(inFile, fileLine)) {
// 4. Display the read line
std::cout << fileLine << std::endl;
}
// 5. Close the file stream
inFile.close();
} else {
// 6. Report error if file opening failed
std::cerr << "Error: Unable to open file mydata.txt for reading." << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
The std::ifstream object, inFile, is used to read the data.
The core reading loop uses while (std::getline(inFile, fileLine)). The std::getline() function attempts to read an entire line into the fileLine string. This function returns a reference to the stream object, which evaluates to true if the read was successful and false (terminating the loop) if the end-of-file (EOF) is reached or an error occurs. This is the idiomatic way to process text files line by line in C++.
Exercise 55: Append to File
Practice Problem: Write a program to open the existing file mydata.txt and append the line This is the appended text. to the end of the file. The original content should remain intact.
Expected Output:
Successfully appended text to mydata.txt
mydata.txt content:
Hello, File Handling!
This is the appended text.
+ Hint
When opening the file using std::ofstream, you need to specify the append file mode using std::ios::app. This ensures that any new data written will be placed at the current end of the file.
+ Show Solution
#include <fstream>
#include <iostream>
int main() {
// 1. Declare an output file stream and open in append mode
std::ofstream outFile("mydata.txt", std::ios::app);
// 2. Check for successful opening
if (outFile.is_open()) {
// 3. Append the new line
outFile << "This is the appended text." << std::endl;
std::cout << "Successfully appended text to mydata.txt" << std::endl;
// 4. Close the file stream
outFile.close();
} else {
std::cerr << "Unable to open file mydata.txt for appending." << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
- The key change here is the use of the second argument in the
ofstreamconstructor:std::ios::app. This file mode flag modifies the behavior of the stream so that all output operations are performed at the end of the file, preserving the previous content. - If this flag were omitted, the default behavior would be to truncate (delete) the file content and start writing from the beginning.
Exercise 56: Count Characters
Practice Problem: Read the content of the file mydata.txt and count the total number of characters it contains. Display the final count on the console. Newline characters should also be counted.
Expected Output:
Total number of characters in mydata.txt: 49
+ Hint
- Read the file character by character using the
get()method of theifstreamobject. - The loop continues as long as the stream is successfully reading characters.
+ Show Solution
#include <fstream>
#include <iostream>
int main() {
std::ifstream inFile("mydata.txt");
char character;
int charCount = 0;
if (inFile.is_open()) {
// Read character by character until the end of the file
while (inFile.get(character)) {
charCount++;
}
std::cout << "Total number of characters in mydata.txt: " << charCount << std::endl;
inFile.close();
} else {
std::cerr << "Error: Unable to open file." << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
- This program uses a
whileloop withinFile.get(character). Theget()method attempts to extract a single character (including whitespace and newline characters) and store it in thecharactervariable. - If the extraction is successful, the stream object evaluates to
true, the loop continues, and thecharCountis incremented. When the end of the file is reached or an error occurs, the stream evaluates tofalse, and the loop terminates.
Exercise 57: Count Lines
Practice Problem: Read the content of the file mydata.txt and count the total number of lines present in the file. Display the final count on the console. An empty file should have a line count of 0.
Expected Output:
Total number of lines in mydata.txt: 2
+ Hint
- Use the
std::getline()function within a loop. - Since
getline()reads until a newline, every successful call to it represents one line counted.
+ Show Solution
#include <fstream>
#include <iostream>
#include <string>
int main() {
std::ifstream inFile("mydata.txt");
std::string line;
int lineCount = 0;
if (inFile.is_open()) {
// Use getline() to read line by line
while (std::getline(inFile, line)) {
lineCount++;
}
std::cout << "Total number of lines in mydata.txt: " << lineCount << std::endl;
inFile.close();
} else {
std::cerr << "Error: Unable to open file." << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
- This solution leverages the behavior of
std::getline(). Each timestd::getline()successfully reads a sequence of characters up to a newline and stores it in thelinestring, thelineCountis incremented. - The loop naturally terminates when the end of the file is reached. This is the most efficient and standard way to count lines in a text file using C++ streams.
