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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #include <iostream> using namespace std; int main() { int number; cout << "Enter an integer: "; cin >> number; cout << "You entered " << number; return 0; } |
Output:
1 2 3 4 | Enter an integer: 112 You entered 112 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include <iostream> using namespace std; int main() { int first_number, second_number, sum; cout << "Enter two integers: "; cin >> first_number >> second_number; // sum of two numbers in stored in variable sumOfTwoNumbers sum = first_number + second_number; // prints sum cout << first_number << " + " << second_number << " = " << sum; return 0; } |
Output:
1 2 3 4 5 | Enter two integers: 12 23 12 + 23 = 35 |
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.
Example 3: Compute quotient and remainder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #include <iostream> using namespace std; int main() { int divisor, dividend, quotient, remainder; cout << "Enter dividend: "; cin >> dividend; cout << "Enter divisor: "; cin >> divisor; quotient = dividend / divisor; remainder = dividend % divisor; cout << "Quotient = " << quotient << endl; cout << "Remainder = " << remainder; return 0; } |
Output:
1 2 3 4 5 6 | Enter dividend: 120 Enter divisor: 25 Quotient = 4 Remainder = 20 |
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 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include <iostream> using namespace std; int main() { int a = 5, b = 10, temp; cout << "Before swapping." << endl; cout << "a = " << a << ", b = " << b << endl; temp = a; a = b; b = temp; cout << "\nAfter swapping." << endl; cout << "a = " << a << ", b = " << b << endl; return 0; } |
Output:
1 2 3 4 5 6 7 | Before swapping. a = 5, b = 10 After swapping. a = 10, b = 5 |
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.
Example 5: Swap Numbers Without Using Temporary Variables
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #include <iostream> using namespace std; int main() { int a = 5, b = 10; cout << "Before swapping." << endl; cout << "a = " << a << ", b = " << b << endl; a = a + b; b = a - b; a = a - b; cout << "\nAfter swapping." << endl; cout << "a = " << a << ", b = " << b << endl; return 0; } |
Output:
1 2 3 4 5 6 7 | Before swapping. a = 5, b = 10 After swapping. a = 10, b = 5 |
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 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #include <iostream> using namespace std; int main() { int n; cout << "Enter an integer: "; cin >> n; if ( n % 2 == 0) cout << n << " is even."; else cout << n << " is odd."; return 0; } |
Output:
1 2 3 4 | Enter an integer: 123 123 is odd. |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #include <iostream> using namespace std; int main() { int n; cout << "Enter an integer: "; cin >> n; (n % 2 == 0) ? cout << n << " is even." : cout << n << " is odd."; return 0; } |
Output:
1 2 3 4 | Enter an integer: 246 246 is even. |
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.
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 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #include <iostream> using namespace std; int main() { double n1, n2, n3; cout << "Enter three numbers: "; cin >> n1 >> n2 >> n3; // check if n1 is the largest number if(n1 >= n2 && n1 >= n3) cout << "Largest number: " << n1; // check if n2 is the largest number else if(n2 >= n1 && n2 >= n3) cout << "Largest number: " << n2; // if neither n1 nor n2 are the largest, n3 is the largest else cout << "Largest number: " << n3; return 0; } |
Output:
1 2 3 4 5 6 | Enter three numbers: 50 30 40 Largest number: 50 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | #include <iostream> using namespace std; int main() { double n1, n2, n3; cout << "Enter three numbers: "; cin >> n1 >> n2 >> n3; // check if n1 is greater than n2 if (n1 >= n2) { // if n1 is also greater than n3, // then n1 is the largest number if (n1 >= n3) cout << "Largest number: " << n1; // but if n1 is less than n3 // but n1 is greater than n2 // then n3 is the largest number else cout << "Largest number: " << n3; } // else, n2 is greater than n1 else { // if n2 is also greater than n3, // then n2 is the largest number if (n2 >= n3) cout << "Largest number: " << n2; // but if n2 is less than n3 // but n2 is greater than n1 // then n3 is the largest number else cout << "Largest number: " << n3; } return 0; } |
Output:
1 2 3 4 5 6 | Enter three numbers: 50 30 40 Largest number: 50 |
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 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | #include <iostream> #include <cmath> using namespace std; int main() { float a, b, c, x1, x2, discriminant, realPart, imaginaryPart; cout << "Enter coefficients a, b and c: "; cin >> a >> b >> c; discriminant = b*b - 4*a*c; if (discriminant > 0) { x1 = (-b + sqrt(discriminant)) / (2*a); x2 = (-b - sqrt(discriminant)) / (2*a); cout << "Roots are real and different." << endl; cout << "x1 = " << x1 << endl; cout << "x2 = " << x2 << endl; } else if (discriminant == 0) { cout << "Roots are real and same." << endl; x1 = -b/(2*a); cout << "x1 = x2 =" << x1 << endl; } else { realPart = -b/(2*a); imaginaryPart =sqrt(-discriminant)/(2*a); cout << "Roots are complex and different." << endl; cout << "x1 = " << realPart << "+" << imaginaryPart << "i" << endl; cout << "x2 = " << realPart << "-" << imaginaryPart << "i" << endl; } return 0; } |
Output:
1 2 3 4 5 6 7 8 | Enter coefficients a, b and c: 8 10 2 Roots are real and different. x1 = -0.25 x2 = -1 |
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.
Example 11: Sum of Natural Numbers using loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #include <iostream> using namespace std; int main() { int n, sum = 0; cout << "Enter a positive integer: "; cin >> n; for (int i = 1; i <= n; ++i) { sum += i; } cout << "Sum = " << sum; return 0; } |
Output:
1 2 3 4 | Enter a positive integer: 23 Sum = 276 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | #include <iostream> using namespace std; int main() { int year; cout << "Enter a year: "; cin >> year; // leap year if perfectly divisible by 400 if (year % 400 == 0) { cout << year << " is a leap year."; } // not a leap year if divisible by 100 // but not divisible by 400 else if (year % 100 == 0) { cout << year << " is not a leap year."; } // leap year if not divisible by 100 // but divisible by 4 else if (year % 4 == 0) { cout << year << " is a leap year."; } // all other years are not leap years else { cout << year << " is not a leap year."; } return 0; } |
Output:
1 2 3 4 | Enter a year: 2004 2004 is a leap year. |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | #include <iostream> using namespace std; int main() { int year; cout << "Enter a year: "; cin >> year; if (year % 4 == 0) { if (year % 100 == 0) { if (year % 400 == 0) { cout << year << " is a leap year."; } else { cout << year << " is not a leap year."; } } else { cout << year << " is a leap year."; } } else { cout << year << " is not a leap year."; } return 0; } |
Output:
1 2 3 4 | Enter a year: 2004 2004 is a leap year. |
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.
Example 14: Find the Factorial of a Given Number
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #include <iostream> using namespace std; int main() { int n; long factorial = 1.0; cout << "Enter a positive integer: "; cin >> n; if (n < 0) cout << "Error! Factorial of a negative number doesn't exist."; else { for(int i = 1; i <= n; ++i) { factorial *= i; } cout << "Factorial of " << n << " = " << factorial; } return 0; } |
Output:
1 2 3 4 | Enter a positive integer: 6 Factorial of 6 = 720 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include <iostream> using namespace std; int main() { int n, range; cout << "Enter an integer: "; cin >> n; cout << "Enter range: "; cin >> range; for (int i = 1; i <= range; ++i) { cout << n << " * " << i << " = " << n * i << endl; } return 0; } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | Enter an integer: 7 Enter range: 10 7 * 1 = 7 7 * 2 = 14 7 * 3 = 21 7 * 4 = 28 7 * 5 = 35 7 * 6 = 42 7 * 7 = 49 7 * 8 = 56 7 * 9 = 63 7 * 10 = 70 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | #include <iostream> using namespace std; int main() { int n, t1 = 0, t2 = 1, nextTerm = 0; cout << "Enter the number of terms: "; cin >> n; cout << "Fibonacci Series: "; for (int i = 1; i <= n; ++i) { // Prints the first two terms. if(i == 1) { cout << t1 << ", "; continue; } if(i == 2) { cout << t2 << ", "; continue; } nextTerm = t1 + t2; t1 = t2; t2 = nextTerm; cout << nextTerm << ", "; } return 0; } |
Output:
1 2 3 4 | Enter the number of terms: 20 Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, |
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 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #include <iostream> using namespace std; int main() { int t1 = 0, t2 = 1, nextTerm = 0, n; cout << "Enter a positive number: "; cin >> n; // displays the first two terms which is always 0 and 1 cout << "Fibonacci Series: " << t1 << ", " << t2 << ", "; nextTerm = t1 + t2; while(nextTerm <= n) { cout << nextTerm << ", "; t1 = t2; t2 = nextTerm; nextTerm = t1 + t2; } return 0; } |
Output:
1 2 3 4 | Enter a positive number: 50 Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, |
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.
Example 18: Find HCF/GCD using for loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | #include <iostream> using namespace std; int main() { int n1, n2, hcf; cout << "Enter two numbers: "; cin >> n1 >> n2; // swapping variables n1 and n2 if n2 is greater than n1. if ( n2 > n1) { int temp = n2; n2 = n1; n1 = temp; } for (int i = 1; i <= n2; ++i) { if (n1 % i == 0 && n2 % i ==0) { hcf = i; } } cout << "HCF = " << hcf; return 0; } |
Output:
1 2 3 4 5 | Enter two numbers: 12 16 HCF = 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 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 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #include <iostream> using namespace std; int main() { int n1, n2; cout << "Enter two numbers: "; cin >> n1 >> n2; while(n1 != n2) { if(n1 > n2) n1 -= n2; else n2 -= n1; } cout << "HCF = " << n1; return 0; } |
Output:
1 2 3 4 5 | Enter two numbers: 12 16 HCF = 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 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 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #include <iostream> using namespace std; int main() { int n1, n2, max; cout << "Enter two numbers: "; cin >> n1 >> n2; // maximum value between n1 and n2 is stored in max max = (n1 > n2) ? n1 : n2; do { if (max % n1 == 0 && max % n2 == 0) { cout << "LCM = " << max; break; } else ++max; } while (true); return 0; } |
Output:
1 2 3 4 5 | Enter two numbers: 12 16 LCM = 48 |
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.
Example 21: C++ Program to Reverse an Integer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #include <iostream> using namespace std; int main() { int n, reversed_number = 0, remainder; cout << "Enter an integer: "; cin >> n; while(n != 0) { remainder = n % 10; reversed_number = reversed_number * 10 + remainder; n /= 10; } cout << "Reversed Number = " << reversed_number; return 0; } |
Output:
1 2 3 4 | Enter an integer: 12345 Reversed Number = 54321 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #include <iostream> using namespace std; int main() { int exponent; float base, result = 1; cout << "Enter base and exponent respectively: "; cin >> base >> exponent; cout << base << "^" << exponent << " = "; while (exponent != 0) { result *= base; --exponent; } cout << result; return 0; } |
Output:
1 2 3 4 5 | Enter base and exponent respectively: 5 3 5^3 = 125 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | #include <iostream> using namespace std; class Complex { private: float real; float imag; public: Complex(): real(0), imag(0){ } void input() { cout << "Enter real and imaginary parts respectively: "; cin >> real; cin >> imag; } // Operator overloading Complex operator - (Complex c2) { Complex temp; temp.real = real - c2.real; temp.imag = imag - c2.imag; return temp; } void output() { if(imag < 0) cout << "Output Complex number: "<< real << imag << "i"; else cout << "Output Complex number: " << real << "+" << imag << "i"; } }; int main() { Complex c1, c2, result; cout<<"Enter first complex number:\n"; c1.input(); cout<<"Enter second complex number:\n"; c2.input(); // In case of operator overloading of binary operators in C++ programming, // the object on right hand side of operator is always assumed as argument by compiler. result = c1 - c2; result.output(); return 0; } |
Output:
1 2 3 4 5 6 7 | Enter first complex number: Enter real and imaginary parts respectively: 10 25 Enter second complex number: Enter real and imaginary parts respectively: 25 15 Output Complex number: -15+10i |
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 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | #include <iostream> using namespace std; int main() { int n, num, digit, rev = 0; cout << "Enter a positive number: "; cin >> num; n = num; do { digit = num % 10; rev = (rev * 10) + digit; num = num / 10; } while (num != 0); cout << " The reverse of the number is: " << rev << endl; if (n == rev) cout << " The number is a palindrome."; else cout << " The number is not a palindrome."; return 0; } |
Output:
1 2 3 4 5 | Enter a positive number: 123321 The reverse of the number is: 123321 The number is a palindrome. |
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 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | #include <iostream> using namespace std; int main() { int i, n; bool is_prime = true; cout << "Enter a positive integer: "; cin >> n; // 0 and 1 are not prime numbers if (n == 0 || n == 1) { is_prime = false; } // loop to check if n is prime for (i = 2; i <= n/2; ++i) { if (n % i == 0) { is_prime = false; break; } } if (is_prime) cout << n << " is a prime number"; else cout << n << " is not a prime number"; return 0; } |
Output:
1 2 3 4 | Enter a positive integer: 53 53 is a prime number |
#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 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include <iostream> using namespace std; int main() { int n, i; cout << "Enter a positive integer: "; cin >> n; cout << "Factors of " << n << " are: "; for(i = 1; i <= n; ++i) { if(n % i == 0) cout << i << " "; } return 0; } |
Output:
1 2 3 4 | Enter a positive integer: 12 Factors of 12 are: 1 2 3 4 6 12 |
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 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include <iostream> using namespace std; int main() { int rows; cout << "Enter number of rows: "; cin >> rows; for(int i = 1; i <= rows; ++i) { for(int j = 1; j <= i; ++j) { cout << "* "; } cout << "\n"; } return 0; } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 | Enter number of rows: 10 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * |
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 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include <iostream> using namespace std; int main() { int rows; cout << "Enter number of rows: "; cin >> rows; for(int i = rows; i >= 1; --i) { for(int j = 1; j <= i; ++j) { cout << "* "; } cout << endl; } return 0; } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 | Enter number of rows: 10 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * |
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 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | #include <iostream> using namespace std; int main() { int space, rows; cout <<"Enter number of rows: "; cin >> rows; for(int i = 1, k = 0; i <= rows; ++i, k = 0) { for(space = 1; space <= rows-i; ++space) { cout <<" "; } while(k != 2*i-1) { cout << "* "; ++k; } cout << endl; } return 0; } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 | Enter number of rows: 10 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * |
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 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | #include <iostream> using namespace std; int main() { int rows; cout << "Enter number of rows: "; cin >> rows; for(int i = rows; i >= 1; --i) { for(int space = 0; space < rows-i; ++space) cout << " "; for(int j = i; j <= 2*i-1; ++j) cout << "* "; for(int j = 0; j < i-1; ++j) cout << "* "; cout << endl; } return 0; } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 | Enter number of rows: 10 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * |
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 valuerows
. - Condition: checks whether
i
is greater than or equal to1
. - Decrement: decreases the value of
i
by1
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 value0
. - Condition: checks whether
space
is less thanrows-i
. - Increment: increases the value of
space
by1
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 valuei
. - Condition: checks whether
j
is less than or equal to2*i-1
. - Increment: increases the value of
j
by1
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 value0
. - Condition: checks whether
j
is less thani-1
. - Increment: increases the value of
j
by1
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 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | # include <iostream> using namespace std; int main() { char op; float num1, num2; cout << "Enter operator: +, -, *, /: "; cin >> op; cout << "Enter two operands: "; cin >> num1 >> num2; switch(op) { case '+': cout << num1 << " + " << num2 << " = " << num1 + num2; break; case '-': cout << num1 << " - " << num2 << " = " << num1 - num2; break; case '*': cout << num1 << " * " << num2 << " = " << num1 * num2; break; case '/': cout << num1 << " / " << num2 << " = " << num1 / num2; break; default: // If the operator is other than +, -, * or /, error message is shown cout << "Error! operator is not correct"; break; } return 0; } |
Output:
1 2 3 4 5 | Enter operator: +, -, *, /: * Enter two operands: 10 20 10 * 20 = 200 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | #include <iostream> using namespace std; int check_prime(int); int main() { int n1, n2; bool flag; cout << "Enter two positive integers: "; cin >> n1 >> n2; // swapping n1 and n2 if n1 is greater than n2 if (n1 > n2) { n2 = n1 + n2; n1 = n2 - n1; n2 = n2 - n1; } cout << "Prime numbers between " << n1 << " and " << n2 << " are:\n"; for(int i = n1+1; i < n2; ++i) { // if i is a prime number, flag will be equal to 1 flag = check_prime(i); if(flag) cout << i << ", "; } return 0; } // user-defined function to check prime number int check_prime(int n) { bool is_prime = true; // 0 and 1 are not prime numbers if (n == 0 || n == 1) { is_prime = false; } for(int j = 2; j <= n/2; ++j) { if (n%j == 0) { is_prime = false; break; } } return is_prime; } |
Output:
1 2 3 4 5 | Enter two positive integers: 10 20 Prime numbers between 10 and 20 are: 11, 13, 17, 19, |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | #include <iostream> using namespace std; int main() { int n, i; float num[100], sum=0.0, average; cout << "Enter the numbers of data: "; cin >> n; while (n > 100 || n <= 0) { cout << "Error! number should in range of (1 to 100)." << endl; cout << "Enter the number again: "; cin >> n; } for(i = 0; i < n; ++i) { cout << i + 1 << ". Enter number: "; cin >> num[i]; sum += num[i]; } average = sum / n; cout << "Average = " << average; return 0; } |
Output:
1 2 3 4 5 6 7 8 9 | Enter the numbers of data: 5 1. Enter number: 20 2. Enter number: 25 3. Enter number: 13 4. Enter number: 14 5. Enter number: 10 Average = 16.4 |
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 i
th element of the num
array.
sum += num[i];
– This line adds the i
th 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | #include <iostream> #include <cmath> using namespace std; float calculateSD(float data[]); int main() { int i; float data[10]; cout << "Enter 10 elements: "; for(i = 0; i < 10; ++i) { cin >> data[i]; } cout << endl << "Standard Deviation = " << calculateSD(data); return 0; } float calculateSD(float data[]) { float sum = 0.0, mean, standardDeviation = 0.0; int i; for(i = 0; i < 10; ++i) { sum += data[i]; } mean = sum / 10; for(i = 0; i < 10; ++i) { standardDeviation += pow(data[i] - mean, 2); } return sqrt(standardDeviation / 10); } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | Enter 10 elements: 10 30 25 45 74 52 10 30 50 60 Standard Deviation = 20.0759 |
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 i
th 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 i
th 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 i
th 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 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | #include <iostream> using namespace std; int main() { int r, c, a[100][100], b[100][100], sum[100][100], i, j; cout << "Enter number of rows (between 1 and 100): "; cin >> r; cout << "Enter number of columns (between 1 and 100): "; cin >> c; cout << endl << "Enter elements of 1st matrix: " << endl; // Storing elements of first matrix entered by user. for(i = 0; i < r; ++i) for(j = 0; j < c; ++j) { cout << "Enter element a" << i + 1 << j + 1 << " : "; cin >> a[i][j]; } // Storing elements of second matrix entered by user. cout << endl << "Enter elements of 2nd matrix: " << endl; for(i = 0; i < r; ++i) for(j = 0; j < c; ++j) { cout << "Enter element b" << i + 1 << j + 1 << " : "; cin >> b[i][j]; } // Adding Two matrices for(i = 0; i < r; ++i) for(j = 0; j < c; ++j) sum[i][j] = a[i][j] + b[i][j]; // Displaying the resultant sum matrix. cout << endl << "Sum of two matrix is: " << endl; for(i = 0; i < r; ++i) for(j = 0; j < c; ++j) { cout << sum[i][j] << " "; if(j == c - 1) cout << endl; } return 0; } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | Enter number of rows (between 1 and 100): 3 Enter number of columns (between 1 and 100): 3 Enter elements of 1st matrix: Enter element a11 : 10 Enter element a12 : 20 Enter element a13 : 30 Enter element a21 : 45 Enter element a22 : 20 Enter element a23 : 12 Enter element a31 : 30 Enter element a32 : 52 Enter element a33 : 30 Enter elements of 2nd matrix: Enter element b11 : 20 Enter element b12 : 30 Enter element b13 : 52 Enter element b21 : 56 Enter element b22 : 10 Enter element b23 : 30 Enter element b31 : 50 Enter element b32 : 10 Enter element b33 : 30 Sum of two matrix is: 30 50 82 101 30 42 80 62 60 |
Example 36: Pointers And Pointer Operations In C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | #include <iostream> using namespace std; int main() { int var = 20; // actual variable declaration int *ip; // pointer variable declaration ip = &var; // store address of var in pointer variable cout << "Value of var variable: "; cout << var << endl; // address stored in pointer variable cout << "Address stored in ip variable: "; cout << ip << endl; // access the value at the address available in pointer cout << "Value of *ip variable: "; cout << *ip << endl; return 0; } |
Output:
1 2 3 4 5 | Value of var variable: 20 Address stored in ip variable: 0x7ffc2b032cec Value of *ip variable: 20 |
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 3 4 5 6 7 8 9 10 11 12 13 14 15 | #include <iostream> int main() { int arr[5] = {1, 2, 3, 4, 5}; int *ptr = arr; std::cout << "Array elements using pointer: " << std::endl; for (int i = 0; i < 5; i++) { std::cout << *ptr << std::endl; ptr++; } return 0; } |
Output:
1 2 3 4 5 6 7 8 | Array elements using pointer: 1 2 3 4 5 |
#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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #include <iostream> int main() { int num; int *ptr = # std::cout << "Enter a number: "; std::cin >> num; std::cout << "Value entered: " << *ptr << std::endl; return 0; } |
Output:
1 2 3 4 | Enter a number: 123 Value entered: 123 |
#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 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include <iostream> #include <algorithm> #include <vector> int main() { std::vector<int> numbers = {1, 2, 3, 4, 5}; int total = 0; std::for_each(numbers.begin(), numbers.end(), [&total](int x) { total += x; } ); std::cout << "Total: " << total << std::endl; return 0; } |
Output:
1 2 3 | Total: 15 |
#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 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #include <iostream> #include <vector> int main() { std::vector<int> numbers = {1, 2, 3, 4, 5}; int total = 0; for (int i = 0; i < numbers.size(); i++) { auto add_number = [&total, &numbers, i](int x) { if (x >= numbers[i]) { total += x; } }; add_number(10); add_number(5); } std::cout << "Total: " << total << std::endl; return 0; } |
#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 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | #include <iostream> #include <vector> int main() { std::vector<int> numbers; int input = 0; int total = 0; auto add_number = [&total](int x) { total += x; }; std::cout << "Enter numbers (enter -1 to stop):" << std::endl; while (input != -1) { std::cin >> input; if (input != -1) { numbers.push_back(input); } } for (const auto &x : numbers) { add_number(x); } std::cout << "Total: " << total << std::endl; return 0; } |
#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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include <iostream> #include <chrono> #include <ctime> int main() { // Define two dates as time points std::chrono::system_clock::time_point date1 = std::chrono::system_clock::now(); std::chrono::system_clock::time_point date2 = std::chrono::system_clock::from_time_t(std::time(nullptr)); // Calculate the difference between the two time points in seconds auto duration = date1 - date2; std::cout << "The difference between the two dates is " << std::chrono::duration_cast<std::chrono::seconds>(duration).count() << " seconds." << std::endl; return 0; } |
Output:
1 2 3 | The difference between the two dates is 0 seconds. |
Example 43: C++ Date Time
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #include <iostream> #include <chrono> #include <ctime> int main() { auto now = std::chrono::system_clock::now(); std::time_t now_c = std::chrono::system_clock::to_time_t(now); std::cout << "Current date and time is: " << std::ctime(&now_c) << std::endl; return 0; } |
1 2 3 | Current date and time is: Sat Feb 4 10:39:51 2023 |
Explanation:
#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.auto now = std::chrono::system_clock::now();
– Get the current time using thesystem_clock
from<chrono>
.auto
automatically infers the type ofnow
asstd::chrono::time_point<std::chrono::system_clock>
.std::time_t now_c = std::chrono::system_clock::to_time_t(now);
– Convert thetime_point
to astd::time_t
, which is a type that can be used with the standard C library time functions.std::cout << "Current date and time is: " << std::ctime(&now_c) << std::endl;
– Usestd::ctime
to format thestd::time_t
as a string, and print it to the console usingstd::cout
. Thestd::endl
is a manipulator that adds a newline character.return 0;
– This returns 0 from themain
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #include <iostream> #include <chrono> #include <ctime> int main() { int days = 5; auto now = std::chrono::system_clock::now(); while (days > 0) { now += std::chrono::hours(24); std::time_t now_c = std::chrono::system_clock::to_time_t(now); char buffer[100]; if (std::strftime(buffer, sizeof(buffer), "%A, %B %d, %Y", std::localtime(&now_c))) { std::cout << "Date: " << buffer << std::endl; } else { std::cout << "Failed to format date" << std::endl; } days--; } return 0; } |
1 2 3 4 5 6 7 | Date: Sunday, February 05, 2023 Date: Monday, February 06, 2023 Date: Tuesday, February 07, 2023 Date: Wednesday, February 08, 2023 Date: Thursday, February 09, 2023 |
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++
1 2 3 4 5 6 7 8 9 10 11 12 | #include <iostream> int main() { int *p = new int; // allocate memory for an integer *p = 42; // store the value 42 in the dynamically allocated memory std::cout << *p << std::endl; // output the value of the dynamically allocated memory delete p; // free the dynamically allocated memory return 0; } |
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 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #include <iostream> int main() { int n = 5; int *p = new int[n]; // allocate memory for an array of 5 integers for (int i = 0; i < n; i++) { p[i] = i * 2; // store values in the dynamically allocated memory } for (int i = 0; i < n; i++) { std::cout << p[i] << " "; // output the values of the dynamically allocated memory } std::cout << std::endl; delete[] p; // free the dynamically allocated memory return 0; } |
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 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #include <iostream> class MyClass { public: // Constructor MyClass(int value) : value_(value) {} // Member function void print() const { std::cout << "Value: " << value_ << std::endl; } private: int value_; // Private member variable }; int main() { MyClass object(42); // Create an object of the class object.print(); // Call the member function return 0; } |
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 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | #include <iostream> class Rectangle { private: int length; int width; public: Rectangle(int length, int width) { this->length = length; this->width = width; } int area() { return length * width; } }; int main() { Rectangle rectangle(10, 5); std::cout << "Area: " << rectangle.area() << std::endl; return 0; } |
Explanation:
- We start by including the
iostream
library, which provides thecout
andendl
objects for printing output to the console. - We define a class
Rectangle
with private member variableslength
andwidth
. These member variables are not accessible from outside the class. - The
Rectangle
class has a constructor that takeslength
andwidth
as parameters and sets the private member variables to these values. - The class has a public method
area
that calculates and returns the area of the rectangle. - In the
main
function, we create an instance of theRectangle
class with the length 10 and width 5. - We then use the
area
method to calculate the area of the rectangle and print it to the console. - 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include <iostream> // Define a namespace namespace my_namespace { class MyClass { public: void print() const { std::cout << "Hello from my namespace" << std::endl; } }; } int main() { // Create an object of the class in the namespace my_namespace::MyClass object; object.print(); return 0; } |
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++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | #include <iostream> class Parent { public: void print() { std::cout << "I am the parent." << std::endl; } }; class Child : public Parent { public: void print() { std::cout << "I am the child." << std::endl; } }; int main() { Parent parent; Child child; parent.print(); // Output: "I am the parent." child.print(); // Output: "I am the child." return 0; } |
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++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | #include <iostream> class Person { private: std::string name; int age; public: Person(std::string name, int age) { this->name = name; this->age = age; } void setName(std::string name) { this->name = name; } void setAge(int age) { this->age = age; } std::string getName() { return name; } int getAge() { return age; } }; int main() { Person person("John Doe", 30); std::cout << "Name: " << person.getName() << std::endl; std::cout << "Age: " << person.getAge() << std::endl; return 0; } |
1 2 3 4 | Name: John Doe Age: 30 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | #include <iostream> class Shape { public: virtual double area() const = 0; }; class Rectangle : public Shape { private: double length, width; public: Rectangle(double l, double w) : length(l), width(w) {} double area() const override { return length * width; } }; class Circle : public Shape { private: double radius; public: Circle(double r) : radius(r) {} double area() const override { return 3.14159 * radius * radius; } }; int main() { Shape *shape1 = new Rectangle(10, 5); Shape *shape2 = new Circle(2); std::cout << "Area of rectangle: " << shape1->area() << std::endl; std::cout << "Area of circle: " << shape2->area() << std::endl; return 0; } |
1 2 3 4 | Area of rectangle: 50 Area of circle: 12.5664 |
#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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #include <iostream> class Complex { public: double real, imag; public: Complex(double r, double i) : real(r), imag(i) {} friend Complex operator+(const Complex &c1, const Complex &c2); }; Complex operator+(const Complex &c1, const Complex &c2) { return Complex(c1.real + c2.real, c1.imag + c2.imag); } int main() { Complex c1(1, 2), c2(3, 4); Complex c3 = c1 + c2; std::cout << "c3 = " << c3.real << " + " << c3.imag << "i" << std::endl; return 0; } |
1 2 3 | c3 = 4 + 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 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include <iostream> #include <thread> void printMessage(std::string message) { std::cout << "Thread says: " << message << std::endl; } int main() { std::string message = "Hello from the new thread!"; std::thread t(printMessage, message); std::cout << "Main thread says: Hello from the main thread!" << std::endl; t.join(); // Wait for the thread to finish return 0; } |
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++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include <iostream> #include <thread> class HelloWorld { public: void operator()() const { std::cout << "Hello from thread!" << std::endl; } }; int main() { HelloWorld hello; std::thread t(hello); t.join(); return 0; } |
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.