Examples of problems and solutions in C++
Problem 1.
Singly linked list. Implement a list of strings. Write functions to count the number of words in the list:
a. beginning and ending with the same letter
b. beginning with the same letter as the next word
c. matching the last word.
Solution:
Here is a C++ implementation of a singly linked list storing strings, along with the three counting functions.
C++
#include <iostream>
#include <string>
#include <cctype>
struct Node {
std::string word;
Node* next;
Node(const std::string& val) : word(val), next(nullptr) {}
};
class StringLinkedList {
private:
Node* head;
public:
StringLinkedList() : head(nullptr) {}
~StringLinkedList() {
Node* current = head;
while (current != nullptr) {
Node* temp = current;
current = current->next;
delete temp;
}
}
void append(const std::string& word) {
Node* newNode = new Node(word);
if (head == nullptr) {
head = newNode;
return;
}
Node* current = head;
while (current->next != nullptr) {
current = current->next;
}
current->next = newNode;
}
// Helper: Normalize character for case-insensitive comparison
char toLowerChar(char ch) const {
return std::tolower(static_cast<unsigned char>(ch));
}
// a. Count words beginning and ending with the same letter
int countSameStartAndEnd() const {
int count = 0;
Node* current = head;
while (current != nullptr) {
const std::string& word = current->word;
if (!word.empty()) {
char firstChar = toLowerChar(word.front());
char lastChar = toLowerChar(word.back());
if (firstChar == lastChar) {
count++;
}
}
current = current->next;
}
return count;
}
// b. Count words beginning with the same letter as the next word
int countSameStartAsNext() const {
int count = 0;
Node* current = head;
while (current != nullptr && current->next != nullptr) {
const std::string& currWord = current->word;
const std::string& nextWord = current->next->word;
if (!currWord.empty() && !nextWord.empty()) {
char currFirst = toLowerChar(currWord.front());
char nextFirst = toLowerChar(nextWord.front());
if (currFirst == nextFirst) {
count++;
}
}
current = current->next;
}
return count;
}
// c. Count words matching the last word in the list
int countMatchingLastWord() const {
if (head == nullptr) return 0;
// Find the last node
Node* current = head;
while (current->next != nullptr) {
current = current->next;
}
std::string lastWord = current->word;
// Count occurrences matching the last word
int count = 0;
current = head;
while (current != nullptr) {
if (current->word == lastWord) {
count++;
}
current = current->next;
}
return count;
}
};
int main() {
StringLinkedList list;
// Example words: "radar", "apple", "anaconda", "banana", "boat", "apple"
list.append("radar");
list.append("apple");
list.append("anaconda");
list.append("banana");
list.append("boat");
list.append("apple");
std::cout << "a. Beginning and ending with same letter: "
<< list.countSameStartAndEnd() << " (e.g., radar, anaconda)\n";
std::cout << "b. Beginning with same letter as next word: "
<< list.countSameStartAsNext() << " (e.g., apple->anaconda, banana->boat)\n";
std::cout << "c. Matching the last word (\"apple\"): "
<< list.countMatchingLastWord() << " (first and last node)\n";
return 0;
}
Explanation of the Functions
countSameStartAndEnd(): Iterates through each node, converts the first (word.front()) and last (word.back()) characters to lowercase, and increments the count if they match.countSameStartAsNext(): Uses lookahead (current->next) to compare the initial character ofcurrent->wordwith the initial character ofcurrent->next->word. It stops at the second-to-last node.countMatchingLastWord(): Operates in two passes over the list—the first pass traverses to the tail to fetch the target string, and the second pass counts how many nodes contain exact string matches to that target (including the last node itself).
The output produced by executing the C++ code above:
Plaintext
a. Beginning and ending with same letter: 2 (e.g., radar, anaconda)
b. Beginning with same letter as next word: 2 (e.g., apple->anaconda, banana->boat)
c. Matching the last word ("apple"): 2 (first and last node)
Breakdown of the Results
a. Same start & end letter:
"radar"(starts and ends with ‘r’) → Match"apple"(starts with ‘a’, ends with ‘e’)"anaconda"(starts and ends with ‘a’) → MatchTotal = 2
b. Same start letter as the next word:
"apple"(‘a’) →"anaconda"(‘a’) → Match"banana"(‘b’) →"boat"(‘b’) → MatchTotal = 2
c. Matches the last word (
"apple"):Node 1 (
"apple") and Node 6 ("apple")Total = 2
Alternatively:
Below is a complete C++ implementation using a singly linked list of strings. It includes separate functions for all three requirements.
#include <iostream>
#include <string>
using namespace std;
// Node structure
struct Node {
string word;
Node* next;
Node(string w) {
word = w;
next = nullptr;
}
};
// Insert a word at the end of the list
void insertEnd(Node*& head, string word) {
Node* newNode = new Node(word);
if (head == nullptr) {
head = newNode;
return;
}
Node* temp = head;
while (temp->next != nullptr) {
temp = temp->next;
}
temp->next = newNode;
}
// Display the list
void display(Node* head) {
Node* temp = head;
while (temp != nullptr) {
cout << temp->word << " -> ";
temp = temp->next;
}
cout << "NULL" << endl;
}
// a. Count words beginning and ending with the same letter
int countSameFirstLast(Node* head) {
int count = 0;
Node* temp = head;
while (temp != nullptr) {
if (!temp->word.empty() &&
temp->word.front() == temp->word.back()) {
count++;
}
temp = temp->next;
}
return count;
}
// b. Count words beginning with the same letter as the next word
int countSameAsNext(Node* head) {
int count = 0;
Node* temp = head;
while (temp != nullptr && temp->next != nullptr) {
if (!temp->word.empty() &&
!temp->next->word.empty() &&
temp->word.front() == temp->next->word.front()) {
count++;
}
temp = temp->next;
}
return count;
}
// c. Count words matching the last word
int countMatchingLastWord(Node* head) {
if (head == nullptr)
return 0;
// Find the last word
Node* last = head;
while (last->next != nullptr) {
last = last->next;
}
string lastWord = last->word;
int count = 0;
// Compare every word with the last word
Node* temp = head;
while (temp != nullptr) {
if (temp->word == lastWord) {
count++;
}
temp = temp->next;
}
return count;
}
// Main function
int main() {
Node* head = nullptr;
// Create the list
insertEnd(head, "level");
insertEnd(head, "apple");
insertEnd(head, "ant");
insertEnd(head, "area");
insertEnd(head, "level");
insertEnd(head, "banana");
insertEnd(head, "level");
cout << "Singly Linked List:" << endl;
display(head);
// a
cout << "\na. Words beginning and ending with the same letter: "
<< countSameFirstLast(head) << endl;
// b
cout << "b. Words beginning with the same letter as the next word: "
<< countSameAsNext(head) << endl;
// c
cout << "c. Words matching the last word: "
<< countMatchingLastWord(head) << endl;
return 0;
}How the three functions work
a. Beginning and ending with the same letter
For each word, compare its first and last characters:
temp->word.front() == temp->word.back()For example, level qualifies because it starts with l and ends with l.
b. Beginning with the same letter as the next word
Compare the first letter of the current node with the first letter of the next node:
temp->word.front() == temp->next->word.front()For example:
apple -> ant
a aSo apple is counted.
The last node isn’t checked because it has no next word.
c. Matching the last word
First, traverse the list to find the last node:
while (last->next != nullptr) {
last = last->next;
}Then compare every word with that last word:
if (temp->word == lastWord)
count++;The output of the provided C++ program is:
Singly Linked List:
level -> apple -> ant -> area -> level -> banana -> level -> NULL
a. Words beginning and ending with the same letter: 4
b. Words beginning with the same letter as the next word: 2
c. Words matching the last word: 3
In the example, the last word is level, and level occurs 3 times, so the result for (c) is 3.
Problem 2.
Two-dimensional array. The characteristic of a column of an integer matrix is the sum of the absolute values of its negative odd elements. By permuting the columns of the given matrix, arrange them in increasing order of their characteristics.
Solution:
simple C++ solution for the two-dimensional array problem.
Idea
For every column:
- Look through all its elements.
- Select elements that are:
- negative (
x < 0) - odd (
x % 2 != 0)
- negative (
- Add their absolute values to get the column’s characteristic.
- Sort the columns in increasing order of these characteristics.
For example, if a column contains:
2
-3
-5
4its characteristic is:
|-3| + |-5| = 3 + 5 = 8C++ Program
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
const int MAX = 100;
// Structure to store a column and its characteristic
struct Column {
int values[MAX];
int characteristic;
};
// Calculate the characteristic of a column
int getCharacteristic(int column[], int rows) {
int sum = 0;
for (int i = 0; i < rows; i++) {
// Negative and odd
if (column[i] < 0 && column[i] % 2 != 0) {
sum += abs(column[i]);
}
}
return sum;
}
// Swap two columns
void swapColumns(int matrix[][MAX], int rows, int col1, int col2) {
for (int i = 0; i < rows; i++) {
swap(matrix[i][col1], matrix[i][col2]);
}
}
int main() {
int rows, cols;
int matrix[MAX][MAX];
cout << "Enter number of rows: ";
cin >> rows;
cout << "Enter number of columns: ";
cin >> cols;
cout << "Enter the matrix elements:\n";
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cin >> matrix[i][j];
}
}
// Calculate characteristics
int characteristic[MAX];
for (int j = 0; j < cols; j++) {
int sum = 0;
for (int i = 0; i < rows; i++) {
if (matrix[i][j] < 0 && matrix[i][j] % 2 != 0) {
sum += abs(matrix[i][j]);
}
}
characteristic[j] = sum;
}
// Sort columns according to their characteristics
for (int i = 0; i < cols - 1; i++) {
for (int j = 0; j < cols - i - 1; j++) {
if (characteristic[j] > characteristic[j + 1]) {
// Swap characteristics
swap(characteristic[j], characteristic[j + 1]);
// Swap the corresponding columns
swapColumns(matrix, rows, j, j + 1);
}
}
}
// Display characteristics
cout << "\nCharacteristics of columns in increasing order:\n";
for (int j = 0; j < cols; j++) {
cout << characteristic[j] << " ";
}
// Display sorted matrix
cout << "\n\nMatrix after sorting columns:\n";
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << matrix[i][j] << "\t";
}
cout << endl;
}
return 0;
}Example
Suppose the input matrix is:
1 -3 4 -7
-5 2 -9 6
8 -1 3 -2The characteristics are:
- Column 1:
|-5| = 5 - Column 2:
|-3| + |-1| = 4 - Column 3:
|-9| = 9 - Column 4:
|-7| = 7
Therefore:
4, 5, 7, 9The columns are rearranged according to that order.
Important: when swapping the characteristic values, we must also swap the entire corresponding columns of the matrix. This is what swapColumns() does.
Problem 3.
Implement a calculator in C++ capable of performing four arithmetic operations. Prompt the user for arguments and the operation sign (symbol). Loop the program—after displaying the result, prompt the user to perform the calculation again. Exit the program by pressing the q key. Perform checks: 1) division by zero (in this case, display a warning message and prompt for the divisor again); 2) correct entry of the operation sign (in this case, prompt the user to enter the correct operation sign).
Solution:
A simple C++ calculator that performs addition, subtraction, multiplication, and division, with both required checks.
#include <iostream>
using namespace std;
int main() {
double a, b, result;
char operation;
char again;
do {
cout << "\nEnter first number: ";
cin >> a;
// Get a valid operation sign
while (true) {
cout << "Enter operation (+, -, *, /): ";
cin >> operation;
if (operation == '+' || operation == '-' ||
operation == '*' || operation == '/') {
break;
}
cout << "Invalid operation! Please enter +, -, * or /.\n";
}
// Get the second number
cout << "Enter second number: ";
cin >> b;
// Check division by zero
while (operation == '/' && b == 0) {
cout << "Warning: Division by zero is not allowed!\n";
cout << "Enter the divisor again: ";
cin >> b;
}
// Perform the calculation
switch (operation) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
result = a / b;
break;
}
cout << "Result = " << result << endl;
// Ask whether to continue
cout << "\nPress any key to calculate again, or q to quit: ";
cin >> again;
} while (again != 'q' && again != 'Q');
cout << "Calculator closed. Goodbye!\n";
return 0;
}Example
Enter first number: 20
Enter operation (+, -, *, /): /
Enter second number: 0
Warning: Division by zero is not allowed!
Enter the divisor again: 5
Result = 4
Press any key to calculate again, or q to quit: y
Enter first number: 10
Enter operation (+, -, *, /): *
Enter second number: 3
Result = 30
Press any key to calculate again, or q to quit: q
Calculator closed. Goodbye!How the checks work
1. Division by zero
while (operation == '/' && b == 0) {
cout << "Warning: Division by zero is not allowed!\n";
cout << "Enter the divisor again: ";
cin >> b;
}The program keeps asking for the divisor until the user enters a non-zero value.
2. Invalid operation sign
while (true) {
cin >> operation;
if (operation == '+' || operation == '-' ||
operation == '*' || operation == '/') {
break;
}
cout << "Invalid operation!\n";
}The program accepts only +, -, *, and /.
3. Exit with q
} while (again != 'q' && again != 'Q');The calculator continues until the user enters q or Q.
Problem 4.
Working with strings. The input is an array of strings and its length. Each string has the form “Last Name First Name Middle Name” (separated by a single space). The function should return a new array consisting of strings of the form “First Name Last Name”.
Solution:
Explore More IT Terms
#
- Using an integrating factor
- Equations in total differentials
- Bernoulli's equation
- Linear differential equations of the first order
- 10 Mixed C++ Challenges to Test Your Skills
- 11 Tricky Non-Technical Questions to Ask in a Recruiting Interview
- 50 Terms Every Programmer Should Know
- 52 Java Thread Interview Questions
- 7 Levels of Using the Zip Function in Python
- 7 Python Code Bugs You Need to Fix
- 70+ Free Resources for Learning Programming
A
- A Comprehensive Guide to HTML and CSS
- A Comprehensive Guide to MODX CMS
- A computer science question tests your ability to work with IP addresses and network masks
- A Guide to SQL Query Formatting for Beginners
- A/B testing
- Abstract Data Type (ADT)
- AES Encryption Algorithm: How It Works and Where It's Used
- Agile
- Algorithm
- Algorithm Analysis
- Algorithm Complexity-Key Points
- Algorithm complexity: deep parsing O(log n)
- Algorithm vs. Program
- Algorithms and Data Structures in C#
- An overview of the C # programming language
- An overview of the Python programming language
- Anaconda Python
- Analysis of graphs and adjacency matrices question
- Android
- Android App Bundle
- Android SDK
- Angular
- Ansible
- Apache
- Apache Airflow
- Apache Kafka
- Apache Tomcat
- App Store
- AppCode
- Applications of microcontrollers: From simple circuits in electronics to complex systems
- Applications of the derivative
- Arduino: How to Program It: Basics for Beginners
- Array-based stack
- ArrayList
- ASCII
- ASP.NET
- Assembly Language Lessons
B
C
- C++ Lessons
- Cache
- Calculating Memory Capacity
- Character sets and encodings
- Characteristics of a good Algorithm
- Circular singly linked list
- Combinational Circuits Solved Questions
- Compiler
- Complexity of algorithms-Tutorial
- Constants
- Creating a Table in HTML
- Creating Forms in HTML
- Creating Lists
- Cybernetics and informatics
- Cycles
D
- Data Analytics: applications of data analysis in companies
- Data Engineer - Who is it, what does a data engineer do, and an overview of the profession
- Data modeling: what it is, types, and process steps.
- Data preprocessing: a complete guide for beginners and professionals.
- Data structure
- Data Structures and Algorithms (DSA)
- Data types vs. Data structures
- Database Tests with Answers
- Deep Learning
- Defining Aliases
- Defining Arrays
- Deque
- Detailed articles and tutorials on PHP
- Developing a Website from Scratch
- Differential Equations
- Differentiation of functions
- Digital data: understand the importance of this asset for businesses.
- Double integrals
- Doubly linked lists
- DSA Tutorial
E
F
G
H
- Handling errors and exceptions
- Heads or Tails? How Probability Theory Is Used in IT
- History of the development of computer science
- Homogeneous equations
- Homogeneous vs. non-homogeneous structures
- How to effectively organize your workflow
- How to Learn Java: Tips for Beginner Developers
- How to Learn PHP: A Beginner's Guide
- How to Use S3 Storage in Kubernetes with CSI
- HTML
- HTML and CSS: Definition, Application, and Operating Principles
- HTML and CSS. Layout from Scratch: What to Learn, Where to Learn, and How Long Will It Take?
- HTML Frame Structure
- HTML Link Formatting
I
- if..else construction
- Infinite sequences and series
- Information properties
- Inheritance in Java: A Complete Guide to Principles and Implementation
- Inserting an Image
- Integration of functions
- Interactive Python Tutorial – Learn Programming from Scratch
- Interpreter
- Interview Problem: Finding a Deleted Element in O(N)
- Interview Scare: The FizzBuzz Challenge
- Introduction to C++
- Introduction to Machine Learning
- Introduction to Networking | Network Fundamentals Part 1
- Introduction to Number Systems (Binary, Octal, Hexadecimal) | Math for CS Foundations #1
- IT Specialist Resume (CV)
J
K
L
M
- Machine Learning
- Machine Learning Basic Tool: NumPy
- Machine Learning Basic Tool: Pandas
- Machine Learning Mathematics
- Mathematics for programmers: what is really needed?
- MD5 encryption algorithm: What is it and why is it needed?
- Microcontroller and Microprocessor - what's the difference?
- ML Engineer: Who They Are, What They Do, How Much They Earn, and How to Become a Neural Network Specialist
- Monte Carlo Simulation: How It Works and What It's For
O
P
- PHP lessons
- Private DNS server and its configuration
- Program code
- Programmer's Dictionary
- Programming
- Programming with pseudocode
- Python Code Formatting Guide: PEP8
- Python for data analysis: how to do it and main libraries
- Python Lessons
- Python Superstar: 5 Ways to Use the * Operator
- Python vs. Julia: Should You Replace Python with Julia?
R
S
- SFML Graphics Library Tutorials
- Sorting Algorithms in Programming: Types, Descriptions, and Comparisons
- SQL commands: see what they are, what the main ones are + examples
- SQL Interview Questions and Tasks
- SQL Lessons
- SQL Stored Procedures
- SQL Syntactic Sugar: The COALESCE Function
- Stack
- Start in analytics: Python or R
- Static vs. dynamic data structures
- Statistical analysis: importance for decision making.
- String formatting in Python
- Structure of computer science
- Swift Lessons
- switch/match construct
- Syntax
T
- Terms in programming
- Text and paragraph formatting tags
- The Complete Guide to Bootstrap
- The Complete Guide to JavaScript
- The concept of information and its transmission
- The Future of Python: Key Trends and Insights from Global Researc
- The Infrastructure of Code: A Complete Guide to Repositories for Languages, Frameworks, and Compilers
- The pip package manager in Python
- The role of informatization in the development of society
- Transfers
- Tricky Java Questions Often Asked in Interviews
- Tutorials / Articles
- TypeScript: What It Is and Why Developers Need It
W
- What are databases, and why do they need DBMS and SQL?
- What do Linux distributions consist of?
- What is .NET and what is it used for?
- What is a data structure?
- What is a GPU in a computer, in simple terms?
- What is a quantum computer: 100,500 problems in one second
- What Is an Algorithm?
- What is Arduino: How it Works and the Platform's Capabilities
- What is Big Data? Introduction, Types, Characteristics, and Examples
- What is FizzBuzz Challenge?
- What is Golang and what is it used for?
- What is Haskell and what is it used for?
- What is Kotlin and what is it used for?
- What is Linux? The History of Linux
- What is machine learning, and how does it work?
- What is Power BI: everything about the data analytics software
- What is recursion, recursive and iterative process in programming?
- What is the C++ programming language?
- What is the OSI Model: A Complete Explanation of the Seven Layers and Their Role in Networking
- What's the difference between x86 and ARM processors?
- Where to start learning the C programming language?
- Which Linux distribution should you choose? A Linux distribution overview

