C - Program For Practice
C - Program For Practice
Table of Contents
Example 1: Print Number Entered by User
Example 2: Program to Add Two Integers
Example 3: Compute quotient and remainder
Example 4: Swap Numbers (Using Temporary Variable)
Example 5: Swap Numbers Without Using Temporary Variables
Example 6: Check Whether Number is Even or Odd using if else
Example 7: Check Whether Number is Even or Odd using ternary operators
Example 8: Find Largest Number Using if…else Statement
Example 9: Find the Largest Number Using Nested if…else statement
Example 10: Roots of a Quadratic Equation
Example 11: Sum of Natural Numbers using loop
Example 12: Check Leap Year Using if…else Ladder
Example 13: Check Leap Year Using Nested if
Example 14: Find the Factorial of a Given Number
Example 15: Display Multiplication Table up to a Given Range
Example 16: Fibonacci Series up to n number of terms
Example 17: Program to Generate Fibonacci Sequence Up to a Certain Number
Example 18: Find HCF/GCD using for loop
Example 19: Find GCD/HCF using while loop
Example 20: Find LCM
Example 21: C++ Program to Reverse an Integer
Example 22: C++ Program to Calculate Power of a Number
Example 23: C++ Program to Subtract Complex Number Using Operator
Overloading
Example 24: C++ Program to Check Whether a Number is Palindrome or Not
Example 25: C++ Program to Check Whether a Number is Prime or Not
Example 26: Display all Factors of a Number
Example 27: Program to Print a Half-Pyramid Using *
Example 28: Inverted Half-Pyramid Using *
Example 29: Program to Print a Full Pyramid Using *
Example 30: Inverted Full Pyramid Using *
Example 31: Simple Calculator using switch statement
Example 32: Prime Numbers Between two Intervals
Example 33: Calculate Average of Numbers Using Arrays
Example 34: Calculate Standard Deviation using Function
Example 35: Add Two Matrices using Multi-dimensional Arrays
Example 36: Pointers And Pointer Operations In C++
Example 37: Pointers, arrays and pointer operations are fundamental concepts
in C++ programming.
Example 38: Pointers and cin are fundamental concepts in C++ programming.
Example 39: Lambdas In C++
Example 40: An example in C++ that demonstrates how to use lambdas with
loops and if control statements
Example 41: An example in C++ that demonstrates how to use lambdas with cin
and arrays
Example 42: C++ Date Time
Example 43: C++ Date Time
Example 44: An example of using a while loop and an if statement to print the
date for the next 5 days
Example 45: An example of using the new and delete operators in C++
Example 46: An example of using the new and delete operators with arrays in C+
+
Example 47: An example of how to create a class in C++
Example 48: A simple example of access modifiers in C++
Example 49: An example of using namespaces in C++ with a user-defined class
Example 50: A simple example of extending a class in C++
Example 51: A simple example of encapsulation in C++
Example 52: An example of polymorphism in C++, along with an explanation of
each line
Example 53: Friend Functions In C++
Example 54: An example of multithreading in C++ using the thread library
Example 55: An example of using multithreading with a class in C++
1
2 Enter an integer: 112
3 You entered 112
4
Here’s an explanation of the code line by line:
1
2 Enter two integers: 12
3 23
4 12 + 23 = 35
5
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.
1
2 Enter dividend: 120
3 Enter divisor: 25
4 Quotient = 4
5 Remainder = 20
6
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)
1
2 #include <iostream>
3 using namespace std;
4
5 int main()
6 {
7 int a = 5, b = 10, temp;
8
9 cout << "Before swapping." << endl;
10 cout << "a = " << a << ", b = " << b << endl;
11
12 temp = a;
13 a = b;
14 b = temp;
15
16 cout << "\nAfter swapping." << endl;
17 cout << "a = " << a << ", b = " << b << endl;
18
19 return 0;
20 }
21
Output:
1
2 Before swapping.
3 a = 5, b = 10
4
5 After swapping.
6 a = 10, b = 5
7
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
1
2 #include <iostream>
3 using namespace std;
4
5 int main()
6 {
7
8 int a = 5, b = 10;
9
10 cout << "Before swapping." << endl;
11 cout << "a = " << a << ", b = " << b << endl;
12
13 a = a + b;
14 b = a - b;
15 a = a - b;
16
17 cout << "\nAfter swapping." << endl;
18 cout << "a = " << a << ", b = " << b << endl;
19
20 return 0;
21 }
22
Output:
1
2 Before swapping.
3 a = 5, b = 10
4
5 After swapping.
6 a = 10, b = 5
7
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
1
2 #include <iostream>
3 using namespace std;
4
5 int main() {
6 int n;
7
8 cout << "Enter an integer: ";
9 cin >> n;
10
11 if ( n % 2 == 0)
12 cout << n << " is even.";
13 else
14 cout << n << " is odd.";
15
16 return 0;
17 }
18
Output:
1
2 Enter an integer: 123
3 123 is odd.
4
Explanation line by line:
1
2 Enter an integer: 246
3 246 is even.
4
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.
1
2 #include <iostream>
3 using namespace std;
4
5 int main() {
6
7 double n1, n2, n3;
8
9 cout << "Enter three numbers: ";
10 cin >> n1 >> n2 >> n3;
11
12 // check if n1 is the largest number
13 if(n1 >= n2 && n1 >= n3)
14 cout << "Largest number: " << n1;
15
16 // check if n2 is the largest number
17 else if(n2 >= n1 && n2 >= n3)
18 cout << "Largest number: " << n2;
19
20 // if neither n1 nor n2 are the largest, n3 is the largest
21 else
22 cout << "Largest number: " << n3;
23
24 return 0;
25 }
26
Output:
1
2 Enter three numbers: 50
3 30
4 40
5 Largest number: 50
6
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.
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.
The main function returns 0, indicating that the program has run successfully.
1
2 Enter three numbers: 50
3 30
4 40
5 Largest number: 50
6
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
1
2 #include <iostream>
3 #include <cmath>
4 using namespace std;
5
6 int main() {
7
8 float a, b, c, x1, x2, discriminant, realPart, imaginaryPart;
9 cout << "Enter coefficients a, b and c: ";
10 cin >> a >> b >> c;
11 discriminant = b*b - 4*a*c;
12
13 if (discriminant > 0) {
14 x1 = (-b + sqrt(discriminant)) / (2*a);
15 x2 = (-b - sqrt(discriminant)) / (2*a);
16 cout << "Roots are real and different." << endl;
17 cout << "x1 = " << x1 << endl;
18 cout << "x2 = " << x2 << endl;
19 }
20
21 else if (discriminant == 0) {
22 cout << "Roots are real and same." << endl;
23 x1 = -b/(2*a);
24 cout << "x1 = x2 =" << x1 << endl;
25 }
26
27 else {
28 realPart = -b/(2*a);
29 imaginaryPart =sqrt(-discriminant)/(2*a);
30 cout << "Roots are complex and different." << endl;
31 cout << "x1 = " << realPart << "+" << imaginaryPart << "i" << endl;
32 cout << "x2 = " << realPart << "-" << imaginaryPart << "i" << endl;
33 }
34
35 return 0;
36 }
37
Output:
1
2 Enter coefficients a, b and c: 8
3 10
42
5 Roots are real and different.
6 x1 = -0.25
7 x2 = -1
8
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
1
2 #include <iostream>
3 using namespace std;
4
5 int main() {
6 int n, sum = 0;
7
8 cout << "Enter a positive integer: ";
9 cin >> n;
10
11 for (int i = 1; i <= n; ++i) {
12 sum += i;
13 }
14
15 cout << "Sum = " << sum;
16 return 0;
17 }
18
Output:
1
2 Enter a positive integer: 23
3 Sum = 276
4
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.
1
2 #include <iostream>
3 using namespace std;
4
5 int main() {
6
7 int year;
8 cout << "Enter a year: ";
9 cin >> year;
10
11 // leap year if perfectly divisible by 400
12 if (year % 400 == 0) {
13 cout << year << " is a leap year.";
14 }
15 // not a leap year if divisible by 100
16 // but not divisible by 400
17 else if (year % 100 == 0) {
18 cout << year << " is not a leap year.";
19 }
20 // leap year if not divisible by 100
21 // but divisible by 4
22 else if (year % 4 == 0) {
23 cout << year << " is a leap year.";
24 }
25 // all other years are not leap years
26 else {
27 cout << year << " is not a leap year.";
28 }
29
30 return 0;
31 }
32
Output:
1
2 Enter a year: 2004
3 2004 is a leap year.
4
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.
1
2 Enter a year: 2004
3 2004 is a leap year.
4
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 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.
1
2 Enter an integer: 7
3 Enter range: 10
4 7*1=7
5 7 * 2 = 14
6 7 * 3 = 21
7 7 * 4 = 28
8 7 * 5 = 35
9 7 * 6 = 42
10 7 * 7 = 49
11 7 * 8 = 56
12 7 * 9 = 63
13 7 * 10 = 70
14
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”.
1
2 Enter the number of terms: 20
3 Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181,
4
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
1
2 #include <iostream>
3 using namespace std;
4
5 int main() {
6 int t1 = 0, t2 = 1, nextTerm = 0, n;
7
8 cout << "Enter a positive number: ";
9 cin >> n;
10
11 // displays the first two terms which is always 0 and 1
12 cout << "Fibonacci Series: " << t1 << ", " << t2 << ", ";
13
14 nextTerm = t1 + t2;
15
16 while(nextTerm <= n) {
17 cout << nextTerm << ", ";
18 t1 = t2;
19 t2 = nextTerm;
20 nextTerm = t1 + t2;
21 }
22 return 0;
23 }
24
Output:
1
2 Enter a positive number: 50
3 Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
4
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
1
2 #include <iostream>
3 using namespace std;
4
5 int main() {
6 int n1, n2, hcf;
7 cout << "Enter two numbers: ";
8 cin >> n1 >> n2;
9
10 // swapping variables n1 and n2 if n2 is greater than n1.
11 if ( n2 > n1) {
12 int temp = n2;
13 n2 = n1;
14 n1 = temp;
15 }
16
17 for (int i = 1; i <= n2; ++i) {
18 if (n1 % i == 0 && n2 % i ==0) {
19 hcf = i;
20 }
21 }
22
23 cout << "HCF = " << hcf;
24
25 return 0;
26 }
27
Output:
1
2 Enter two numbers: 12
3 16
4 HCF = 4
5
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
1
2 #include <iostream>
3 using namespace std;
4
5 int main() {
6 int n1, n2;
7
8 cout << "Enter two numbers: ";
9 cin >> n1 >> n2;
10
11 while(n1 != n2) {
12 if(n1 > n2)
13 n1 -= n2;
14 else
15 n2 -= n1;
16 }
17
18 cout << "HCF = " << n1;
19
20 return 0;
21 }
22
Output:
1
2 Enter two numbers: 12
3 16
4 HCF = 4
5
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
1
2 #include <iostream>
3 using namespace std;
4
5 int main()
6 {
7 int n1, n2, max;
8
9 cout << "Enter two numbers: ";
10 cin >> n1 >> n2;
11
12 // maximum value between n1 and n2 is stored in max
13 max = (n1 > n2) ? n1 : n2;
14
15 do
16 {
17 if (max % n1 == 0 && max % n2 == 0)
18 {
19 cout << "LCM = " << max;
20 break;
21 }
22 else
23 ++max;
24 } while (true);
25
26 return 0;
27 }
28
Output:
1
2 Enter two numbers: 12
3 16
4 LCM = 48
5
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
1
2 #include <iostream>
3 using namespace std;
4
5 int main() {
6
7 int n, reversed_number = 0, remainder;
8
9 cout << "Enter an integer: ";
10 cin >> n;
11
12 while(n != 0) {
13 remainder = n % 10;
14 reversed_number = reversed_number * 10 + remainder;
15 n /= 10;
16 }
17
18 cout << "Reversed Number = " << reversed_number;
19
20 return 0;
21 }
22
Output:
1
2 Enter an integer: 12345
3 Reversed Number = 54321
4
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.
1
2 Enter base and exponent respectively: 5
33
4 5^3 = 125
5
The program starts with the inclusion of the iostream header file.
1
2 #include <iostream>
3 using namespace std;
4
5 class Complex
6 {
7 private:
8 float real;
9 float imag;
10 public:
11 Complex(): real(0), imag(0){ }
12 void input()
13 {
14 cout << "Enter real and imaginary parts respectively: ";
15 cin >> real;
16 cin >> imag;
17 }
18
19 // Operator overloading
20 Complex operator - (Complex c2)
21 {
22 Complex temp;
23 temp.real = real - c2.real;
24 temp.imag = imag - c2.imag;
25
26 return temp;
27 }
28
29 void output()
30 {
31 if(imag < 0)
32 cout << "Output Complex number: "<< real << imag << "i";
33 else
34 cout << "Output Complex number: " << real << "+" << imag << "i";
35 }
36 };
37
38 int main()
39 {
40 Complex c1, c2, result;
41
42 cout<<"Enter first complex number:\n";
43 c1.input();
44
45 cout<<"Enter second complex number:\n";
46 c2.input();
47
48 // In case of operator overloading of binary operators in C++ programming,
49 // the object on right hand side of operator is always assumed as argument by compiler.
50 result = c1 - c2;
51 result.output();
52
53 return 0;
54 }
55
Output:
1
2 Enter first complex number:
3 Enter real and imaginary parts respectively: 10 25
4 Enter second complex number:
5 Enter real and imaginary parts respectively: 25 15
6 Output Complex number: -15+10i
7
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
1
2 #include <iostream>
3 using namespace std;
4
5 int main()
6 {
7 int n, num, digit, rev = 0;
8
9 cout << "Enter a positive number: ";
10 cin >> num;
11
12 n = num;
13
14 do
15 {
16 digit = num % 10;
17 rev = (rev * 10) + digit;
18 num = num / 10;
19 } while (num != 0);
20
21 cout << " The reverse of the number is: " << rev << endl;
22
23 if (n == rev)
24 cout << " The number is a palindrome.";
25 else
26 cout << " The number is not a palindrome.";
27
28 return 0;
29 }
30
Output:
1
2 Enter a positive number: 123321
3 The reverse of the number is: 123321
4 The number is a palindrome.
5
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
1
2 #include <iostream>
3 using namespace std;
4
5 int main() {
6
7 int i, n;
8 bool is_prime = true;
9
10 cout << "Enter a positive integer: ";
11 cin >> n;
12
13 // 0 and 1 are not prime numbers
14 if (n == 0 || n == 1) {
15 is_prime = false;
16 }
17
18 // loop to check if n is prime
19 for (i = 2; i <= n/2; ++i) {
20 if (n % i == 0) {
21 is_prime = false;
22 break;
23 }
24 }
25
26 if (is_prime)
27 cout << n << " is a prime number";
28 else
29 cout << n << " is not a prime number";
30
31 return 0;
32 }
33
Output:
1
2 Enter a positive integer: 53
3 53 is a prime number
4
#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
1
2 #include <iostream>
3 using namespace std;
4
5 int main() {
6 int n, i;
7
8 cout << "Enter a positive integer: ";
9 cin >> n;
10
11 cout << "Factors of " << n << " are: ";
12 for(i = 1; i <= n; ++i) {
13 if(n % i == 0)
14 cout << i << " ";
15 }
16
17 return 0;
18 }
19
Output:
1
2 Enter a positive integer: 12
3 Factors of 12 are: 1 2 3 4 6 12
4
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 *
1
2 #include <iostream>
3 using namespace std;
4
5 int main() {
6
7 int rows;
8
9 cout << "Enter number of rows: ";
10 cin >> rows;
11
12 for(int i = 1; i <= rows; ++i) {
13 for(int j = 1; j <= i; ++j) {
14 cout << "* ";
15 }
16 cout << "\n";
17 }
18 return 0;
19 }
20
Output:
1
2 Enter number of rows: 10
3 *
4 **
5 ***
6 ****
7 *****
8 ******
9 *******
10 * * * * * * * *
11 * * * * * * * * *
12 * * * * * * * * * *
13
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 *
1
2 #include <iostream>
3 using namespace std;
4
5 int main() {
6
7 int rows;
8
9 cout << "Enter number of rows: ";
10 cin >> rows;
11
12 for(int i = rows; i >= 1; --i) {
13 for(int j = 1; j <= i; ++j) {
14 cout << "* ";
15 }
16 cout << endl;
17 }
18
19 return 0;
20 }
21
Output:
1
2 Enter number of rows: 10
3 **********
4 *********
5 ********
6 *******
7 ******
8 *****
9 ****
10 * * *
11 * *
12 *
13
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 *
1
2 #include <iostream>
3 using namespace std;
4
5 int main() {
6
7 int space, rows;
8
9 cout <<"Enter number of rows: ";
10 cin >> rows;
11
12 for(int i = 1, k = 0; i <= rows; ++i, k = 0) {
13 for(space = 1; space <= rows-i; ++space) {
14 cout <<" ";
15 }
16
17 while(k != 2*i-1) {
18 cout << "* ";
19 ++k;
20 }
21 cout << endl;
22 }
23 return 0;
24 }
25
Output:
1
2 Enter number of rows: 10
3 *
4 ***
5 *****
6 *******
7 *********
8 ***********
9 *************
10 * * * * * * * * * * * * * * *
11 * * * * * * * * * * * * * * * * *
12 * * * * * * * * * * * * * * * * * * *
13
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 *
1
2 #include <iostream>
3 using namespace std;
4
5 int main() {
6
7 int rows;
8
9 cout << "Enter number of rows: ";
10 cin >> rows;
11
12 for(int i = rows; i >= 1; --i) {
13 for(int space = 0; space < rows-i; ++space)
14 cout << " ";
15
16 for(int j = i; j <= 2*i-1; ++j)
17 cout << "* ";
18
19 for(int j = 0; j < i-1; ++j)
20 cout << "* ";
21
22 cout << endl;
23 }
24
25 return 0;
26 }
27
Output:
1
2 Enter number of rows: 10
3 *******************
4 *****************
5 ***************
6 *************
7 ***********
8 *********
9 *******
10 *****
11 ***
12 *
13
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
1
2 # include <iostream>
3 using namespace std;
4
5 int main() {
6
7 char op;
8 float num1, num2;
9
10 cout << "Enter operator: +, -, *, /: ";
11 cin >> op;
12
13 cout << "Enter two operands: ";
14 cin >> num1 >> num2;
15
16 switch(op) {
17
18 case '+':
19 cout << num1 << " + " << num2 << " = " << num1 + num2;
20 break;
21
22 case '-':
23 cout << num1 << " - " << num2 << " = " << num1 - num2;
24 break;
25
26 case '*':
27 cout << num1 << " * " << num2 << " = " << num1 * num2;
28 break;
29
30 case '/':
31 cout << num1 << " / " << num2 << " = " << num1 / num2;
32 break;
33
34 default:
35 // If the operator is other than +, -, * or /, error message is shown
36 cout << "Error! operator is not correct";
37 break;
38 }
39
40 return 0;
41 }
42
Output:
1
2 Enter operator: +, -, *, /: *
3 Enter two operands: 10 20
4 10 * 20 = 200
5
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 “using namespace std” statement allows the use of standard library objects and
functions without the need to qualify them with the std namespace.
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 “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.
1
2 Enter two positive integers: 10 20
3 Prime numbers between 10 and 20 are:
4 11, 13, 17, 19,
5
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 “using namespace std” statement allows the use of standard library objects and
functions without the need to qualify them with the std namespace.
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 “return 0” statement is used to indicate that the “main” function has executed
successfully.
1
2 Enter the numbers of data: 5
3 1. Enter number: 20
4 2. Enter number: 25
5 3. Enter number: 13
6 4. Enter number: 14
7 5. Enter number: 10
8 Average = 16.4
9
Here’s a line-by-line explanation of the code:
1
2 Enter 10 elements: 10
3 30
4 25
5 45
6 74
7 52
8 10
9 30
10 50
11 60
12
13 Standard Deviation = 20.0759
14
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
1
2 #include <iostream>
3 using namespace std;
4
5 int main()
6 {
7 int r, c, a[100][100], b[100][100], sum[100][100], i, j;
8
9 cout << "Enter number of rows (between 1 and 100): ";
10 cin >> r;
11
12 cout << "Enter number of columns (between 1 and 100): ";
13 cin >> c;
14
15 cout << endl << "Enter elements of 1st matrix: " << endl;
16
17 // Storing elements of first matrix entered by user.
18 for(i = 0; i < r; ++i)
19 for(j = 0; j < c; ++j)
20 {
21 cout << "Enter element a" << i + 1 << j + 1 << " : ";
22 cin >> a[i][j];
23 }
24
25 // Storing elements of second matrix entered by user.
26 cout << endl << "Enter elements of 2nd matrix: " << endl;
27 for(i = 0; i < r; ++i)
28 for(j = 0; j < c; ++j)
29 {
30 cout << "Enter element b" << i + 1 << j + 1 << " : ";
31 cin >> b[i][j];
32 }
33
34 // Adding Two matrices
35 for(i = 0; i < r; ++i)
36 for(j = 0; j < c; ++j)
37 sum[i][j] = a[i][j] + b[i][j];
38
39 // Displaying the resultant sum matrix.
40 cout << endl << "Sum of two matrix is: " << endl;
41 for(i = 0; i < r; ++i)
42 for(j = 0; j < c; ++j)
43 {
44 cout << sum[i][j] << " ";
45 if(j == c - 1)
46 cout << endl;
47 }
48
49 return 0;
50 }
51
Output:
1
2 Enter number of rows (between 1 and 100): 3
3 Enter number of columns (between 1 and 100): 3
4
5 Enter elements of 1st matrix:
6 Enter element a11 : 10
7 Enter element a12 : 20
8 Enter element a13 : 30
9 Enter element a21 : 45
10 Enter element a22 : 20
11 Enter element a23 : 12
12 Enter element a31 : 30
13 Enter element a32 : 52
14 Enter element a33 : 30
15
16 Enter elements of 2nd matrix:
17 Enter element b11 : 20
18 Enter element b12 : 30
19 Enter element b13 : 52
20 Enter element b21 : 56
21 Enter element b22 : 10
22 Enter element b23 : 30
23 Enter element b31 : 50
24 Enter element b32 : 10
25 Enter element b33 : 30
26
27 Sum of two matrix is:
28 30 50 82
29 101 30 42
30 80 62 60
31
Example 36: Pointers And Pointer Operations In C++
1
2 #include <iostream>
3 using namespace std;
4
5 int main()
6 {
7 int var = 20; // actual variable declaration
8 int *ip; // pointer variable declaration
9
10 ip = &var; // store address of var in pointer variable
11
12 cout << "Value of var variable: ";
13 cout << var << endl;
14
15 // address stored in pointer variable
16 cout << "Address stored in ip variable: ";
17 cout << ip << endl;
18
19 // access the value at the address available in pointer
20 cout << "Value of *ip variable: ";
21 cout << *ip << endl;
22
23 return 0;
24 }
25
Output:
1
2 Value of var variable: 20
3 Address stored in ip variable: 0x7ffc2b032cec
4 Value of *ip variable: 20
5
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:
1
2 #include <iostream>
3
4 int main() {
5 int arr[5] = {1, 2, 3, 4, 5};
6 int *ptr = arr;
7
8 std::cout << "Array elements using pointer: " << std::endl;
9 for (int i = 0; i < 5; i++) {
10 std::cout << *ptr << std::endl;
11 ptr++;
12 }
13 return 0;
14 }
15
Output:
1
2 Array elements using pointer:
31
42
53
64
75
8
#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.
1
2 #include <iostream>
3
4 int main() {
5 int num;
6 int *ptr = #
7
8 std::cout << "Enter a number: ";
9 std::cin >> num;
10 std::cout << "Value entered: " << *ptr << std::endl;
11
12 return 0;
13 }
14
Output:
1
2 Enter a number: 123
3 Value entered: 123
4
#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 = # – 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:
1
2 #include <iostream>
3 #include <algorithm>
4 #include <vector>
5
6 int main() {
7 std::vector<int> numbers = {1, 2, 3, 4, 5};
8 int total = 0;
9
10 std::for_each(numbers.begin(), numbers.end(),
11 [&total](int x) {
12 total += x;
13 }
14 );
15
16 std::cout << "Total: " << total << std::endl;
17
18 return 0;
19 }
20
Output:
1
2 Total: 15
3
#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
1
2 #include <iostream>
3 #include <vector>
4
5 int main() {
6 std::vector<int> numbers = {1, 2, 3, 4, 5};
7 int total = 0;
8
9 for (int i = 0; i < numbers.size(); i++) {
10 auto add_number = [&total, &numbers, i](int x) {
11 if (x >= numbers[i]) {
12 total += x;
13 }
14 };
15
16 add_number(10);
17 add_number(5);
18 }
19
20 std::cout << "Total: " << total << std::endl;
21
22 return 0;
23 }
24
#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
1
2 #include <iostream>
3 #include <vector>
4
5 int main() {
6 std::vector<int> numbers;
7 int input = 0;
8 int total = 0;
9
10 auto add_number = [&total](int x) {
11 total += x;
12 };
13
14 std::cout << "Enter numbers (enter -1 to stop):" << std::endl;
15 while (input != -1) {
16 std::cin >> input;
17 if (input != -1) {
18 numbers.push_back(input);
19 }
20 }
21
22 for (const auto &x : numbers) {
23 add_number(x);
24 }
25
26 std::cout << "Total: " << total << std::endl;
27
28 return 0;
29 }
30
#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.
1
#include <iostream>
2
#include <chrono>
3
#include <ctime>
4
5
int main() {
6
// Define two dates as time points
7
std::chrono::system_clock::time_point date1 = std::chrono::system_clock::now();
8
std::chrono::system_clock::time_point date2 =
9
std::chrono::system_clock::from_time_t(std::time(nullptr));
10
11
// Calculate the difference between the two time points in seconds
12
auto duration = date1 - date2;
13
std::cout << "The difference between the two dates is "
14
<< std::chrono::duration_cast<std::chrono::seconds>(duration).count()
15
<< " seconds." << std::endl;
16
17
return 0;
18
}
19
Output:
1
2 The difference between the two dates is 0 seconds.
3
Example 43: C++ Date Time
1
2 #include <iostream>
3 #include <chrono>
4 #include <ctime>
5
6 int main() {
7 auto now = std::chrono::system_clock::now();
8 std::time_t now_c = std::chrono::system_clock::to_time_t(now);
9
10 std::cout << "Current date and time is: " << std::ctime(&now_c) << std::endl;
11
12 return 0;
13 }
14
Current
date and
1 time is:
2 Sat Feb
3 4
10:39:51
2023
Explanation:
Date:
Sunday,
February
05, 2023
Date:
Monday,
February
1
06, 2023
2
Date:
3
Tuesday,
4
February
5
07, 2023
6
Date:
7
Wednesday,
February
08, 2023
Date:
Thursday,
February
09, 2023
#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++
1
2 #include <iostream>
3
4 int main() {
5 int *p = new int; // allocate memory for an integer
6 *p = 42; // store the value 42 in the dynamically allocated memory
7 std::cout << *p << std::endl; // output the value of the dynamically allocated memory
8 delete p; // free the dynamically allocated memory
9
10 return 0;
11 }
12
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++
1
2 #include <iostream>
3
4 int main() {
5 int n = 5;
6 int *p = new int[n]; // allocate memory for an array of 5 integers
7 for (int i = 0; i < n; i++) {
8 p[i] = i * 2; // store values in the dynamically allocated memory
9 }
10 for (int i = 0; i < n; i++) {
11 std::cout << p[i] << " "; // output the values of the dynamically allocated memory
12 }
13 std::cout << std::endl;
14 delete[] p; // free the dynamically allocated memory
15
16 return 0;
17 }
18
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++
1
2 #include <iostream>
3
4 class MyClass {
5 public:
6 // Constructor
7 MyClass(int value) : value_(value) {}
8
9 // Member function
10 void print() const {
11 std::cout << "Value: " << value_ << std::endl;
12 }
13
14 private:
15 int value_; // Private member variable
16 };
17
18 int main() {
19 MyClass object(42); // Create an object of the class
20 object.print(); // Call the member function
21
22 return 0;
23 }
24
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++
1
2 #include <iostream>
3
4 class Rectangle {
5 private:
6 int length;
7 int width;
8
9 public:
10 Rectangle(int length, int width) {
11 this->length = length;
12 this->width = width;
13 }
14
15 int area() {
16 return length * width;
17 }
18 };
19
20 int main() {
21 Rectangle rectangle(10, 5);
22
23 std::cout << "Area: " << rectangle.area() << std::endl;
24
25 return 0;
26 }
27
Explanation:
Example 52: An example of polymorphism in C++, along with an explanation of each line
1
2 #include <iostream>
3
4 class Shape {
5 public:
6 virtual double area() const = 0;
7 };
8
9 class Rectangle : public Shape {
10 private:
11 double length, width;
12 public:
13 Rectangle(double l, double w) : length(l), width(w) {}
14 double area() const override {
15 return length * width;
16 }
17 };
18
19 class Circle : public Shape {
20 private:
21 double radius;
22 public:
23 Circle(double r) : radius(r) {}
24 double area() const override {
25 return 3.14159 * radius * radius;
26 }
27 };
28
29 int main() {
30 Shape *shape1 = new Rectangle(10, 5);
31 Shape *shape2 = new Circle(2);
32
33 std::cout << "Area of rectangle: " << shape1->area() << std::endl;
34 std::cout << "Area of circle: " << shape2->area() << std::endl;
35
36 return 0;
37 }
38
Area of
1 rectangle:
2 50
3 Area of
4 circle:
12.5664
1
2 #include <iostream>
3
4 class Complex {
5 public:
6 double real, imag;
7
8 public:
9 Complex(double r, double i) : real(r), imag(i) {}
10
11 friend Complex operator+(const Complex &c1, const Complex &c2);
12 };
13
14 Complex operator+(const Complex &c1, const Complex &c2) {
15 return Complex(c1.real + c2.real, c1.imag + c2.imag);
16 }
17
18 int main() {
19 Complex c1(1, 2), c2(3, 4);
20 Complex c3 = c1 + c2;
21
22 std::cout << "c3 = " << c3.real << " + " << c3.imag << "i" << std::endl;
23
24 return 0;
25 }
26
c3
1 =
2 4
3 +
6i
#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
1
2 #include <iostream>
3 #include <thread>
4
5 void printMessage(std::string message)
6 {
7 std::cout << "Thread says: " << message << std::endl;
8 }
9
10 int main()
11 {
12 std::string message = "Hello from the new thread!";
13 std::thread t(printMessage, message);
14
15 std::cout << "Main thread says: Hello from the main thread!" << std::endl;
16
17 t.join(); // Wait for the thread to finish
18
19 return 0;
20 }
21
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.