# C++ Programming Code Examples

## C++ > Beginners Lab Assignments Code Examples

### C++ Program to Solve Palindrome Partitioning Problem

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
/* C++ Program to Solve Palindrome Partitioning Problem */ #include <iostream> #include <cstdio> #include <cstring> #include <climits> #include <cstring> #include <cstdlib> using namespace std; // get minimum of two integers int min (int a, int b) { return (a < b)? a : b; } /* Returns the minimum number of cuts needed to partition a string such that every part is a palindrome */ int minPalPartion(char *str) { int n = strlen(str); int C[n][n]; bool P[n][n]; int i, j, k, L; for (i = 0; i < n; i++) { P[i][i] = true; C[i][i] = 0; } for (L = 2; L <= n; L++) { for (i = 0; i < n - L + 1; i++) { j = i + L - 1; if (L == 2) P[i][j] = (str[i] == str[j]); else P[i][j] = (str[i] == str[j]) && P[i + 1][j - 1]; if (P[i][j] == true) C[i][j] = 0; else { C[i][j] = INT_MAX; for (k = i; k <= j - 1; k++) C[i][j] = min (C[i][j], C[i][k] + C[k + 1][j] + 1); } } } return C[0][n-1]; } // Main int main() { char str[] = "ababbbabbababa"; cout<<"Min cuts needed for Palindrome Partitioning is: "<<minPalPartion(str); cout<<endl; return 0; }
Algorithm Library min() Function in C++
Return the smallest. Returns the smallest of a and b. If both are equivalent, a is returned. min() function is a library function of algorithm header, it is used to find the smallest value from given two values, it accepts two values and returns the smallest value and if both the values are the same it returns the first value. The versions for initializer lists (3) return the smallest of all the elements in the list. Returning the first of them if these are more than one. The function uses operator< (or comp, if provided) to compare the values.
Syntax for Algorithm min() Function in C++
#include <algorithm> //default (1) template <class T> const T& min (const T& a, const T& b); //custom (2) template <class T, class Compare> const T& min (const T& a, const T& b, Compare comp); //initializer list (3) template <class T> T min (initializer_list<T> il); template <class T, class Compare> T min (initializer_list<T> il, Compare comp);
a, b
Values to compare
comp
Binary function that accepts two values of type T as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered less than the second. The function shall not modify any of its arguments. This can either be a function pointer or a function object.
il
An initializer_list object. These objects are automatically constructed from initializer list declarators. T shall support being compared with operator<. For (3), T shall be copy constructible. Function returns the lesser of the values passed as arguments.
Complexity
Linear in one less than the number of elements compared (constant for (1) and (2)).
Exceptions
Throws if any comparison 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 26
/* std::min is defined in the header file <algorithm> and is used to find out the smallest of the number passed to it. It returns the first of them, if there are more than one. */ /* accept two values and return the smaller one by min() function code example. */ #include <iostream> #include <algorithm> using namespace std; // Defining the binary function bool comp(int a, int b) { return (a < b); } int main() { int a = 5; int b = 7; cout << std::min(a, b, comp) << "\n"; // Returns the first one if both the numbers // are same cout << std::min(7, 7, comp); return 0; }
Standard Output Stream (cout) in C++
The cout is a predefined object of ostream class. It is connected with the standard output device, which is usually a display screen. The cout is used in conjunction with stream insertion operator (<<) to display the output on a console. On most program environments, the standard output by default is the screen, and the C++ stream object defined to access it is cout.
Syntax for cout in C++
cout << var_name; //or cout << "Some String";
The syntax of the cout object in C++: cout << var_name; Or cout << "Some String";
<<
is the insertion operator
var_name
is usually a variable, but can also be an array element or elements of containers like vectors, lists, maps, etc. The "c" in cout refers to "character" and "out" means "output". Hence cout means "character output". The cout object is used along with the insertion operator << in order to display a stream of characters. The << operator can be used more than once with a combination of variables, strings, and manipulators. cout is used for displaying data on the screen. The operator << called as insertion operator or put to operator. The Insertion operator can be overloaded. Insertion operator is similar to the printf() operation in C. cout is the object of ostream class. Data flow direction is from variable to output device. Multiple outputs can be displayed using cout.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* standard output stream (cout) in C++ language */ #include <iostream> using namespace std; int main() { string str = "Do not interrupt me"; char ch = 'm'; // use cout with write() cout.write(str,6); cout << endl; // use cout with put() cout.put(ch); return 0; }
strlen() Function in C++
Get string length. Returns the length of the C string str. C++ strlen() is an inbuilt function that is used to calculate the length of the string. It is a beneficial method to find the length of the string. The strlen() function is defined under the string.h header file. The strlen() takes a null-terminated byte string str as its argument and returns its length. The length does not include a null character. If there is no null character in the string, the behavior of the function is undefined.
Syntax for strlen() Function in C++
#include <cstring> size_t strlen ( const char * str );
str
a string passed to this function, whose length needs to be found. Here str is the string variable of whose we have to find the length. It takes one parameter which is a pointer that points to the null-terminated byte string. The string is terminated by a null character. If a null character does not terminate it, then the behavior is undefined. It returns an integer giving the length of the passed string. Function returns the length of string. While calculating the total length of a String, the character at the first index is counted as 1 and not 0, i.e. one-based index . The function strlen returns the total number of characters actually present in the char[] and not the total number of character it can hold.
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
/* return the length of the C string str by strlen() function code example */ #include <cstring> #include <iostream> using namespace std; int main() { char str1[] = "This a string"; char str2[] = "This is another string"; // find lengths of str1 and str2 // size_t return value converted to int int len1 = strlen(str1); int len2 = strlen(str2); cout << "Length of str1 = " << len1 << endl; cout << "Length of str2 = " << len2 << endl; if (len1 > len2) cout << "str1 is longer than str2"; else if (len1 < len2) cout << "str2 is longer than str1"; else cout << "str1 and str2 are of equal length"; return 0; }
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 }
To call the namespace-enabled version of either function or variable, prepend (::) the namespace name as follows:
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 } }
• Namespace is a feature added in C++ and not present in C. • A namespace is a declarative region that provides a scope to the identifiers (names of the types, function, variables etc) inside it. • Multiple namespace blocks with the same name are allowed. All declarations within those blocks are declared in the named scope. • Namespace declarations appear only at global scope. • Namespace declarations can be nested within another namespace. • Namespace declarations don't have access specifiers. (Public or private) • No need to give semicolon after the closing brace of definition of namespace. • We can split the definition of namespace over several units.
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; }
Logical Operators in C++
Logical Operators are used to compare and connect two or more expressions or variables, such that the value of the expression is completely dependent on the original expression or value or variable. We use logical operators to check whether an expression is true or false. If the expression is true, it returns 1 whereas if the expression is false, it returns 0. Assume variable A holds 1 and variable B holds 0:
&&
Called Logical AND operator. If both the operands are non-zero, then condition becomes true. (A && B) is false. The logical AND operator && returns true - if and only if all the operands are true. false - if one or more operands are false.
||
Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true. (A || B) is true. The logical OR operator || returns true - if one or more of the operands are true. false - if and only if all the operands are false.
!
Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true, then Logical NOT operator will make false. !(A && B) is true. The logical NOT operator ! is a unary operator i.e. it takes only one operand. It returns true when the operand is false, and false when the operand is true.
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
/* The operator ! is the C++ operator for the Boolean operation NOT. It has only one operand, to its right, and inverts it, producing false if its operand is true, and true if its operand is false. Basically, it returns the opposite Boolean value of evaluating its operand. The logical operators && and || are used when evaluating two expressions to obtain a single relational result. The operator && corresponds to the Boolean logical operation AND, which yields true if both its operands are true, and false otherwise. */ #include <iostream> using namespace std; main() { int a = 5; int b = 20; int c ; if(a && b) { cout << "Line 1 - Condition is true"<< endl ; } if(a || b) { cout << "Line 2 - Condition is true"<< endl ; } /* Let's change the values of a and b */ a = 0; b = 10; if(a && b) { cout << "Line 3 - Condition is true"<< endl ; } else { cout << "Line 4 - Condition is not true"<< endl ; } if(!(a && b)) { cout << "Line 5 - Condition is true"<< endl ; } return 0; }
If Else Statement in C++
In computer programming, we use the if statement to run a block code only when a certain condition is met. An if statement can be followed by an optional else statement, which executes when the boolean expression is false. There are three forms of if...else statements in C++: • if statement, • if...else statement, • if...else if...else statement,
Syntax for If Statement in C++
if (condition) { // body of if statement }
The if statement evaluates the condition inside the parentheses ( ). If the condition evaluates to true, the code inside the body of if is executed. If the condition evaluates to false, the code inside the body of if is skipped.
Syntax for If...Else Statement
if (condition) { // block of code if condition is true } else { // block of code if condition is false }
The if..else statement evaluates the condition inside the parenthesis. If the condition evaluates true, the code inside the body of if is executed, the code inside the body of else is skipped from execution. If the condition evaluates false, the code inside the body of else is executed, the code inside the body of if is skipped from execution. The if...else statement is used to execute a block of code among two alternatives. However, if we need to make a choice between more than two alternatives, we use the if...else if...else statement.
Syntax for If...Else...Else If Statement in C++
if (condition1) { // code block 1 } else if (condition2){ // code block 2 } else { // code block 3 }
• If condition1 evaluates to true, the code block 1 is executed. • If condition1 evaluates to false, then condition2 is evaluated. • If condition2 is true, the code block 2 is executed. • If condition2 is false, the code block 3 is executed. There can be more than one else if statement but only one if and else statements. In C/C++ if-else-if ladder helps user decide from among multiple options. The C/C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
Syntax for If Else If Ladder in C++
if (condition) statement 1; else if (condition) statement 2; . . else statement;
Working of the if-else-if ladder: 1. Control falls into the if block. 2. The flow jumps to Condition 1. 3. Condition is tested. If Condition yields true, goto Step 4. If Condition yields false, goto Step 5. 4. The present block is executed. Goto Step 7. 5. The flow jumps to Condition 2. If Condition yields true, goto step 4. If Condition yields false, goto Step 6. 6. The flow jumps to Condition 3. If Condition yields true, goto step 4. If Condition yields false, execute else block. Goto Step 7. 7. Exits the if-else-if ladder. • The if else ladder statement in C++ programming language is used to check set of conditions in sequence. • This is useful when we want to selectively executes one code block(out of many) based on certain conditions. • It allows us to check for multiple condition expressions and execute different code blocks for more than two conditions. • A condition expression is tested only when all previous if conditions in if-else ladder is false. • If any of the conditional expression evaluates to true, then it will execute the corresponding code block and exits whole if-else ladder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* If Else Statement in C++ Language */ #include <iostream> using namespace std; int main () { // local variable declaration: int a = 100; // check the boolean condition if( a < 20 ) { // if condition is true then print the following cout << "a is less than 20;" << endl; } else { // if condition is false then print the following cout << "a is not less than 20;" << endl; } cout << "value of a is : " << a << endl; 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. }
Outer_loop and Inner_loop are the valid loops that can be a 'for' loop, 'while' loop or 'do-while' 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 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; }
#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"
Including using " ": When using the double quotes(" "), the preprocessor access the current directory in which the source "header_file" is located. This type is mainly used to access any header files of the user's program or user-defined files.
Including using <>: While importing file using angular brackets(<>), the the preprocessor uses a predetermined directory path to access the file. It is mainly used to access system header files located in the standard system directories. Header File or Standard files: This is a file which contains C/C++ function declarations and macro definitions to be shared between several source files. Functions like the printf(), scanf(), cout, cin and various other input-output or other standard functions are contained within different header files. So to utilise those functions, the users need to import a few header files which define the required functions. User-defined files: These files resembles the header files, except for the fact that they are written and defined by the user itself. This saves the user from writing a particular function multiple times. Once a user-defined file is written, it can be imported anywhere in the program using the #include preprocessor. • In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename. • In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename. • You can use only comment after filename otherwise it will give error.
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; }
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; }
What is an Multi-Dimensional Array
An array is a collection of data items, all of the same type, accessed using a common name. A one-dimensional array is like a list; A two dimensional array is like a table; The C++ language places no limits on the number of dimensions in an array, though specific implementations may. Some texts refer to one-dimensional arrays as vectors, two-dimensional arrays as matrices, and use the general term arrays when the number of dimensions is unspecified or unimportant.
Declaring Two-Dimensional Arrays
An array of arrays is known as 2D array. The two dimensional (2D) array in C++ programming is also known as matrix. A matrix can be represented as a table of rows and columns. In C/C++, we can define multi dimensional arrays in simple words as array of arrays. Data in multi dimensional arrays are stored in tabular form (in row major order). General form of declaring N-dimensional arrays is:
datatype arrayname[size1][size2]....[sizeN]; example: int 2d-array[8][16]; char letters[4][9]; float numbers[10][25];
Initializing Two-Dimensional Arrays
In the 1D array, we don't need to specify the size of the array if the declaration and initialization are being done simultaneously. However, this will not work with 2D arrays. We will have to define at least the second dimension of the array. The two-dimensional array can be declared and defined in the following way. Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an array with 3 rows and each row has 4 columns.
int numbers[3][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}};
Accessing Two-Dimensional Array Elements
Just like one-dimensional arrays, two-dimensional arrays also require indices to access the required elements. A row and a column index are needed to access a particular element; for nested loops, two indices (one to traverse the rows and the other to traverse the columns in each row) are required to print a two-dimensional array.
// an array with 3 rows and 2 columns. int x[3][2] = {{0,1}, {2,3}, {4,5}}; // output each array element's value for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) { cout << "Element at x[" << i << "][" << j << "]: "; cout << x[i][j]<<endl; } }
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
/* multi-dimensional arrays in C++ language */ /* taking input for two dimensional array */ #include <iostream> using namespace std; int main() { int numbers[2][3]; cout << "Enter 6 numbers: " << endl; // Storing user input in the array for (int i = 0; i < 2; ++i) { for (int j = 0; j < 3; ++j) { cin >> numbers[i][j]; } } cout << "The numbers are: " << endl; // Printing array elements for (int i = 0; i < 2; ++i) { for (int j = 0; j < 3; ++j) { cout << "numbers[" << i << "][" << j << "]: " << numbers[i][j] << endl; } } return 0; }
String Relational Operators in C++
Relational operators for string. Performs the appropriate comparison operation between the string objects lhs and rhs. The functions use string::compare for the comparison. These operators are overloaded in header <string>. If strings are compared using relational operators then, their characters are compared lexicographically according to the current character traits, means it starts comparison character by character starting from the first character until the characters in both strings are equal or a NULL character is encountered.
Syntax for String Relational Operators in C++
#include <string> //(1) == : Equal to bool operator== (const string& lhs, const string& rhs) noexcept; bool operator== (const char* lhs, const string& rhs); bool operator== (const string& lhs, const char* rhs); //(2) != : Not equal to bool operator!= (const string& lhs, const string& rhs) noexcept; bool operator!= (const char* lhs, const string& rhs); bool operator!= (const string& lhs, const char* rhs); //(3) < : Less than bool operator< (const string& lhs, const string& rhs) noexcept; bool operator< (const char* lhs, const string& rhs); bool operator< (const string& lhs, const char* rhs); //(4) <= : Less than and equal to bool operator<= (const string& lhs, const string& rhs) noexcept; bool operator<= (const char* lhs, const string& rhs); bool operator<= (const string& lhs, const char* rhs); //(5) > : Greater than bool operator> (const string& lhs, const string& rhs) noexcept; bool operator> (const char* lhs, const string& rhs); bool operator> (const string& lhs, const char* rhs); //(6) >= : Greater than and equal to bool operator>= (const string& lhs, const string& rhs) noexcept; bool operator>= (const char* lhs, const string& rhs); bool operator>= (const string& lhs, const char* rhs);
lhs, rhs
Arguments to the left- and right-hand side of the operator, respectively. If of type char*, it shall point to a null-terminated character sequence. • lhs < rhs : A string lhs is smaller than rhs string, if either, length of lhs is shorter than rhs or first mismatched character is smaller. • lhs > rhs : A string lhs is greater than rhs string, if either, length of lhs is longer than rhs or first mismatched character is larger. • <= and >= have almost same implementation with additional feature of being equal as well. • If after comparing lexicographically, both strings are found same, then they are said to be equal. • If any of the points from 1 to 3 follows up then, strings are said to be unequal. Function returns true if the condition holds, and false otherwise.
Complexity
Unspecified, but generally up to linear in both lhs and rhs's lengths.
Iterator validity
No changes
Data races
Both objects, lhs and rhs, are accessed.
Exception safety
If an argument of type char* does not point to null-terminated character sequence, it causes undefined behavior. For operations between string objects, exceptions are never thrown (no-throw guarantee). For other cases, if an exception is thrown, there are no changes in the string (strong guarantee).
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
/* If strings are compared using relational operators then, their characters are compared lexicographically according to the current character traits, means it starts comparison character by character starting from the first character until the characters in both strings are equal or a NULL character is encountered. */ // CPP code example to implement relational operators on String objects #include<iostream> using namespace std; void relational_operation(string s1, string s2) { string s3 = s1 + s2; if(s1 != s2) cout << s1 << " is not equal to " << s2 << endl; if(s1 > s2) cout << s1 << " is greater than " << s2 << endl; else if(s1 < s2) cout << s1 << " is smaller than " << s2 << endl; if(s3 == s1 + s2) cout << s3 << " is equal to " << s1 + s2 << endl; } // Main function int main() { string s1("Happy"); string s2("Happy 8) Codings"); relational_operation(s1, s2); return 0; }
Standard end line (endl) in C++
A predefined object of the class called iostream class is used to insert the new line characters while flushing the stream is called endl in C++. This endl is similar to \n which performs the functionality of inserting new line characters but it does not flush the stream whereas endl does the job of inserting the new line characters while flushing the stream. Hence the statement cout<<endl; will be equal to the statement cout<< '\n' << flush; meaning the new line character used along with flush explicitly becomes equivalent to the endl statement in C++.
Syntax for end line (endl) in C++
cout<< statement to be executed <<endl;
Whenever the program is writing the output data to the stream, all the data will not be written to the terminal at once. Instead, it will be written to the buffer until enough data is collected in the buffer to output to the terminal. But if are using flush in our program, the entire output data will be flushed to the terminal directly without storing anything in the buffer. Whenever there is a need to insert the new line character to display the output in the next line while flushing the stream, we can make use of endl in C++. Whenever there is a need to insert the new line character to display the output in the next line, we can make use of endl in '\n' character but it does not do the job of flushing the stream. So if we want to insert a new line character along with flushing the stream, we make use of endl in C++. Whenever the program is writing the output data to the stream, all the data will not be written to the terminal at once. Instead, it will be written to the buffer until enough data is collected in the buffer to output to the terminal. • It is a manipulator. • It doesn't occupy any memory. • It is a keyword and would not specify any meaning when stored in a string. • We cannot write 'endl' in between double quotations. • It is only supported by C++. • It keeps flushing the queue in the output buffer throughout the process.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* Standard end line (endl) in C++ language */ //The header file iostream is imported to enable us to use cout in the program #include <iostream> //a namespace called std is defined using namespace std; //main method is called int main( ) { //cout is used to output the statement cout<< "Welcome to "; //cout is used to output the statement along with endl to start the next statement in the new line and flush the output stream cout<< "C#"<<endl; //cout is used to output the statement along with endl to start the next statement in the new line and flush the output stream cout<< "Learning is fun"<<endl; }
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; }

C++ Program to "generate random numbers" using Linear Congruential Generator. A linear congruential generator (LCG) is an algorithm that yields a sequence of pseudo-randomized
Linear search is method for searching a value within an array. It 'sequentially' checks one by one of the arrays for the 'target element' until 'match is found' or until all the elements have
This algorithm takes the 'Input of the Natural' number and prints all the possible partition of each number less than or equal to it. For each number, it starts with the number and breaks