C++ Programming Code Examples
C++ > Mathematics Code Examples
Compute Discrete Fourier Transform Using the Fast Fourier Transform Approach
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/* Compute Discrete Fourier Transform Using the Fast Fourier Transform Approach
This is a C++ Program to perform Fast Fourier Transform. A fast Fourier transform (FFT) is an algorithm to compute the discrete Fourier transform (DFT) and its inverse. Fourier analysis converts time (or space) to frequency and vice versa; an FFT rapidly computes such transformations by factorizing the DFT matrix into a product of sparse (mostly zero) factors. */
#include <iostream>
#include <complex>
#include <cmath>
#include <iterator>
using namespace std;
unsigned int bitReverse(unsigned int x, int log2n)
{
int n = 0;
int mask = 0x1;
for (int i = 0; i < log2n; i++)
{
n <<= 1;
n |= (x & 1);
x >>= 1;
}
return n;
}
const double PI = 3.1415926536;
template<class Iter_T>
void fft(Iter_T a, Iter_T b, int log2n)
{
typedef typename iterator_traits<iter_t>::value_type complex;
const complex J(0, 1);
int n = 1 << log2n;
for (unsigned int i = 0; i < n; ++i)
{
b[bitReverse(i, log2n)] = a[i];
}
for (int s = 1; s <= log2n; ++s)
{
int m = 1 << s;
int m2 = m >> 1;
complex w(1, 0);
complex wm = exp(-J * (PI / m2));
for (int j = 0; j < m2; ++j)
{
for (int k = j; k < n; k += m)
{
complex t = w * b[k + m2];
complex u = b[k];
b[k] = u + t;
b[k + m2] = u - t;
}
w *= wm;
}
}
}
int main(int argc, char **argv)
{
typedef complex cx;
cx a[] = { cx(0, 0), cx(1, 1), cx(3, 3), cx(4, 4), cx(4, 4), cx(3, 3), cx(
1, 1), cx(0, 0) };
cx b[8];
fft(a, b, 3);
for (int i = 0; i < 8; ++i)
cout << b[i] << "\n";
}
Namespaces in C++ Language
Consider a situation, when we have two persons with the same name, jhon, in the same class. Whenever we need to differentiate them definitely we would have to use some additional information along with their name, like either the area, if they live in different area or their mother's or father's name, etc.
Same situation can arise in your C++ applications. For example, you might be writing some code that has a function called xyz() and there is another library available which is also having same function xyz(). Now the compiler has no way of knowing which version of xyz() function you are referring to within your code.
A namespace is designed to overcome this difficulty and is used as additional information to differentiate similar functions, classes, variables etc. with the same name available in different libraries. Using namespace, you can define the context in which names are defined. In essence, a namespace defines a scope.
Defining a Namespace
A namespace definition begins with the keyword namespace followed by the namespace name as follows:
namespace namespace_name {
// code declarations
}
name::code; // code could be variable or function.
Using Directive
You can also avoid prepending of namespaces with the using namespace directive. This directive tells the compiler that the subsequent code is making use of names in the specified namespace.
Discontiguous Namespaces
A namespace can be defined in several parts and so a namespace is made up of the sum of its separately defined parts. The separate parts of a namespace can be spread over multiple files.
So, if one part of the namespace requires a name defined in another file, that name must still be declared. Writing a following namespace definition either defines a new namespace or adds new elements to an existing one:
namespace namespace_name {
// code declarations
}
Nested Namespaces
Namespaces can be nested where you can define one namespace inside another name space as follows:
namespace namespace_name1 {
// code declarations
namespace namespace_name2 {
// code declarations
}
}
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
/* namespaces in C++ language */
// A C++ code to demonstrate that we can define
// methods outside namespace.
#include <iostream>
using namespace std;
// Creating a namespace
namespace ns
{
void display();
class happy
{
public:
void display();
};
}
// Defining methods of namespace
void ns::happy::display()
{
cout << "ns::happy::display()\n";
}
void ns::display()
{
cout << "ns::display()\n";
}
// Driver code
int main()
{
ns::happy obj;
ns::display();
obj.display();
return 0;
}
Assignment Operators in C++
As the name already suggests, these operators help in assigning values to variables. These operators help us in allocating a particular value to the operands. The main simple assignment operator is '='. We have to be sure that both the left and right sides of the operator must have the same data type. We have different levels of operators.
Assignment operators are used to assign the value, variable and function to another variable. Assignment operators in C are some of the C Programming Operator, which are useful to assign the values to the declared variables. Let's discuss the various types of the assignment operators such as =, +=, -=, /=, *= and %=. The following table lists the assignment operators supported by the C language:
=
Simple assignment operator. Assigns values from right side operands to left side operand
+=
Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand.
-=
Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand.
*=
Multiply AND assignment operator. It multiplies the right operand with the left operand and assigns the result to the left operand.
/=
Divide AND assignment operator. It divides the left operand with the right operand and assigns the result to the left operand.
%=
Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand.
<<=
Left shift AND assignment operator.
>>=
Right shift AND assignment operator.
&=
Bitwise AND assignment operator.
^=
Bitwise exclusive OR and assignment operator.
|=
Bitwise inclusive OR and assignment operator.
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
/* Assignment operators are used to assigning value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error. */
// C++ program to demonstrate working of Assignment operators
#include <iostream>
using namespace std;
int main()
{
// Assigning value 10 to a
// using "=" operator
int a = 10;
cout << "Value of a is "<<a<<"\n";
// Assigning value by adding 10 to a
// using "+=" operator
a += 10;
cout << "Value of a is "<<a<<"\n";
// Assigning value by subtracting 10 from a
// using "-=" operator
a -= 10;
cout << "Value of a is "<<a<<"\n";
// Assigning value by multiplying 10 to a
// using "*=" operator
a *= 10;
cout << "Value of a is "<<a<<"\n";
// Assigning value by dividing 10 from a
// using "/=" operator
a /= 10;
cout << "Value of a is "<<a<<"\n";
return 0;
}
time() Function in C++
Get current time. Get the current calendar time as a value of type time_t. The function returns this value, and if the argument is not a null pointer, it also sets this value to the object pointed by timer.
The value returned generally represents the number of seconds since 00:00 hours, Jan 1, 1970 UTC (i.e., the current unix timestamp). Although libraries may use a different representation of time: Portable programs should not use the value returned by this function directly, but always rely on calls to other elements of the standard library to translate them to portable types (such as localtime, gmtime or difftime).
Syntax for time() Function in C++
#include <ctime>
time_t time (time_t* timer);
timer
Pointer to an object of type time_t, where the time value is stored.
Alternatively, this parameter can be a null pointer, in which case the parameter is not used (the function still returns a value of type time_t with the result).
Function returns the current calendar time as a time_t object.
If the argument is not a null pointer, the return value is the same as the one stored in the location pointed by argument timer.
If the function could not retrieve the calendar time, it returns a value of -1.
time_t is an alias of a fundamental arithmetic type capable of representing times.
Data races
The object pointed by timer is modified (if not null).
Exceptions
No-throw guarantee: this function never throws exceptions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/* std::time function returns the current calendar time encoded as a std::time_t object, and also stores it in the object pointed to by arg, unless arg is a null pointer. */
/* Get the current calendar time as a value of type time_t. by time() function code example */
#include <iostream>
#include <ctime>
using namespace std;
int main() {
time_t current_time;
// stores time in current_time
time(¤t_time);
cout << current_time;
cout << " seconds has passed since 00:00:00 GMT, Jan 1, 1970";
return 0;
}
Function Templates in C++
A C++ template is a powerful feature added to C++. It allows you to define the generic classes and generic functions and thus provides support for generic programming. Generic programming is a technique where generic types are used as parameters in algorithms so that they can work for a variety of data types.
We can define a template for a function. For example, if we have an add() function, we can create versions of the add function for adding the int, float or double type values.
Syntax for Function Templates in C++
template < class Ttype> ret_type func_name(parameter_list)
{
// body of function.
}
Ttype
a placeholder name
class
specify a generic type
Where Ttype: It is a placeholder name for a data type used by the function. It is used within the function definition. It is only a placeholder that the compiler will automatically replace this placeholder with the actual data type.
class: A class keyword is used to specify a generic type in a template declaration.
• Generic functions use the concept of a function template. Generic functions define a set of operations that can be applied to the various types of data.
• The type of the data that the function will operate on depends on the type of the data passed as a parameter.
• For example, Quick sorting algorithm is implemented using a generic function, it can be implemented to an array of integers or array of floats.
• A Generic function is created by using the keyword template. The template defines what function will do.
Function templates with multiple parameters:
We can use more than one generic type in the template function by using the comma to separate the list.
template<class T1, class T2,.....>
return_type function_name (arguments of type T1, T2....)
{
// body of 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
/* function templates in C++ language */
/* adding two numbers using function templates */
#include <iostream>
using namespace std;
template <typename T>
T add(T num1, T num2) {
return (num1 + num2);
}
int main() {
int result1;
double result2;
// calling with int parameters
result1 = add<int>(2, 3);
cout << "2 + 3 = " << result1 << endl;
// calling with double parameters
result2 = add<double>(2.2, 3.3);
cout << "2.2 + 3.3 = " << result2 << endl;
return 0;
}
Iterators in C++ Language
Iterators are just like pointers used to access the container elements. Iterators are one of the four pillars of the Standard Template Library or STL in C++. An iterator is used to point to the memory address of the STL container classes. For better understanding, you can relate them with a pointer, to some extent.
Iterators act as a bridge that connects algorithms to STL containers and allows the modifications of the data present inside the container. They allow you to iterate over the container, access and assign the values, and run different operators over them, to get the desired result.
Syntax for Iterators in C++
<ContainerType> :: iterator;
<ContainerType> :: const_iterator;
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
/* Iterators in C++ language */
// C++ code to demonstrate the working of next() and prev()
#include<iostream>
#include<iterator> // for iterators
#include<vector> // for vectors
using namespace std;
int main()
{
vector<int> ar = { 1, 2, 3, 4, 5 };
// Declaring iterators to a vector
vector<int>::iterator ptr = ar.begin();
vector<int>::iterator ftr = ar.end();
// Using next() to return new iterator
// points to 4
auto it = next(ptr, 3);
// Using prev() to return new iterator
// points to 3
auto it1 = prev(ftr, 3);
// Displaying iterator position
cout << "The position of new iterator using next() is : ";
cout << *it << " ";
cout << endl;
// Displaying iterator position
cout << "The position of new iterator using prev() is : ";
cout << *it1 << " ";
cout << endl;
return 0;
}
#include Directive in C++
#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program.
Syntax for #include Directive in C++
#include "user-defined_file"
#include <header_file>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/* using #include directive in C language */
#include <stdio.h>
int main()
{
/*
* C standard library printf function
* defined in the stdio.h header file
*/
printf("I love you Clementine");
printf("I love you so much");
printf("HappyCodings");
return 0;
}
Nested Loop Statement in C++
C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of statements inside another loop. Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number of loops. The nesting level can be defined at n times. You can define any type of loop inside another loop; for example, you can define 'while' loop inside a 'for' loop.
A loop inside another loop is called a nested loop. The depth of nested loop depends on the complexity of a problem. We can have any number of nested loops as required. Consider a nested loop where the outer loop runs n times and consists of another loop inside it. The inner loop runs m times. Then, the total number of times the inner loop runs during the program execution is n*m.
Syntax for Nested Loop Statement in C++
Outer_loop
{
Inner_loop
{
// inner loop statements.
}
// outer loop 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
25
26
27
28
29
30
31
32
33
/* nested loop statement in C++ language */
// C++ program that uses nested for loop to print a 2D matrix
#include <bits/stdc++.h>
using namespace std;
#define ROW 3
#define COL 3
// Driver program
int main()
{
int i, j;
// Declare the matrix
int matrix[ROW][COL] = { { 4, 8, 12 },
{ 16, 20, 24 },
{ 28, 32, 36 } };
cout << "Given matrix is \n";
// Print the matrix using nested loops
for (i = 0; i < ROW; i++) {
for (j = 0; j < COL; j++)
cout << matrix[i][j];
cout << "\n";
}
return 0;
}
Arithmetic Operators in C++
Arithmetic Operator is used to performing mathematical operations such as addition, subtraction, multiplication, division, modulus, etc., on the given operands. For example: 6 + 3 = 9, 5 - 3 = 2, 3 * 4 = 12, etc. are the examples of arithmetic operators. Let's discuss the different types of Arithmetic Operators in the C programming.
+
Plus Operator is a simple Plus (+) Operator used to add two given operands. We can use Plus Operator with different data types such as integer, float, long, double, enumerated and string type data to add the given operand.
-
The minus operator is denoted by the minus (-) symbol. It is used to return the subtraction of the first number from the second number. The data type of the given number can be different types, such as int, float, double, long double, etc., in the programing language.
*
The multiplication operator is represented as an asterisk (*) symbol, and it is used to return the product of n1 and n2 numbers. The data type of the given number can be different types such as int, float, and double in the C programing language.
/
The division operator is an arithmetic operator that divides the first (n1) by the second (n2) number. Using division operator (/), we can divide the int, float, double and long data types variables.
%
The modulus operator is represented by the percentage sign (%), and it is used to return the remainder by dividing the first number by the second number.
++
Increment Operator is the type of Arithmetic operator, which is denoted by double plus (++) operator. It is used to increase the integer value by 1.
--
Decrement Operator is denoted by the double minus (--) symbol, which decreases the operand value by 1.
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
/* Perhaps you have warm memories of doing arithmetic drills in grade school. You can give that same pleasure to your computer. C++ uses operators to do arithmetic. It provides operators for five basic arithmetic calculations: addition, subtraction, multiplication, division, and taking the modulus. Each of these operators uses two values (called operands) to calculate a final answer. Together, the operator and its operands constitute an expression. */
#include <iostream>
using namespace std;
int main() {
int a, b;
a = 7;
b = 2;
// printing the sum of a and b
cout << "a + b = " << (a + b) << endl;
// printing the difference of a and b
cout << "a - b = " << (a - b) << endl;
// printing the product of a and b
cout << "a * b = " << (a * b) << endl;
// printing the division of a by b
cout << "a / b = " << (a / b) << endl;
// printing the modulo of a by b
cout << "a % b = " << (a % b) << endl;
return 0;
}
For Loop Statement in C++
In computer programming, loops are used to repeat a block of code. For example, when you are displaying number from 1 to 100 you may want set the value of a variable to 1 and display it 100 times, increasing its value by 1 on each loop iteration. When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop. A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
Syntax of For Loop Statement in C++
for (initialization; condition; update) {
// body of-loop
}
initialization
initializes variables and is executed only once.
condition
if true, the body of for loop is executed, if false, the for loop is terminated.
update
updates the value of initialized variables and again checks the condition.
A new range-based for loop was introduced to work with collections such as arrays and vectors.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/* For Loop Statement in C++ Language */
// C++ program to find the sum of first n natural numbers
// positive integers such as 1,2,3,...n are known as natural numbers
#include <iostream>
using namespace std;
int main() {
int num, sum;
sum = 0;
cout << "Enter a positive integer: ";
cin >> num;
for (int i = 1; i <= num; ++i) {
sum += i;
}
cout << "Sum = " << sum << endl;
return 0;
}
main() Function in C++
A program shall contain a global function named main, which is the designated start of the program in hosted environment. main() function is the entry point of any C++ program. It is the point at which execution of program is started. When a C++ program is executed, the execution control goes directly to the main() function. Every C++ program have a main() function.
Syntax for main() Function in C++
void main()
{
............
............
}
void
void is a keyword in C++ language, void means nothing, whenever we use void as a function return type then that function nothing return. here main() function no return any value.
main
main is a name of function which is predefined function in C++ library.
In place of void we can also use int return type of main() function, at that time main() return integer type value.
1) It cannot be used anywhere in the program
a) in particular, it cannot be called recursively
b) its address cannot be taken
2) It cannot be predefined and cannot be overloaded: effectively, the name main in the global namespace is reserved for functions (although it can be used to name classes, namespaces, enumerations, and any entity in a non-global namespace, except that a function called "main" cannot be declared with C language linkage in any namespace).
3) It cannot be defined as deleted or (since C++11) declared with C language linkage, constexpr (since C++11), consteval (since C++20), inline, or static.
4) The body of the main function does not need to contain the return statement: if control reaches the end of main without encountering a return statement, the effect is that of executing return 0;.
5) Execution of the return (or the implicit return upon reaching the end of main) is equivalent to first leaving the function normally (which destroys the objects with automatic storage duration) and then calling std::exit with the same argument as the argument of the return. (std::exit then destroys static objects and terminates the program).
6) (since C++14) The return type of the main function cannot be deduced (auto main() {... is not allowed).
7) (since C++20) The main function cannot be a coroutine.
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
/* simple code example by main() function in C++ */
#include <iostream>
using namespace std;
int main() {
int day = 4;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
}
return 0;
}
Math Library exp() Function in C++
Compute exponential function. Returns the base-e exponential function of x, which is e raised to the power x: ex.
This function is defined in <cmath> header file. Additional overloads are provided in this header (<cmath>) for the integral types: These overloads effectively cast x to a double before calculations.
This function is also overloaded in <complex> and <valarray> (see complex exp and valarray exp).
Syntax for Math exp() Function in C++
#include <cmath>
double exp (double x);
float exp (float x);
long double exp (long double x);
double exp (T x); // additional overloads for integral types
x
Value of the exponent.
The function can take any value i.e, positive, negative or zero in its parameter and returns result in int, double or float or long double.
Function returns exponential value of x.
If the magnitude of the result is too large to be represented by a value of the return type, the function returns HUGE_VAL (or HUGE_VALF or HUGE_VALL) with the proper sign, and an overflow range error occurs:
If an overflow range error occurs:
- And math_errhandling has MATH_ERRNO set: the global variable errno is set to ERANGE.
- And math_errhandling has MATH_ERREXCEPT set: FE_OVERFLOW is raised.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/* The exp() function in C++ returns the exponential (Euler's number) e raised to the given argument. */
/* compute the exponential e raised to the power given number by exp() function code example. */
#include <iostream>
#include <cmath>
using namespace std;
int main () {
double x = 0;
cout << "The exponential value of " << x << " is " << exp(x) << endl;
cout << "The exponential value of " << x+1 << " is " << exp(x+1) <<
endl;
cout << "The exponential value of " << x+2 << " is " << exp(x+2) <<
endl;
return(0);
}
transform() Function in C++
Transform range. Applies an operation sequentially to the elements of one (1) or two (2) ranges and stores the result in the range that begins at result. The transform() function in C++ sequentially applies an operation to the elements of an array(s) and then stores the result in another output array.
The transform function is used in two forms:
Unary operation: The operation is applied to each element in the input range, and the result is stored in the output array. The transform() function takes the pointer to the starting and ending position of a single input array and to the starting position of the output array.
Binary Operation: A binary operation is called on each element of the first input range and the respective element of the second input range. The output is stored in the output array.
When applying a binary function, the transform() function takes the pointer to the starting and ending position of the first input array and to the starting position of the second input array. The function also takes the pointer to the start of our output array and to the binary function that we want to apply to our two input arrays.
Syntax for transform() Function in C++
// unary operation(1)
template <class InputIterator, class OutputIterator, class UnaryOperation>
OutputIterator transform (InputIterator first1, InputIterator last1,
OutputIterator result, UnaryOperation op);
// binary operation(2)
template <class InputIterator1, class InputIterator2,
class OutputIterator, class BinaryOperation>
OutputIterator transform (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, OutputIterator result,
BinaryOperation binary_op);
first1
An input iterator pointing the position of the first element of the first range to be operated on.
last1
An iterator pointing the position one past the final element of the first range to be operated on.
Input iterators to the initial and final positions of the first sequence. The range used is [first1,last1), which contains all the elements between first1 and last1, including the element pointed to by first1 but not the element pointed to by last1.
first2
Input iterator pointing to the first element in the second range to be operated on.
result
An output iterator to the initial position of the range where the operation results are stored.
op
Unary function applied to each element of the range.
binary_op
Binary function that two elements passed as its arguments.
Neither op nor binary_op should directly modify the elements passed as its arguments: These are indirectly modified by the algorithm (using the return value) if the same range is specified for result.
(1) unary operation: Applies op to each of the elements in the range [first1,last1) and stores the value returned by each operation in the range that begins at result.
(2) binary operation: Calls binary_op using each of the elements in the range [first1,last1) as first argument, and the respective argument in the range that begins at first2 as second argument. The value returned by each call is stored in the range that begins at result.
transform() returns an iterator pointing to the end of the transformed range.
Complexity
Linear in the distance between first1 and last1: Performs one assignment and one application of op (or binary_op) per element.
Data races
The objects in the range [first1,last1) (and eventually those in the range beginning at first2) are accessed (each object is accessed exactly once). The objects in the range beginning at result are modified.
Exceptions
Throws if any of the function calls, the assignments or the operations on iterators throws. Note that invalid arguments cause undefined behavior.
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
/* if we want to perform square of each element of an array, and store it into other, then we can use the transform() function */
// C++ program to demonstrate working of
// transform with unary operator.
#include <bits/stdc++.h>
using namespace std;
int increment(int x) { return (x+1); }
int main()
{
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr)/sizeof(arr[0]);
// Apply increment to all elements of
// arr[] and store the modified elements
// back in arr[]
transform(arr, arr+n, arr, increment);
for (int i=0; i<n; i++)
cout << arr[i] << " ";
return 0;
}
Complex Number Constructor in C++
Complex number constructor. Constructs a complex object. It may be constructed from two values (re and im) or from another complex.
We can create complex number class in C++, that can hold the real and imaginary part of the complex number as member elements. There will be some member functions that are used to handle this class.
Syntax for Complex Number Constructor in C++
#include <complex>
//initialization (1)
complex (const T& re = T(), const T& im = T());
//copy (2)
complex (const complex& x);
//conversion (3)
template<class U>
complex (const complex<U>& x);
re, im
Real and imaginary parts, respectively, of the complex number. T is complex's template parameter.
x
A complex object. If constructed from a complex object with a different template parameter (U), the appropriate conversions are performed.
Exception safety
Narrowing conversions on floating-point types may produce undefined behavior (when the value is too small or too great to be represented by the type). Otherwise, constructing a complex never throws exceptions.
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
/* The complex library implements the complex class to contain complex numbers in cartesian form and several functions and overloads to operate with them. */
#include <iostream>
#include <iomanip>
#include <complex>
#include <cmath>
int main()
{
using namespace std::complex_literals;
std::cout << std::fixed << std::setprecision(1);
std::complex<double> z1 = 1i * 1i; // imaginary unit squared
std::cout << "i * i = " << z1 << '\n';
std::complex<double> z2 = std::pow(1i, 2); // imaginary unit squared
std::cout << "pow(i, 2) = " << z2 << '\n';
const double PI = std::acos(-1); // or std::numbers::pi in C++20
std::complex<double> z3 = std::exp(1i * PI); // Euler's formula
std::cout << "exp(i * pi) = " << z3 << '\n';
std::complex<double> z4 = 1. + 2i, z5 = 1. - 2i; // conjugates
std::cout << "(1+2i)*(1-2i) = " << z4*z5 << '\n';
}
Class Templates in C++
Templates are powerful features of C++ which allows us to write generic programs. Similar to function templates, we can use class templates to create a single class to work with different data types. Class templates come in handy as they can make our code shorter and more manageable. A class template starts with the keyword template followed by template parameter(s) inside <> which is followed by the class declaration.
Declaration for Class Template in C++
template <class T>
class className {
private:
T var;
... .. ...
public:
T functionName(T arg);
... .. ...
};
T
template argument
var
a member variable
T is the template argument which is a placeholder for the data type used, and class is a keyword.
Inside the class body, a member variable var and a member function functionName() are both of type T.
Creating a class template object:
Once we've declared and defined a class template, we can create its objects in other classes or functions (such as the main() function) with the following syntax:
className<dataType> classObject;
template <class T>
class ClassName {
... .. ...
// Function prototype
returnType functionName();
};
// Function definition
template <class T>
returnType ClassName<T>::functionName() {
// code
}
template <class T, class U, class V = int>
class ClassName {
private:
T member1;
U member2;
V member3;
... .. ...
public:
... .. ...
};
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
/* Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type. A template is a blueprint or formula for creating a generic class or a function. */
#include <iostream>
using namespace std;
template <typename T>
class Array {
private:
T *ptr;
int size;
public:
Array(T arr[], int s);
void print();
};
template <typename T>
Array<T>::Array(T arr[], int s) {
ptr = new T[s];
size = s;
for(int i = 0; i < size; i++)
ptr[i] = arr[i];
}
template <typename T>
void Array<T>::print() {
for (int i = 0; i < size; i++)
cout<<" "<<*(ptr + i);
cout<<endl;
}
int main() {
int arr[5] = {1, 2, 3, 4, 5};
Array<int> a(arr, 5);
a.print();
return 0;
}
Bitwise Operators in C++
The bitwise operators are the operators used to perform the operations on the data at the bit-level. When we perform the bitwise operations, then it is also known as bit-level programming. It consists of two digits, either 0 or 1. It is mainly used in numerical computations to make the calculations faster. We have different types of bitwise operators in the C++ programming language. The following is the list of the bitwise operators:
&
Bitwise AND operator is denoted by the single ampersand sign (&). Two integer operands are written on both sides of the (&) operator. If the corresponding bits of both the operands are 1, then the output of the bitwise AND operation is 1; otherwise, the output would be 0.
This is one of the most commonly used logical bitwise operators. It is represented by a single ampersand sign (&). Two integer expressions are written on each side of the (&) operator.
The result of the bitwise AND operation is 1 if both the bits have the value as 1; otherwise, the result is always 0.
The bitwise AND operator is a single ampersand: &. A handy mnemonic is that the small version of the boolean AND, &&, works on smaller pieces (bits instead of bytes, chars, integers, etc). In essence, a binary AND simply takes the logical AND of the bits in each position of a number in binary form.
01001000 & 10111000 = 00001000
The most significant bit of the first number is 0, so we know the most significant bit of the result must be 0; in the second most significant bit, the bit of second number is zero, so we have the same result. The only time where both bits are 1, which is the only time the result will be 1, is the fifth bit from the left.
|
Bitwise OR operator is represented by a single vertical sign (|). Two integer operands are written on both sides of the (|) symbol. If the bit value of any of the operand is 1, then the output would be 1, otherwise 0.
It is represented by a single vertical bar sign (|). Two integer expressions are written on each side of the (|) operator.
The result of the bitwise OR operation is 1 if at least one of the expression has the value as 1; otherwise, the result is always 0.
Bitwise OR works almost exactly the same way as bitwise AND. The only difference is that only one of the two bits needs to be a 1 for that position's bit in the result to be 1. (If both bits are a 1, the result will also have a 1 in that position.) The symbol is a pipe: |. Again, this is similar to boolean logical operator, which is ||.
01001000 | 10111000 = 11111000
^
Bitwise exclusive OR operator is denoted by (^) symbol. Two operands are written on both sides of the exclusive OR operator. If the corresponding bit of any of the operand is 1 then the output would be 1, otherwise 0.
The bitwise XOR ^ operator returns 1 if and only if one of the operands is 1. However, if both the operands are 0, or if both are 1, then the result is 0.
The following truth table demonstrates the working of the bitwise XOR operator. Let a and b be two operands that can only take binary values i.e. 1 or 0.
There is no boolean operator counterpart to bitwise exclusive-or, but there is a simple explanation. The exclusive-or operation takes two inputs and returns a 1 if either one or the other of the inputs is a 1, but not if both are. That is, if both inputs are 1 or both inputs are 0, it returns 0. Bitwise exclusive-or, with the operator of a caret, ^, performs the exclusive-or operation on each pair of bits. Exclusive-or is commonly abbreviated XOR.
01110010 ^ 10101010 = 11011000
~
Bitwise complement operator is also known as one's complement operator (unary operator). It is represented by the symbol tilde (~). It takes only one operand or variable and performs complement operation on an operand. When we apply the complement operation on any bits, then 0 becomes 1 and 1 becomes 0.
The bitwise complement operator, the tilde, ~, flips every bit. A useful way to remember this is that the tilde is sometimes called a twiddle, and the bitwise complement twiddles every bit: if you have a 1, it's a 0, and if you have a 0, it's a 1.
The bitwise complement is also called as one's complement operator since it always takes only one value or an operand. It is a unary operator.
When we perform complement on any bits, all the 1's become 0's and vice versa.
If we have an integer expression that contains 0000 1111 then after performing bitwise complement operation the value will become 1111 0000.
Bitwise complement operator is denoted by symbol tilde (~).
The bitwise shift operators are used to move/shift the bit patterns either to the left or right side. Left and right are two shift operators provided by 'C' which are represented as follows:
Operand << n (Left Shift),
Operand >> n (Right Shift)
an operand is an integer expression on which we have to perform the shift operation.
'n' is the total number of bit positions that we have to shift in the integer expression.
<<
Left-shift operator - It is an operator that shifts the number of bits to the left-side. Left shift operator shifts all bits towards left by a certain number of specified bits. The bit positions that have been vacated by the left shift operator are filled with 0. The symbol of the left shift operator is <<.
The left shift operation will shift the 'n' number of bits to the left side. The leftmost bits in the expression will be popped out, and n bits with the value 0 will be filled on the right side.
>>
Right-shift operator - It is an operator that shifts the number of bits to the right side. Right shift operator shifts all bits towards right by certain number of specified bits. It is denoted by >>.
The right shift operation will shift the 'n' number of bits to the right side. The rightmost 'n' bits in the expression will be popped out, and the value 0 will be filled on the left side.
X Y X&Y X|Y X^Y
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 1
Shifts operators can be combined then it can be used to extract the data from the integer expression.
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
/* bitwise operators in C++ language*/
#include <iostream>
using namespace std;
int main() {
// a = 5(00000101), b = 9(00001001)
int a = 5, b = 9;
// The result is 00000001
cout<<"a = " << a <<","<< " b = " << b <<endl;
cout << "a & b = " << (a & b) << endl;
// The result is 00001101
cout << "a | b = " << (a | b) << endl;
// The result is 00001100
cout << "a ^ b = " << (a ^ b) << endl;
// The result is 11111010
cout << "~(" << a << ") = " << (~a) << endl;
// The result is 00010010
cout<<"b << 1" <<" = "<< (b << 1) <<endl;
// The result is 00000100
cout<<"b >> 1 "<<"= " << (b >> 1 )<<endl;
return 0;
}
'Constructor' is automatically called when an object("the Instance of the Lass") create. It is special member function of the class. Object member variable values assigned to another
This is a sample program to illustrate the Bin-Packing algorithm using next fit heuristics. In the bin packing problem, objects of different volumes must be packed into a finite number
Ask to enter two time periods and these two periods are stored in structure variables t1 t2 respectively. The computeTimeDifference() Function calculates the Difference Between