Table of Contents
Recursion in C++
Recursion is a method of solving problems where a function calls itself to solve a simpler version of the same problem. In C++, recursion can be implemented using a function that calls itself, with a base case that stops the recursion. Here’s an example of a simple recursive function in C++ that calculates the factorial of a given number:
#include
int factorial(int n) {
if (n == 0) {
return 1; // base case
} else {
return n * factorial(n - 1); // recursive call
}
}
int main() {
int num;
std::cout << "Enter a number: ";
std::cin >> num;
std::cout << "The factorial of " << num << " is " << factorial(num) << std::endl;
return 0;
}
In this example, the function factorial()
takes an integer argument n
, and returns the factorial of n
. The function first checks if n
is equal to 0, which is the base case for the recursion. If n
is 0, the function returns 1, which is the factorial of 0. If n
is not 0, the function calls itself with the argument n - 1
, and multiplies the result by n
. This process continues until n
is equal to 0, at which point the recursion stops and the final result is returned.
It’s important to have a base case to stop the recursion. If the base case is not defined, or if the recursion doesn’t progress towards the base case, the function will enter into an infinite recursion and crash the program.
Recursion can also be applied to solve problems by dividing the problem into smaller sub-problems. This can be achieved using divide-and-conquer algorithms, where the problem is divided into smaller sub-problems and each sub-problem is solved recursively.
Note, also that recursion can cause stack overflow problem if not used carefully, specially for problem with large input or if recursion depth is high.
It’s important to understand the problem you’re trying to solve and choose the most appropriate algorithm to solve it, whether that be recursion or some other technique
How to read and write the files with the help of C++
In C++, you can read and write to files using the fstream
library, which provides several classes and functions for working with files, including ifstream
for reading from files, ofstream
for writing to files, and fstream
for reading and writing to files.
Here’s an example of how to read a text file in C++ using the ifstream
class:
#include
#include
#include
int main() {
std::ifstream input_file;
input_file.open("example.txt"); // open the file
if (input_file.is_open()) {
std::string line;
while (std::getline(input_file, line)) { // read one line at a time
std::cout << line << std::endl;
}
input_file.close(); // close the file
} else {
std::cout << "Unable to open file" << std::endl;
}
return 0;
}
This example opens a file called “example.txt” using the open()
function of the ifstream
class. The is_open()
function is used to check if the file was successfully opened. If the file was opened successfully, the program reads the file one line at a time using the getline()
function, and prints each line to the console. If the file could not be opened, an error message is displayed. Finally, the file is closed using the close()
function.
Here is an example of how to write a file using the ofstream
class:
ย
#include
#include
int main() {
std::ofstream output_file;
output_file.open("example.txt", std::ios::app); // open the file in append mode
if (output_file.is_open()) {
output_file << "Writing to a file in C++" << std::endl;
output_file.close(); // close the file
} else {
std::cout << "Unable to open file" << std::endl;
}
return 0;
}
In this example, a file named “example.txt” is opened using the open()
function of the ofstream
class with mode std::ios::app
, it open the file in append mode which means that new data is added to the end of the file instead of overwriting the existing data. The is_open()
function is used to check if the file was successfully opened. If the file was opened successfully, the program writes to the file using the <<
operator and writes the string “Writing to a file in C++” to the file, and a newline character is added to the end of the string. If the file could not be opened, an error message is displayed and the file is closed using the close()
function.
It is worth noting that if you open a file for writing and the file does not exist, it will be created, and if it does exist, its existing content will be truncated (overwritten with new content)
It’s also important to always close the files once you’re done with them to release system resources and avoid data loss.
Polymorphism in C++
console.log( 'Code is Poetry' );
In object-oriented programming, polymorphism refers to the ability of a single function or method to operate on multiple types of data. In C++, this can be achieved through function overloading, operator overloading, and virtual functions.
For example, consider the following code:
#include
class Shape {
public:
virtual double area() = 0; // pure virtual function
};
class Rectangle : public Shape {
double width, height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
double area() { return width * height; }
};
class Circle : public Shape {
double radius;
public:
Circle(double r) : radius(r) {}
double area() { return 3.14159 * radius * radius; }
};
int main() {
Shape *shapes[2];
shapes[0] = new Rectangle(3, 4);
shapes[1] = new Circle(5);
for (int i = 0; i < 2; i++) {
cout << "Area of shape " << i+1 << ": " << shapes[i]->area() << endl;
}
return 0;
}
Here, the Shape
class is defined as an abstract class with a pure virtual function area()
. This means that the Shape
class cannot be instantiated, but other classes can inherit from it. The Rectangle
and Circle
classes both inherit from Shape
and provide their own implementation of the area()
function.
In the main()
function, an array of Shape
pointers is created, and objects of the Rectangle
and Circle
classes are assigned to its elements. The area()
function is then called on each element of the array, resulting in the area of the rectangle and the circle being printed. Since the area()
function is virtual, the correct implementation for each object is called based on its actual type at runtime, even though the array elements are declared as Shape
pointers. This demonstrates polymorphism in C++.
ย