C++

C++ Programs (Code Explanation Line by Line)

C++ is a high-level, general-purpose programming language developed by Bjarne Stroustrup in 1983. It is an extension of the C language and is widely used for developing operating systems, system software, and various applications such as gaming, financial modeling, and scientific simulations.

C++ is an object-oriented language, which means it allows for encapsulation, inheritance, and polymorphism, making it easier for developers to write maintainable and reusable code. It also supports multiple programming paradigms, including procedural, functional, and generic programming.




One of the main advantages of C++ is its performance. It is compiled, meaning that its code is translated into machine code that is executed directly by the computer’s hardware. This results in faster execution times compared to interpreted languages like Python or JavaScript.

Another feature of C++ is its Standard Template Library (STL), which provides a collection of pre-written algorithms and data structures that can be easily reused, making it easier to develop complex programs.

C++ is widely used in the industry, with many well-known companies relying on it for their software development. This is because it is a versatile language that can be used for many different purposes, making it a valuable tool for software developers.

Overall, C++ is a powerful and widely-used programming language that is used for developing a wide range of applications. Its performance, versatility, and extensive library make it a valuable tool for software developers.

Here is C++ Programs and explanations line by line.

Example 1: Print Number Entered by User

Output:

Here’s an explanation of the code line by line:

#include <iostream> is a preprocessor directive that includes the iostream library in the program. This library provides input/output functionality to the program.

using namespace std; allows the use of standard library objects and functions without having to qualify them with std::.

int main() is the main function of the program. All C++ programs must have a main function.

int number; declares an integer variable named number.

cout << "Enter an integer: "; writes the string “Enter an integer: ” to the console.

cin >> number; reads an integer from the user and stores it in the number variable.

cout << "You entered " << number; writes the string “You entered ” followed by the value of number to the console.

return 0; ends the main function and returns a value of 0 to the operating system, indicating that the program ran successfully.

Example 2: Program to Add Two Integers

Output:

Here’s an explanation of the code line by line:

#include <iostream>: This line includes the standard input/output library in the program.

using namespace std;: This line includes the standard namespace in the program.

int main(): The main function, the starting point of the program.

int first_number, second_number, sum;: Three integer variables are declared, first_number and second_number to store the input numbers, and sum to store the sum of the two numbers.

cout << "Enter two integers: ";: This line outputs the prompt “Enter two integers: ” on the screen.

cin >> first_number >> second_number;: This line reads two integers from the input stream and stores them in first_number and second_number respectively.

sum = first_number + second_number;: The sum of first_number and second_number is calculated and stored in the sum variable.

cout << first_number << " + " << second_number << " = " << sum;: This line outputs the expression first_number + second_number = sum on the screen.

return 0;: This line returns 0 to indicate that the program executed successfully.

The program ends.

Click here for more examples

Example 3: Compute quotient and remainder

Output:

Here’s an explanation of the code line by line:

#include <iostream>: This line includes the iostream library, which provides input and output functions (e.g. cin and cout).

using namespace std;: This line makes all the symbols in the std namespace accessible without the std:: prefix.

int main(): This line defines the main function, which is the entry point of the program. The int keyword indicates that the function returns an integer.

int divisor, dividend, quotient, remainder;: This line declares four variables named divisor, dividend, quotient, and remainder, all of type int.

cout << "Enter dividend: ";: This line outputs the text “Enter dividend: ” to the console using the cout stream.

cin >> dividend;: This line inputs an integer from the user and stores it in the dividend variable using the cin stream.

cout << "Enter divisor: ";: This line outputs the text “Enter divisor: ” to the console using the cout stream.

cin >> divisor;: This line inputs an integer from the user and stores it in the divisor variable using the cin stream.

quotient = dividend / divisor;: This line calculates the integer division of dividend by divisor and stores the result in the quotient variable.

remainder = dividend % divisor;: This line calculates the remainder of dividend divided by divisor using the modulo operator % and stores the result in the remainder variable.

cout << "Quotient = " << quotient << endl;: This line outputs the value of quotient to the console, followed by a newline character.

cout << "Remainder = " << remainder;: This line outputs the value of remainder to the console.

return 0;: This line returns the value 0 to indicate that the program executed successfully.

}: This closes the main function definition.

Example 4: Swap Numbers (Using Temporary Variable)

Output:

Here’s an explanation of the code line by line:

#include <iostream>: This line includes the iostream library, which provides input and output functions (e.g. cin and cout).

using namespace std;: This line makes all the symbols in the std namespace accessible without the std:: prefix.

int main(): This line defines the main function, which is the entry point of the program. The int keyword indicates that the function returns an integer.

int a = 5, b = 10, temp;: This line declares three variables named a, b, and temp, with a initialized to 5, b initialized to 10, and temp uninitialized.

cout << "Before swapping." << endl;: This line outputs the text “Before swapping.” to the console, followed by a newline character, using the cout stream.

cout << "a = " << a << ", b = " << b << endl;: This line outputs the values of a and b to the console, separated by a comma and a space, followed by a newline character, using the cout stream.

temp = a;: This line stores the value of a in temp.

a = b;: This line assigns the value of b to a.

b = temp;: This line assigns the value of temp to b.

cout << "\nAfter swapping." << endl;: This line outputs the text “After swapping.” to the console, followed by a newline character, using the cout stream.

cout << "a = " << a << ", b = " << b << endl;: This line outputs the values of a and b to the console, separated by a comma and a space, followed by a newline character, using the cout stream.

return 0;: This line returns the value 0 to indicate that the program executed successfully.

}: This closes the main function definition.

Click here for more examples

Example 5: Swap Numbers Without Using Temporary Variables

Output:

Here’s an explanation of the code line by line:

#include <iostream>: This line includes the iostream library, which provides input and output functions (e.g. cin and cout).

using namespace std;: This line makes all the symbols in the std namespace accessible without the std:: prefix.

int main(): This line defines the main function, which is the entry point of the program. The int keyword indicates that the function returns an integer.

int a = 5, b = 10;: This line declares two variables named a, b, with a initialized to 5 and b initialized to 10.

cout << "Before swapping." << endl;: This line outputs the text “Before swapping.” to the console, followed by a newline character, using the cout stream.

cout << "a = " << a << ", b = " << b << endl;: This line outputs the values of a and b to the console, separated by a comma and a space, followed by a newline character, using the cout stream.

a = a + b;: This line adds the values of a and b and stores the result in a.

b = a - b;: This line subtracts the value of b from a and stores the result in b.

a = a - b;: This line subtracts the value of b from a and stores the result in a.

cout << "\nAfter swapping." << endl;: This line outputs the text “After swapping.” to the console, followed by a newline character, using the cout stream.

cout << "a = " << a << ", b = " << b << endl;: This line outputs the values of a and b to the console, separated by a comma and a space, followed by a newline character, using the cout stream.

return 0;: This line returns the value 0 to indicate that the program executed successfully.

}: This closes the main function definition.

Example 6: Check Whether Number is Even or Odd using if else

Output:

Explanation line by line:

#include <iostream>: The standard library iostream header file is included. It contains functions to input and output data, such as cin and cout.

using namespace std;: The standard namespace std is defined, so that the standard library functions can be called without using the namespace name.

int main(): The main function is the starting point of the program. The int in front of main indicates that the main function returns an integer value.

int n;: An integer variable n is declared.

cout << "Enter an integer: ";: The message “Enter an integer: ” is printed to the console.

cin >> n;: The user is prompted to enter an integer, which is stored in the n variable.

if ( n % 2 == 0): The if statement checks if n is even. If n is evenly divisible by 2, n % 2 will equal 0. The == operator is used to compare two values for equality. If the comparison is true, the code inside the if block will execute.

cout << n << " is even.";: The message “is even” is printed to the console, along with the value of n.

else: If the comparison in the if statement is false, the code inside the else block will execute.

cout << n << " is odd.";: The message “is odd” is printed to the console, along with the value of n.

return 0;: The main function returns the integer value 0, indicating that the program has run successfully.

Example 7: Check Whether Number is Even or Odd using ternary operators

Output:

Here’s an explanation of the code line by line:

The line #include <iostream> includes the standard input/output library in the program, which allows us to use the input/output stream operators cin and cout.

The line using namespace std; allows us to use the standard library without having to qualify it with std::.

The line int main() declares the main function, which is the starting point of the program. The line int n; declares the integer variable n, which will be used to store the input entered by the user.

The lines cout << "Enter an integer: "; and cin >> n; prompt the user to enter an integer, which is stored in the variable n.

The line (n % 2 == 0) ? cout << n << " is even." : cout << n << " is odd."; uses a ternary operator to check if n is even or odd. If n is divisible by 2 with no remainder, then n % 2 will equal 0, so the expression n % 2 == 0 will evaluate to true and the program will print n followed by “is even”. If n is not divisible by 2 with no remainder, then the expression n % 2 == 0 will evaluate to false, and the program will print n followed by “is odd”.

Finally, the line return 0; ends the main function and returns a value of 0 to indicate successful completion of the program.

Click here for more examples

Example 8: Find Largest Number Using if…else Statement

This program calculates the largest number from 3 inputted numbers. The code uses conditional statements to check which number is the largest and outputs it.

Output:

Here’s an explanation of the code line by line:

Include the iostream library and use the “using namespace std;” directive to allow for using the standard input and output functions.

The main function starts.

Three double variables, n1, n2, and n3, are declared to store the inputted numbers.

The user is prompted to enter three numbers and the values are stored in the n1, n2, and n3 variables using the cin function.

An if-else statement is used to check if n1 is the largest number. If n1 is greater than or equal to both n2 and n3, the message “Largest number: n1” is outputted.

Another if-else statement is used to check if n2 is the largest number. If n2 is greater than or equal to both n1 and n3, the message “Largest number: n2” is outputted.

The last else statement checks if neither n1 nor n2 are the largest number. In this case, n3 must be the largest number and the message “Largest number: n3” is outputted.

The main function returns 0, indicating that the program has run successfully.

Example 9: Find the Largest Number Using Nested if…else statement

Output:

Here’s an explanation line by line:

#include <iostream>: This line includes the standard input/output library in the C++ program, which provides functions like cin and cout.

using namespace std;: This line is used to include the standard namespace in the program, so you don’t have to qualify cout and cin with the scope operator std::.

int main(): This line declares the main function, which is the starting point of the program.

double n1, n2, n3;: These lines declare three variables, n1, n2, and n3, of type double to store the three numbers entered by the user.

cout << "Enter three numbers: ";: This line prints the message “Enter three numbers: ” to the console to prompt the user to enter three numbers.

cin >> n1 >> n2 >> n3;: This line reads the three numbers entered by the user and stores them in the variables n1, n2, and n3.

if (n1 >= n2) {: This line starts the first if statement, which checks if n1 is greater than or equal to n2.

if (n1 >= n3): This line starts the nested if statement, which checks if n1 is also greater than or equal to n3.

cout << "Largest number: " << n1;: If both conditions in the if statements are true, this line prints the message “Largest number: ” followed by the value of n1.

else: If the condition in the nested if statement is false, this line starts the else block.

cout << "Largest number: " << n3;: This line prints the message “Largest number: ” followed by the value of n3, since n1 is greater than n2 but not n3.

else: If the condition in the first if statement is false, this line starts the else block.

if (n2 >= n3): This line starts a nested if statement, which checks if n2 is greater than or equal to n3.

cout << "Largest number: " << n2;: If the condition in the nested if statement is true, this line prints the message “Largest number: ” followed by the value of n2.

else: If the condition in the nested if statement is false, this line starts the else block.

cout << "Largest number: " << n3;: This line prints the message “Largest number: ” followed by the value of n3, since n2 is greater than n1 but not n3.

return 0;: This line ends the main function and returns a value of 0 to indicate that the program ran successfully.

Example 10: Roots of a Quadratic Equation

Output:

Here’s an explanation line by line:

The code starts by including the iostream and cmath libraries. iostream provides input/output functions (cin and cout), and cmath provides mathematical functions (sqrt).

This line specifies that the standard namespace std should be used in the program, which includes the input/output and mathematical functions.

In the main function, variables a, b, c, x1, x2, discriminant, realPart, and imaginaryPart are declared as float types.

The program outputs a message asking the user to input the coefficients a, b, and c, and then uses cin to read the user’s input into the variables.

The discriminant of a quadratic equation is calculated as b^2 - 4ac. The value is stored in the variable discriminant.

If the discriminant is greater than 0, then the roots of the equation are real and different. The roots are calculated using the formula (-b ± √(discriminant)) / (2a), and the results are stored in x1 and x2. The program outputs a message indicating that the roots are real and different, and the values of x1 and x2.

If the discriminant is equal to 0, then the roots of the equation are real and the same. The value of the root is calculated as -b/(2a), and stored in x1. The program outputs a message indicating that the roots are real and the same, and the value of the root.

return 0;: This line ends the main function and returns a value of 0 to indicate that the program ran successfully.

Click here for more examples

Example 11: Sum of Natural Numbers using loop

Output:

Here’s an explanation line by line:

The program includes the “iostream” library and uses the “std” namespace.

In the main function, an integer variable “n” is declared and initialized by the user’s input, and an integer variable “sum” is initialized to 0.

The program calculates the sum of the first “n” positive integers using a for loop.

In the for loop, the variable “i” is initialized to 1 and increments by 1 until it reaches “n”. The sum is calculated by adding the current value of “i” to the current value of “sum”.

After the for loop, the program prints the calculated sum value.

The program returns 0, indicating a successful execution.

Example 12: Check Leap Year Using if…else Ladder

This C++ program determines if a given year is a leap year or not.

Output:

Here’s an explanation line by line:

The program includes the “iostream” library and uses the “std” namespace.

In the main function, an integer variable “year” is declared and initialized by the user’s input.

The first if statement checks if the year is perfectly divisible by 400. If true, the program prints “year is a leap year”.

The else if statement checks if the year is divisible by 100 but not divisible by 400. If true, the program prints “year is not a leap year”.

The second else if statement checks if the year is not divisible by 100 but is divisible by 4. If true, the program prints “year is a leap year”.

The final else statement catches all other cases and prints “year is not a leap year”.

The program returns 0, indicating a successful execution.

Example 13: Check Leap Year Using Nested if

Output:

Here’s an explanation line by line:

The program includes the “iostream” library and uses the “std” namespace.

In the main function, an integer variable “year” is declared and initialized by the user’s input.

The first if statement checks if the year is divisible by 4. If true, the program proceeds to the next step.

The nested if statement checks if the year is divisible by 100. If true, the program proceeds to the next step.

The nested if statement checks if the year is divisible by 400. If true, the program prints “year is a leap year”.

If the year is not divisible by 400, the program prints “year is not a leap year”.

If the year is not divisible by 100, the program prints “year is a leap year”.

If the year is not divisible by 4, the program prints “year is not a leap year”.

The program returns 0, indicating a successful execution.

Click here for more examples

Example 14: Find the Factorial of a Given Number

Output:

Here’s an explanation line by line:

The program includes the “iostream” library and uses the “std” namespace.

In the main function, an integer variable “n” is declared and initialized by the user’s input, and a long variable “factorial” is initialized to 1.

The program checks if the input integer “n” is less than 0. If true, it prints an error message “Error! Factorial of a negative number doesn’t exist.”

If the input integer “n” is non-negative, the program enters the else block and calculates the factorial using a for loop.

In the for loop, the variable “i” is initialized to 1 and increments by 1 until it reaches “n”. The factorial is calculated by multiplying the current value of “factorial” with the current value of “i”.

After the for loop, the program prints the calculated factorial value.

The program returns 0, indicating a successful execution.

Example 15: Display Multiplication Table up to a Given Range

Output:

Here’s an explanation line by line:

The program includes the “iostream” library and uses the “std” namespace.

In the main function, two integer variables “n” and “range” are declared and initialized by the user’s input.

The program generates the multiplication table of “n” up to a given range using a for loop.

In the for loop, the variable “i” is initialized to 1 and increments by 1 until it reaches “range”. The multiplication result is calculated by multiplying the current value of “n” and “i”.

The program prints each multiplication result, along with the values of “n” and “i”.

The program returns 0, indicating a successful execution.

Example 16: Fibonacci Series up to n number of terms

Output:

Here is an explanation of the code line by line:

#include <iostream>: This line includes the header file iostream, which provides input and output functionality in C++.

using namespace std;: This line specifies that all the names in the standard library should be in the std namespace.

int main(): This is the main function of the program, which is the entry point of the program and returns an integer value.

int n, t1 = 0, t2 = 1, nextTerm = 0;: This line declares four integer variables, n, t1, t2, and nextTerm. n is used to store the number of terms to be printed, t1 and t2 are used to store the first two terms in the Fibonacci series, and nextTerm is used to store the next term in the series.

cout << "Enter the number of terms: ";: This line outputs the prompt “Enter the number of terms: ” to the console.

cin >> n;: This line reads the number of terms from the user and stores it in the variable n.

cout << "Fibonacci Series: ";: This line outputs the text “Fibonacci Series: ” to the console.

for (int i = 1; i <= n; ++i): This is the start of a for loop that will run n times. i is the loop counter, which starts from 1 and increases by 1 each iteration until it reaches n.

if (i == 1): This if statement checks if the current value of i is equal to 1. If it is, the first term of the Fibonacci series is printed to the console.

continue;: This line skips to the next iteration of the loop, bypassing the rest of the code in the current iteration.

if (i == 2): This if statement checks if the current value of i is equal to 2. If it is, the second term of the Fibonacci series is printed to the console.

nextTerm = t1 + t2;: This line calculates the next term in the series by adding t1 and t2.

t1 = t2;: This line sets the value of t1 to the value of t2.

t2 = nextTerm;: This line sets the value of t2 to the value of nextTerm.

cout << nextTerm << ", ";: This line outputs the value of nextTerm followed by a comma and a space to the console.

return 0;: This line returns the value 0 from the main function, indicating that the program has run successfully.

Example 17: Program to Generate Fibonacci Sequence Up to a Certain Number

Output:

Here’s a line-by-line explanation of the code:

The first line #include <iostream> is a preprocessor directive that includes the input/output stream library for C++.

The line using namespace std; makes all the standard library functions available to the program without having to qualify them with the std:: prefix.

int main() is the starting point of every C++ program. It returns an integer value and is the main function.

int t1 = 0, t2 = 1, nextTerm = 0, n; declares four integer variables: t1 and t2 are used to store the previous two terms of the Fibonacci series, nextTerm is used to store the next term of the series, and n is used to store the number up to which the Fibonacci series will be generated.

cout << "Enter a positive number: "; outputs the message “Enter a positive number: ” on the screen.

cin >> n; is used to read an integer value from the user and store it in the variable n.

cout << "Fibonacci Series: " << t1 << ", " << t2 << ", "; outputs the message “Fibonacci Series: ” followed by the first two terms of the series, which is 0 and 1.

nextTerm = t1 + t2; calculates the next term of the series by adding the previous two terms.

The while loop is executed while the value of nextTerm is less than or equal to n. Within the loop, the code:

cout << nextTerm << ", "; outputs the next term of the series.

t1 = t2; assigns the value of t2 to t1.

t2 = nextTerm; assigns the value of nextTerm to t2.

nextTerm = t1 + t2; calculates the next term of the series by adding the previous two terms.

return 0; returns a value of 0 to the operating system, indicating that the program has executed successfully.

Click here for more examples

Example 18: Find HCF/GCD using for loop

Output:

Here’s a line-by-line explanation of the code:

The first line #include <iostream> is a preprocessor directive that includes the input/output stream library for C++.

The line using namespace std; makes all the standard library functions available to the program without having to qualify them with the std:: prefix.

int main() is the starting point of every C++ program. It returns an integer value and is the main function.

int n1, n2, hcf; declares three integer variables: n1 and n2 are used to store the two numbers entered by the user, and hcf is used to store the highest common factor of the two numbers.

cout << "Enter two numbers: "; outputs the message “Enter two numbers: ” on the screen.

cin >> n1 >> n2; is used to read two integer values from the user and store them in the variables n1 and n2, respectively.

The if-statement if ( n2 > n1) checks if the value of n2 is greater than n1. If true, the code within the block swaps the values of n1 and n2 using a temporary variable temp.

The for loop is executed for the number of times equal to the value of n2. Within the loop, the code:

if (n1 % i == 0 && n2 % i ==0) checks if the variables n1 and n2 are divisible by i, the loop counter.

If the condition is true, hcf = i; assigns the value of i to hcf.

cout << "HCF = " << hcf; outputs the message “HCF = ” followed by the value of hcf, which is the highest common factor of n1 and n2.

return 0; returns a value of 0 to the operating system, indicating that the program has executed successfully.

Example 19: Find GCD/HCF using while loop

Output:

Here’s a line-by-line explanation of the code:

The first line #include <iostream> is a preprocessor directive that includes the input/output stream library for C++.

The line using namespace std; makes all the standard library functions available to the program without having to qualify them with the std:: prefix.

int main() is the starting point of every C++ program. It returns an integer value and is the main function.

int n1, n2; declares two integer variables: n1 and n2 are used to store the two numbers entered by the user.

cout << "Enter two numbers: "; outputs the message “Enter two numbers: ” on the screen.

cin >> n1 >> n2; is used to read two integer values from the user and store them in the variables n1 and n2, respectively.

The while loop while(n1 != n2) checks if n1 is not equal to n2. If true, the code within the loop is executed.

The if-else statement if(n1 > n2) checks if n1 is greater than n2.

If true, n1 -= n2; subtracts n2 from n1.

If false, n2 -= n1; subtracts n1 from n2.

cout << "HCF = " << n1; outputs the message “HCF = ” followed by the value of n1, which is the highest common factor of n1 and n2.

return 0; returns a value of 0 to the operating system, indicating that the program has executed successfully.

Example 20: Find LCM

Output:

Here’s a line-by-line explanation of the code:

The first line #include <iostream> is a preprocessor directive that includes the input/output stream library for C++.

The line using namespace std; makes all the standard library functions available to the program without having to qualify them with the std:: prefix.

int main() is the starting point of every C++ program. It returns an integer value and is the main function.

int n1, n2, max; declares three integer variables: n1 and n2 are used to store the two numbers entered by the user, and max is used to store the maximum value between n1 and n2.

cout << "Enter two numbers: "; outputs the message “Enter two numbers: ” on the screen.

cin >> n1 >> n2; is used to read two integer values from the user and store them in the variables n1 and n2, respectively.

max = (n1 > n2) ? n1 : n2; assigns the greater of the two values n1 and n2 to the variable max. The conditional operator (?) checks if n1 is greater than n2, and if true, n1 is assigned to max. If false, n2 is assigned to max.

The do-while loop do { ... } while (true); executes the code within the loop at least once and then continues to execute as long as the condition (true) is met.

The if-else statement if (max % n1 == 0 && max % n2 == 0) checks if max is divisible by both n1 and n2 without a remainder.

If true, cout << "LCM = " << max; outputs the message “LCM = ” followed by the value of max, which is the least common multiple of n1 and n2.

If false, ++max; increments the value of max by 1.

break; terminates the do-while loop when the least common multiple of n1 and n2 is found.

return 0; returns a value of 0 to the operating system, indicating that the program has executed successfully.

Click here for more examples

Example 21: C++ Program to Reverse an Integer

Output:

The program starts with the inclusion of the iostream header file.

The main function starts and declares an integer n and reversed_number initialized to 0.

The cout statement outputs the string “Enter an integer: ” to prompt the user to enter an integer.

The cin statement inputs the integer entered by the user and stores it in n.

The while loop starts and checks if n is not equal to 0. If true, the remainder of n divided by 10 is stored in remainder.

The value of reversed_number is updated by multiplying the current value by 10 and adding the remainder.

The value of n is updated by integer division n by 10.

Steps 5 to 7 repeat until n is equal to 0.

The cout statement outputs the string “Reversed Number = ” and the value of reversed_number.

The program returns 0 and terminates.

Example 22: C++ Program to Calculate Power of a Number

Output:

The program starts with the inclusion of the iostream header file.

The main function starts and declares an integer exponent, a float base and result initialized to 1.

The cout statement outputs the string “Enter base and exponent respectively: ” to prompt the user to enter the base and exponent.

The cin statement inputs the base and exponent entered by the user and stores it in base and exponent respectively.

The cout statement outputs the expression base raised to the power exponent.

The while loop starts and checks if exponent is not equal to 0. If true, the value of result is updated by multiplying it with base.

The value of exponent is decremented by 1.

Steps 6 and 7 repeat until exponent is equal to 0.

The cout statement outputs the value of result.

The program returns 0 and terminates.

Example 23: C++ Program to Subtract Complex Number Using Operator Overloading

This C++ program demonstrates the use of operator overloading in C++ to perform subtraction on two complex numbers.

Output:

The program starts by declaring the Complex class with the private member variables real and imag for the real and imaginary parts of a complex number respectively.

The constructor initializes the real and imag to 0.

The input() function takes the input for the real and imaginary parts of a complex number from the user.

The operator- function overloads the subtraction operator to perform subtraction of two complex numbers and returns the difference as a Complex object.

The output() function prints the complex number to the console in the format “Output Complex number: real + imag i”.

In the main function, two complex numbers are taken as input and the difference is obtained by calling the operator- function. The result is then printed to the console.

The program returns 0 as the exit code.

Example 24: C++ Program to Check Whether a Number is Palindrome or Not

Output:

This is a program to check if an integer entered by the user is a palindrome.

int n, num, digit, rev = 0;: These are variable declarations. n is used to store the original number entered by the user, num is used to store the number during processing, digit is used to store the last digit of num, and rev is used to store the reverse of the number.

cout << "Enter a positive number: ";: This line prompts the user to enter a positive number.

cin >> num;: This line takes the input from the user and stores it in num.

n = num;: This line stores the original value of num in n.

do { ... } while (num != 0);: This is a do-while loop that will keep executing as long as num is not equal to zero. The loop continues until all digits of num have been processed.

digit = num % 10;: This line calculates the last digit of num and stores it in digit.

rev = (rev * 10) + digit;: This line multiplies the current value of rev by 10 and adds digit to it, effectively appending digit to the right side of rev.

num = num / 10;: This line removes the last digit of num by dividing num by 10.

cout << " The reverse of the number is: " << rev << endl;: This line prints the reverse of the original number entered by the user.

if (n == rev) ... else ...: This is an if-else statement that checks if n and rev are equal. If they are equal, the number is a palindrome and the message " The number is a palindrome." is printed. If they are not equal, the message " The number is not a palindrome." is printed.

return 0;: This line terminates the main function and returns 0 to indicate a successful execution.

Example 25: C++ Program to Check Whether a Number is Prime or Not

Output:

#include <iostream> – The header file is included for input/output operations.

using namespace std; – The standard namespace is included.

int main() – The main function starts here.

int i, n; – Two integer variables i and n are declared.

bool is_prime = true; – A boolean variable is_prime is declared and initialized to true.

cout << "Enter a positive integer: "; – Prompts the user to enter a positive integer.

cin >> n; – Reads the integer entered by the user.

if (n == 0 || n == 1) – Checks if the integer entered is 0 or 1.

is_prime = false; – If the above condition is true, the value of is_prime is set to false.

for (i = 2; i <= n/2; ++i) – A for loop that starts from 2 and runs until i is less than or equal to n/2.

if (n % i == 0) – Checks if n is divisible by i.

is_prime = false; – If the above condition is true, the value of is_prime is set to false.

break; – The for loop is broken.

if (is_prime) – Checks if the value of is_prime is true.

cout << n << " is a prime number"; – If the above condition is true, the entered number is a prime number.

else – If the above condition is not true.

cout << n << " is not a prime number"; – The entered number is not a prime number.

return 0; – The main function returns 0, indicating successful execution of the program.

Example 26: Display all Factors of a Number

Output:

Here is a line-by-line explanation of the code:

#include <iostream> – This line includes the input/output library in C++, allowing the code to use cout (console output) and cin (console input).

using namespace std; – This line defines the standard namespace, which contains many common C++ functions and objects.

int main() – This line starts the main function, which is the starting point of the program.

int n, i; – This line declares two integer variables, n and i.

cout << "Enter a positive integer: "; – This line outputs the string “Enter a positive integer:” to the console, asking the user to input a positive integer.

cin >> n; – This line inputs the integer entered by the user and stores it in the variable n.

cout << "Factors of " << n << " are: "; – This line outputs the string “Factors of” followed by the integer entered by the user, followed by the string “are:”.

for(i = 1; i <= n; ++i) – This line starts a for loop, which will run i from 1 to n (inclusive). The loop increments i by 1 each time it runs.

if(n % i == 0) – This line checks if the remainder of n divided by i is equal to 0, which means i is a factor of n.

cout << i << " "; – If the previous if statement is true, this line outputs the value of i, followed by a space.

return 0; – This line returns 0 from the main function, indicating that the program has executed successfully.

Example 27: Program to Print a Half-Pyramid Using *

Output:

Here is a line-by-line explanation of the code:

#include <iostream> – This line includes the input/output library in C++, allowing the code to use cout (console output) and cin (console input).

using namespace std; – This line defines the standard namespace, which contains many common C++ functions and objects.

int main() – This line starts the main function, which is the starting point of the program.

int rows; – This line declares an integer variable named rows.

cout << "Enter number of rows: "; – This line outputs the string “Enter number of rows:” to the console, asking the user to input the number of rows.

cin >> rows; – This line inputs the integer entered by the user and stores it in the variable rows.

for(int i = 1; i <= rows; ++i) – This line starts the outer for loop, which will run i from 1 to rows (inclusive). The loop increments i by 1 each time it runs.

for(int j = 1; j <= i; ++j) – This line starts the inner for loop, which will run j from 1 to i (inclusive). The loop increments j by 1 each time it runs.

cout << "* "; – This line outputs an asterisk followed by a space, which will represent a single character in the pyramid shape.

cout << "\n"; – This line outputs a newline character, which will start a new line and move the output to the next row of the pyramid.

return 0; – This line returns 0 from the main function, indicating that the program has executed successfully.

Example 28: Inverted Half-Pyramid Using *

Output:

Here is a line-by-line explanation of the code:

#include <iostream> – This line includes the input/output library in C++, allowing the code to use cout (console output) and cin (console input).

using namespace std; – This line defines the standard namespace, which contains many common C++ functions and objects.

int main() – This line starts the main function, which is the starting point of the program.

int rows; – This line declares an integer variable named rows.

cout << "Enter number of rows: "; – This line outputs the string “Enter number of rows:” to the console, asking the user to input the number of rows.

cin >> rows; – This line inputs the integer entered by the user and stores it in the variable rows.

for(int i = rows; i >= 1; --i) – This line starts the outer for loop, which will run i from rows to 1 (inclusive). The loop decrements i by 1 each time it runs.

for(int j = 1; j <= i; ++j) – This line starts the inner for loop, which will run j from 1 to i (inclusive). The loop increments j by 1 each time it runs.

cout << "* "; – This line outputs an asterisk followed by a space, which will represent a single character in the pyramid shape.

cout << endl; – This line outputs a newline character, which will start a new line and move the output to the next row of the pyramid.

return 0; – This line returns 0 from the main function, indicating that the program has executed successfully.

Example 29: Program to Print a Full Pyramid Using *

Output:

Here is a line-by-line explanation of the code:

#include <iostream> – This line includes the input/output library in C++, allowing the code to use cout (console output) and cin (console input).

using namespace std; – This line defines the standard namespace, which contains many common C++ functions and objects.

int main() – This line starts the main function, which is the starting point of the program.

int space, rows; – This line declares two integer variables, space and rows.

cout <<"Enter number of rows: "; – This line outputs the string “Enter number of rows:” to the console, asking the user to input the number of rows.

cin >> rows; – This line inputs the integer entered by the user and stores it in the variable rows.

for(int i = 1, k = 0; i <= rows; ++i, k = 0) – This line starts the outer for loop, which will run i from 1 to rows (inclusive). The loop increments i by 1 each time it runs. The k variable is also initialized to 0 and will be used in the inner while loop.

for(space = 1; space <= rows-i; ++space) – This line starts the inner for loop, which will run space from 1 to rows-i (inclusive). The loop increments space by 1 each time it runs. The purpose of this loop is to print spaces before the asterisks in each row.

cout <<" "; – This line outputs two spaces, which represent the blank spaces before the asterisks.

while(k != 2*i-1) – This line starts the while loop, which will run while k is not equal to 2*i-1. The purpose of this loop is to print the asterisks in each row.

cout << "* "; – This line outputs an asterisk followed by a space, which will represent a single character in the pyramid shape.

++k; – This line increments the value of k by 1.

cout << endl; – This line outputs a newline character, which will start a new line and move the output to the next row of the pyramid.

return 0; – This line returns 0 from the main function, indicating that the program has executed successfully.

Example 30: Inverted Full Pyramid Using *

Output:

Here’s a line-by-line explanation of the code:

#include <iostream> – This line includes the iostream library, which provides input/output functions such as cout and cin.

using namespace std; – This line uses the std namespace, which contains the standard library.

int main() – This line defines the main function, which is the starting point of the program.

int rows; – This line declares an integer variable rows.

cout << "Enter number of rows: "; – This line outputs the text Enter number of rows: to the console.

cin >> rows; – This line reads an integer from the user and stores it in the rows variable.

for(int i = rows; i >= 1; --i) – This is the first for loop that performs the following operations:

  • Initialization: declares a variable i with initial value rows.
  • Condition: checks whether i is greater than or equal to 1.
  • Decrement: decreases the value of i by 1 after each iteration.

for(int space = 0; space < rows-i; ++space) – This is the nested for loop inside the first loop. It performs the following operations:

  • Initialization: declares a variable space with initial value 0.
  • Condition: checks whether space is less than rows-i.
  • Increment: increases the value of space by 1 after each iteration.

cout << " "; – This line outputs two spaces to the console.

for(int j = i; j <= 2*i-1; ++j) – This is the second nested for loop inside the first loop. It performs the following operations:

  • Initialization: declares a variable j with initial value i.
  • Condition: checks whether j is less than or equal to 2*i-1.
  • Increment: increases the value of j by 1 after each iteration.

cout << "* "; – This line outputs * to the console.

for(int j = 0; j < i-1; ++j) – This is the third nested for loop inside the first loop. It performs the following operations:

  • Initialization: declares a variable j with initial value 0.
  • Condition: checks whether j is less than i-1.
  • Increment: increases the value of j by 1 after each iteration.

cout << "* "; – This line outputs * to the console.

cout << endl; – This line outputs a new line to the console.

return 0; – This line returns 0 from the main function, indicating that the program has executed successfully.

Example 31: Simple Calculator using switch statement

Output:

This is a simple calculator program written in C++. It performs basic arithmetic operations based on the operator entered by the user. Here’s an explanation of the code:

The first line includes the input/output library “iostream”.

The “using namespace std” statement allows the use of standard library objects and functions without the need to qualify them with the std namespace.

The “main” function is the starting point of the program.

A character variable “op” is declared to store the operator entered by the user. Two float variables “num1” and “num2” are declared to store the operands.

The “cout” statement is used to display the message “Enter operator: +, -, *, /: ” on the console.

The “cin” statement is used to take input from the user and store it in the “op” variable.

The “cout” statement is used to display the message “Enter two operands: ” on the console.

The “cin” statement is used to take two inputs from the user and store them in “num1” and “num2” variables.

The “switch” statement checks the value of “op” and executes the corresponding block of code based on the operator entered by the user.

If the operator is “+”, the sum of “num1” and “num2” is calculated and displayed on the console.

If the operator is “-“, the difference of “num1” and “num2” is calculated and displayed on the console.

If the operator is “*”, the product of “num1” and “num2” is calculated and displayed on the console.

If the operator is “/”, the quotient of “num1” and “num2” is calculated and displayed on the console.

If the operator is other than +, -, * or /, the “default” case block is executed and an error message is displayed on the console.

The “return 0” statement is used to indicate that the “main” function has executed successfully.

Example 32: Prime Numbers Between two Intervals

Output:

This is a C++ program that finds and prints the prime numbers between two positive integers entered by the user. Here’s an explanation of the code:

The first line includes the input/output library “iostream”.

The “using namespace std” statement allows the use of standard library objects and functions without the need to qualify them with the std namespace.

The function “check_prime” is declared to check if a given integer is a prime number or not.

The “main” function is the starting point of the program.

Two integer variables “n1” and “n2” are declared to store the positive integers entered by the user. A boolean variable “flag” is declared to store the result of the “check_prime” function.

The “cout” statement is used to display the message “Enter two positive integers: ” on the console.

The “cin” statement is used to take two inputs from the user and store them in “n1” and “n2” variables.

The “if” statement checks if “n1” is greater than “n2” and swaps their values if necessary.

The “cout” statement is used to display the message “Prime numbers between ” and the values of “n1” and “n2” on the console.

The “for” loop iterates from “n1+1” to “n2-1” and checks each number for primality using the “check_prime” function.

If the result of the “check_prime” function is true, the “flag” variable is set to 1 and the current number is displayed on the console.

The “check_prime” function takes an integer “n” as input and returns a boolean value indicating whether the number is prime or not.

The function first checks if the number is 0 or 1 and sets the “is_prime” variable to false in that case.

A “for” loop is used to divide “n” by all integers from 2 to n/2. If the result of any division is 0, the “is_prime” variable is set to false and the loop breaks.

The value of “is_prime” is returned as the result of the function.

The “return 0” statement is used to indicate that the “main” function has executed successfully.

Example 33: Calculate Average of Numbers Using Arrays

Output:

Here’s a line-by-line explanation of the code:

#include <iostream> – This line includes the input/output stream library iostream which allows the program to input and output data.

using namespace std; – This line makes all elements in the standard namespace available to the program.

int main() – This line declares the main function, which is the entry point of the program.

int n, i; – These lines declare two integer variables n and i. n will be used to store the number of data, and i will be used as a loop counter.

float num[100], sum=0.0, average; – These lines declare an array num of size 100, a float variable sum initialized to 0.0, and a float variable average. The array num will store the input numbers, sum will store their sum, and average will store their average.

cout << "Enter the numbers of data: "; – This line outputs a prompt asking the user to enter the number of data.

cin >> n; – This line inputs the number of data from the user and stores it in the variable n.

while (n > 100 || n <= 0) – This line starts a while loop that checks if n is greater than 100 or less than or equal to 0. If either condition is true, the loop will execute.

cout << "Error! number should in range of (1 to 100)." << endl; – This line outputs an error message indicating that the number should be in the range of 1 to 100.

cout << "Enter the number again: "; – This line outputs a prompt asking the user to enter the number again.

cin >> n; – This line inputs the number of data from the user and stores it in the variable n.

for(i = 0; i < n; ++i) – This line starts a for loop that will repeat n times, incrementing i by 1 each iteration.

cout << i + 1 << ". Enter number: "; – This line outputs a prompt asking the user to enter a number, with the number of the prompt being i + 1.

cin >> num[i]; – This line inputs a number from the user and stores it in the ith element of the num array.

sum += num[i]; – This line adds the ith element of the num array to the sum variable.

average = sum / n; – This line calculates the average of the numbers by dividing the sum by n and storing the result in the average variable.

cout << "Average = " << average; – This line outputs the average of the numbers.

return 0; – This line returns 0 from the main function, indicating that the program ran successfully.

} – This brace closes the main function.

Example 34: Calculate Standard Deviation using Function

Output:

Here’s a line-by-line explanation of the code:

#include <iostream> – This line includes the input/output stream library iostream which allows the program to input and output data.

#include <cmath> – This line includes the cmath library which provides mathematical functions such as sqrt and pow.

using namespace std; – This line makes all elements in the standard namespace available to the program.

float calculateSD(float data[]); – This line declares a function named calculateSD which takes an array of floats as an argument and returns a float.

int main() – This line declares the main function, which is the entry point of the program.

int i; – This line declares an integer variable i which will be used as a loop counter.

float data[10]; – This line declares an array of 10 floating-point numbers named data.

cout << "Enter 10 elements: "; – This line outputs a prompt asking the user to enter 10 elements.

for(i = 0; i < 10; ++i) { – This line starts a for loop that will repeat 10 times, incrementing i by 1 each iteration.

cin >> data[i]; – This line inputs a number from the user and stores it in the ith element of the data array.

cout << endl << "Standard Deviation = " << calculateSD(data); – This line outputs a newline and the standard deviation of the elements by calling the calculateSD function and passing the data array as an argument.

return 0; – This line returns 0 from the main function, indicating that the program ran successfully.

} – This brace closes the main function.

float calculateSD(float data[]) – This line starts the definition of the calculateSD function.

float sum = 0.0, mean, standardDeviation = 0.0; – These lines declare three floating-point variables named sum, mean, and standardDeviation. sum will store the sum of the elements, mean will store their average, and standardDeviation will store the standard deviation.

for(i = 0; i < 10; ++i) { – This line starts a for loop that will repeat 10 times, incrementing i by 1 each iteration.

sum += data[i]; – This line adds the ith element of the data array to the sum variable.

mean = sum / 10; – This line calculates the average of the elements by dividing the sum by 10 and storing the result in the mean variable.

standardDeviation += pow(data[i] - mean, 2); – This line updates the standardDeviation variable by adding the square of the difference between the ith element of the data array and the mean.

return sqrt(standardDeviation / 10); – This line returns the square root of the standardDeviation divided by 10, which return sqrt(standardDeviation / 10);: Returns the square root of the standard deviation divided by 10, which is the sample size. This result represents the standard deviation of the given data set.

return 0;: Returns 0 to indicate that the program has executed successfully.

Example 35: Add Two Matrices using Multi-dimensional Arrays

Output:

Example 36: Pointers And Pointer Operations In C++

Output:

Explanation line by line:

int var = 20; – A variable named var is declared and initialized with a value of 20.

int *ip; – A pointer named ip is declared, with a data type of int.

ip = &var; – The address of the var variable is stored in the pointer ip. This is done using the & operator.

cout << "Value of var variable: "; – Writes “Value of var variable:” to the console.

cout << var << endl; – Writes the value of the var variable (which is 20) to the console, followed by a newline.

cout << "Address stored in ip variable: "; – Writes “Address stored in ip variable:” to the console.

cout << ip << endl; – Writes the address of the var variable, stored in the pointer ip, to the console, followed by a newline.

cout << "Value of *ip variable: "; – Writes “Value of *ip variable:” to the console.

cout << *ip << endl; – Writes the value stored at the address pointed to by ip (which is 20), to the console, followed by a newline.

Example 37: Pointers, arrays and pointer operations are fundamental concepts in C++ programming.

Here is an example in C++ that demonstrates these concepts and a line-by-line explanation of the code:

Output:

#include <iostream> – This line includes the iostream library, which provides the input/output stream functions in C++.

int arr[5] = {1, 2, 3, 4, 5}; – This line declares an array arr of size 5 and initializes its elements to 1, 2, 3, 4, and 5.

int *ptr = arr; – This line declares a pointer ptr of type int and initializes it to the starting address of the array arr.

std::cout << "Array elements using pointer: " << std::endl; – This line outputs the string “Array elements using pointer: ” to the standard output.

for (int i = 0; i < 5; i++) { – This line starts a for loop that will run 5 times.

std::cout << *ptr << std::endl; – This line outputs the value stored at the memory location pointed to by the pointer ptr. The * operator is used to dereference the pointer and access the value stored at the memory location.

ptr++; – This line increments the pointer ptr to point to the next memory location.

return 0; – This line returns 0 to indicate that the program executed successfully.

Example 38: Pointers and cin are fundamental concepts in C++ programming.

Here is an example in C++ that demonstrates these concepts and a line-by-line explanation of the code:

Output:

#include <iostream> – This line includes the iostream library, which provides the input/output stream functions in C++.

int num; – This line declares a variable num of type int.

int *ptr = &num; – This line declares a pointer ptr of type int and initializes it to the address of the variable num. The & operator is used to obtain the address of the variable num.

std::cout << "Enter a number: "; – This line outputs the string “Enter a number: ” to the standard output.

std::cin >> num; – This line inputs a number from the standard input and stores it in the variable num.

std::cout << "Value entered: " << *ptr << std::endl; – This line outputs the string “Value entered: ” followed by the value stored at the memory location pointed to by the pointer ptr. The * operator is used to dereference the pointer and access the value stored at the memory location.

return 0; – This line returns 0 to indicate that the program executed successfully.

Example 39: Lambdas In C++

Lambdas are a powerful feature in C++ that allow you to define anonymous functions (functions without a name) and use them in-place as function objects. Here is an example in C++ that demonstrates how to use lambdas and a line-by-line explanation of the code:

Output:

#include <iostream> – This line includes the iostream library, which provides the input/output stream functions in C++.

#include <algorithm> – This line includes the algorithm library, which provides the for_each function.

#include <vector> – This line includes the vector library, which provides the vector container class.

std::vector<int> numbers = {1, 2, 3, 4, 5}; – This line declares a vector numbers of size 5 and initializes its elements to 1, 2, 3, 4, and 5.

int total = 0; – This line declares a variable total of type int and initializes it to 0.

std::for_each(numbers.begin(), numbers.end(), [&total](int x) { total += x; }); – This line uses the for_each function to iterate through the elements of the vector numbers. The lambda [&total](int x) { total += x; } takes an int argument x and increments the variable total by x for each iteration. The & in [&total] captures the variable total by reference, so that changes made to total inside the lambda will be reflected outside.

std::cout << "Total: " << total << std::endl; – This line outputs the string “Total: ” followed by the value of the variable total to the standard output.

return 0; – This line returns 0 to indicate that the program executed successfully.

Example 40: An example in C++ that demonstrates how to use lambdas with loops and if control statements

#include <iostream> – This line includes the iostream library, which provides the input/output stream functions in C++.

#include <vector> – This line includes the vector library, which provides the vector container class.

std::vector<int> numbers = {1, 2, 3, 4, 5}; – This line declares a vector numbers of size 5 and initializes its elements to 1, 2, 3, 4, and 5.

int total = 0; – This line declares a variable total of type int and initializes it to 0.

for (int i = 0; i < numbers.size(); i++) { – This line starts a for loop that iterates numbers.size() times.

auto add_number = [&total, &numbers, i](int x) { – This line declares a lambda add_number that takes an int argument x and captures the variables total and numbers by reference and the variable i by value.

if (x >= numbers[i]) { – This line checks if the value of x is greater than or equal to the current value of numbers[i] in the loop.

total += x; – This line increments the value of total by x if the condition in the if statement is true.

add_number(10); and add_number(5); – These lines call the lambda add_number with the arguments 10 and 5.

std::cout << "Total: " << total << std::endl; – This line outputs the string “Total: ” followed by the value of the variable total to the standard output.

return 0; – This line returns 0 to indicate that the program executed successfully.

Example 41: An example in C++ that demonstrates how to use lambdas with cin and arrays

#include <iostream> – This line includes the iostream library, which provides the input/output stream functions in C++.

#include <vector> – This line includes the vector library, which provides the vector container class.

std::vector<int> numbers; – This line declares a vector numbers of type int.

int input = 0; – This line declares a variable input of type int and initializes it to 0.

int total = 0; – This line declares a variable total of type int and initializes it to 0.

auto add_number = [&total](int x) { – This line declares a lambda add_number that takes an int argument x and captures the variable total by reference.

total += x; – This line increments the value of total by x.

std::cout << "Enter numbers (enter -1 to stop):" << std::endl; – This line outputs the string “Enter numbers (enter -1 to stop):” to the standard output.

while (input != -1) { – This line starts a while loop that continues as long as the value of input is not equal to -1.

std::cin >> input; – This line reads an integer from the standard input into the variable input.

if (input != -1) { – This line checks if the value of input is not equal to -1.

numbers.push_back(input); – This line adds the value of input to the end of the vector numbers if the condition in the if statement is true.

for (const auto &x : numbers) { – This line starts a for loop that iterates through all elements in the vector numbers.

add_number(x); – This line calls the lambda add_number with the current value of x.

std::cout << "Total: " << total << std::endl; – This line outputs the string “Total: ” followed by the value of the variable total to the standard output.

return 0; – This line returns 0 to indicate that the program executed successfully.

Example 42: C++ Date Time

Here’s an example of how to use the C++ standard library’s chrono library to create a program that calculates the difference between two dates.

Output:

Example 43: C++ Date Time

Explanation:

  1. #include <iostream> – This is the standard input/output library in C++, used for printing to the console.
  2. #include <chrono> – This is the C++11 library for working with time.
  3. #include <ctime> – This library provides access to the standard C library functions for working with time.
  4. auto now = std::chrono::system_clock::now(); – Get the current time using the system_clock from <chrono>. auto automatically infers the type of now as std::chrono::time_point<std::chrono::system_clock>.
  5. std::time_t now_c = std::chrono::system_clock::to_time_t(now); – Convert the time_point to a std::time_t, which is a type that can be used with the standard C library time functions.
  6. std::cout << "Current date and time is: " << std::ctime(&now_c) << std::endl; – Use std::ctime to format the std::time_t as a string, and print it to the console using std::cout. The std::endl is a manipulator that adds a newline character.
  7. return 0; – This returns 0 from the main function to indicate that the program executed successfully.

Example 44: An example of using a while loop and an if statement to print the date for the next 5 days

Here’s an explanation of the above C++ code:

#include <iostream> – This is the standard input/output library in C++, used for printing to the console.

#include <chrono> – This is the C++11 library for working with time.

#include <ctime> – This library provides access to the standard C library functions for working with time.

int days = 5; – Define a variable days with the value 5. This represents the number of days that will be printed.

auto now = std::chrono::system_clock::now(); – Get the current time using the system_clock from <chrono>. auto automatically infers the type of now as std::chrono::time_point<std::chrono::system_clock>.

while (days > 0) – Start a while loop that will run as long as days is greater than 0.

now += std::chrono::hours(24); – Add 24 hours to the current time stored in now. This will advance the time by one day.

std::time_t now_c = std::chrono::system_clock::to_time_t(now); – Convert the time_point to a std::time_t, which is a type that can be used with the standard C library time functions.

if (std::strftime(buffer, sizeof(buffer), "%A, %B %d, %Y", std::localtime(&now_c))) – Use std::strftime to format the std::time_t as a string using the specified format (%A, %B %d, %Y represents the day of the week, the month, the day of the month, and the year, respectively). If the formatting is successful, the if statement will evaluate to true.

std::cout << "Date: " << buffer << std::endl; – If the formatting is successful, print the formatted date to the console using std::cout. The std::endl is a manipulator that adds a newline character.

days--; – Decrement the value of days by 1. This will eventually cause the while loop to terminate when days reaches 0.

return 0; – Return 0 from main to indicate successful termination of the program.

Example 45: An example of using the new and delete operators in C++

The new operator dynamically allocates memory on the heap for an object of a specific type and returns a pointer to the memory location. The delete operator frees the dynamically allocated memory and ensures that the memory is deallocated correctly, avoiding memory leaks.

Example 46: An example of using the new and delete operators with arrays in C++

Note that the delete operator must be used with the square brackets [] when freeing dynamically allocated arrays. This tells the compiler that the memory being freed is an array, rather than just a single object, and allows it to properly deallocate the memory for each element in the array.

Example 47: An example of how to create a class in C++

In this example, we create a class MyClass with a constructor that takes an int parameter, a private member variable value_, and a member function print that outputs the value of value_. In the main function, we create an object of the class MyClass and call its print method.

Example 48: A simple example of access modifiers in C++

Explanation:

  1. We start by including the iostream library, which provides the cout and endl objects for printing output to the console.
  2. We define a class Rectangle with private member variables length and width. These member variables are not accessible from outside the class.
  3. The Rectangle class has a constructor that takes length and width as parameters and sets the private member variables to these values.
  4. The class has a public method area that calculates and returns the area of the rectangle.
  5. In the main function, we create an instance of the Rectangle class with the length 10 and width 5.
  6. We then use the area method to calculate the area of the rectangle and print it to the console.
  7. Finally, we return 0 to indicate a successful execution of the program.

This example demonstrates the use of private access modifiers, which restrict the accessibility of member variables to within the class. In this case, the length and width member variables can only be accessed and modified through the class’s constructor and public methods.

Example 49: An example of using namespaces in C++ with a user-defined class

In this example, we define a namespace my_namespace and a class MyClass within it. In the main function, we create an object of the class MyClass and call its print method. By using the namespace, we ensure that our class won’t conflict with any classes of the same name defined in other parts of the program or libraries.

Example 50: A simple example of extending a class in C++

We then define a class Child that extends the Parent class using the : public Parent syntax.

The Child class has its own implementation of the print method that outputs “I am the child.” to the console.

In the main function, we create instances of both the Parent and Child classes.

We call the print method on both the Parent and Child objects. The output shows that the correct implementation of the print method is being called for each object.

Finally, we return 0 to indicate a successful execution of the program.

Example 51: A simple example of encapsulation in C++

Explanation:

We start by including the iostream library, which provides the cout and endl objects for printing output to the console.

We define a class Person with private member variables name and age. These member variables are not accessible from outside the class.

The Person class has a constructor that takes name and age as parameters and sets the private member variables to these values.

The class has public methods setName and setAge that allow the values of the private member variables to be changed.

The class also has public methods getName and getAge that return the values of the private member variables.

In the main function, we create an instance of the Person class with the name “John Doe” and age 30.

We then use the getName and getAge methods to access the values of the private member variables and print them to the console.

Finally, we return 0 to indicate a successful execution of the program.

Example 52: An example of polymorphism in C++, along with an explanation of each line

#include <iostream> – This is a preprocessor directive that includes the standard I/O library.

class Shape { – This declares the class Shape, which serves as a base class.

virtual double area() const = 0; – This declares a virtual method area() which returns a double value and has no implementation. The keyword virtual signifies that this method can be overridden by derived classes. The keyword = 0 makes this method abstract, meaning it must be overridden by any class that inherits from Shape.

class Rectangle : public Shape { – This declares the class Rectangle, which inherits from the Shape class. The public keyword signifies that the inheritance is public.

double length, width; – This declares two private member variables that represent the length and width of the rectangle.

Rectangle(double l, double w) : length(l), width(w) {} – This is the constructor for the Rectangle class. It takes two double values as arguments and initializes the length and width member variables.

double area() const override { return length * width; } – This is the implementation of the area() method for the Rectangle class. The keyword override signifies that this method is intended to override the area() method from the base class Shape. The implementation calculates the area of the rectangle as length * width.

class Circle : public Shape { – This declares the class Circle, which also inherits from the Shape class.

double radius; – This declares a private member variable that represents the radius of the circle.

Circle(double r) : radius(r) {} – This is the constructor for the Circle class. It takes one double value as an argument and initializes the radius member variable.

double area() const override { return 3.14159 * radius * radius; } – This is the implementation of the area() method for the Circle class. The implementation calculates the area of the circle as 3.14159 * radius * radius.

Shape *shape1 = new Rectangle(10, 5); – This creates a pointer to a Shape object and initializes it with a new Rectangle object, with length equal to 10 and width equal to 5.

Shape *shape2 = new Circle(2); – This creates another pointer to a Shape object and initializes it with a new Circle object, with radius equal to 2.

std::cout << "Area of rectangle: " << shape1->area() << std::endl; – This line outputs the area of the Rectangle object, which is calculated using the area() method and accessed via the pointer shape1.

std::cout << "Area of circle: " << shape2->area() << std::endl; – This line outputs the area of the Circle object, which is calculated using the area() method and accessed via the pointer shape2.

return 0; – This line returns 0, indicating successful execution of the program.

With polymorphism, we can treat objects of different classes that inherit from a common base class in a uniform manner, as in this example where we use pointers to Shape objects to access the area() method. The actual implementation of the area() method used will depend on the type of object the pointer is pointing to, i.e., either Rectangle or Circle.

Example 53: Friend Functions In C++

An example of a friend function in C++, along with an explanation of each line.

#include <iostream> – This line includes the iostream header, which provides standard input/output functions.

class Complex { – This line declares a class called Complex.

double real, imag; – This line declares two public member variables, real and imag, which represent the real and imaginary parts of a complex number.

Complex(double r, double i) : real(r), imag(i) {} – This line declares the constructor for the Complex class. The constructor takes two double values r and i as arguments and initializes the real and imag member variables with them.

friend Complex operator+(const Complex &c1, const Complex &c2); – This line declares a friend function called operator+, which takes two const Complex & references as arguments and returns a Complex object. The friend keyword allows this non-member function to access the private members of the Complex class.

Complex operator+(const Complex &c1, const Complex &c2) { – This line defines the operator+ friend function.

return Complex(c1.real + c2.real, c1.imag + c2.imag); – This line returns a Complex object that represents the sum of the two complex numbers passed as arguments to the operator+ function. The sum is calculated by adding the real parts and the imaginary parts of the two complex numbers.

Complex c1(1, 2), c2(3, 4); – This line declares two Complex objects c1 and c2 and initializes them with the values (1, 2) and (3, 4), respectively.

Complex c3 = c1 + c2; – This line declares a third Complex object c3 and initializes it with the sum of c1 and c2. This is done by calling the operator+ function.

std::cout << "c3 = " << c3.real << " + " << c3.imag << "i" << std::endl; – This line outputs the value of c3 to the standard output stream. The value is displayed in the format real + imag i, where real is the real part and imag is the imaginary part of the Complex object c3.

return 0; – This line returns 0 to indicate the successful execution of the program.

In this code, we define a class Complex to represent complex numbers and a friend function operator+ to perform addition on Complex objects. The operator+ function is declared as a friend function to allow it to access the private members of the Complex class. The code demonstrates how to use the Complex class and the operator+ function to add two complex numbers.

Example 54: An example of multithreading in C++ using the thread library

In this example, the printMessage function is executed in a separate thread by passing it to a std::thread object, t. The join function is used to wait for the new thread to finish before ending the program.

The std::thread class provides several member functions for managing the state of a thread, such as join, detach, get_id, and hardware_concurrency. The join function blocks the calling thread until the thread represented by std::thread has finished its execution. The detach function allows a thread to run freely on its own, without the need for the calling thread to wait for its completion.

It’s important to note that multithreading comes with its own set of challenges and potential bugs, such as race conditions, deadlocks, and resource conflicts. Good understanding of thread synchronization and mutual exclusion is necessary to avoid these issues.

Example 55: An example of using multithreading with a class in C++

In this example, the HelloWorld class has an overloaded operator() that is executed in a separate thread when a std::thread object is constructed with an instance of HelloWorld. The thread is then joined to wait for its completion.

The same synchronization and mutual exclusion considerations apply as in regular multithreading with std::thread. It’s also good practice to make sure the class is copyable or movable if it is to be used with std::thread, to avoid undefined behavior.

Leave a Comment