Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes


C++ Programming Code Examples

C++ > Beginners Lab Assignments Code Examples

C++ Program to Implement String in STL

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 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
/* C++ Program to Implement String in STL */ #include <iostream> #include <string> #include <cstdlib> using namespace std; int main() { int choice, pos, len; string::iterator it; size_t found; string s, str = "Happy Codings - C++ Programming Language Code Examples."; cout<<"Initial String is--> "<<str<<endl; while (1) { cout<<"\n---------------------"<<endl; cout<<"String Implementation in Stl"<<endl; cout<<"\n---------------------"<<endl; cout<<"1.Insert Substring in a String"<<endl; cout<<"2.Erase Substring from a String"<<endl; cout<<"3.Append Substring to a String"<<endl; cout<<"4.Replace the String with a Substrng"<<endl; cout<<"5.Size of the String"<<endl; cout<<"6.Find substring in a String"<<endl; cout<<"7.Display the String"<<endl; cout<<"8.Exit"<<endl; cout<<"Enter your Choice: "; cin>>choice; switch(choice) { case 1: cout<<"Enter the substring to be inserted: "; cin>>s; cout<<"Position after which substring to be inserted: "; cin>>pos; if (pos <= str.length()) str.insert(pos, s); else cout<<"Position out of bounds"<<endl; break; case 2: cout<<"Position after which substring to be erased: "; cin>>pos; cout<<"Length of the substring to be deleted: "; cin>>len; str.erase(pos, len); break; case 3: s = " This is an appended string."; str.append(s); break; case 4: s = "n example"; str.replace(9, 5, s); break; case 5: cout<<"Size of the string: "<<str.size()<<endl; break; case 6: cout<<"Enter substring to be found: "; cin>>s; found = str.find(s); if (found != string::npos) cout <<"Substring "<<s<<" found at " << found <<endl; else cout <<"Substring "<<s<<" not found"<<endl; break; case 7: for (it = str.begin(); it != str.end(); ++it) cout<<*it; cout<<endl; break; case 8: exit(1); break; default: cout<<"Wrong Choice"<<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;
• Iterators are used to traverse from one element to another element, a process is known as iterating through the container. • The main advantage of an iterator is to provide a common interface for all the containers type. • Iterators make the algorithm independent of the type of the container used. • Iterators provide a generic approach to navigate through the elements of a container. Operator (*) : The '*' operator returns the element of the current position pointed by the iterator. Operator (++) : The '++' operator increments the iterator by one. Therefore, an iterator points to the next element of the container. Operator (==) and Operator (!=) : Both these operators determine whether the two iterators point to the same position or not. Operator (=) : The '=' operator assigns the iterator. Iterators can be smart pointers which allow to iterate over the complex data structures. A Container provides its iterator type. Therefore, we can say that the iterators have the common interface with different container type. The container classes provide two basic member functions that allow to iterate or move through the elements of a container: begin(): The begin() function returns an iterator pointing to the first element of the container. end(): The end() function returns an iterator pointing to the past-the-last element of the container. Input Iterator: An input iterator is an iterator used to access the elements from the container, but it does not modify the value of a container. Operators used for an input iterator are: Increment operator(++), Equal operator(==), Not equal operator(!=), Dereference operator(*). Output Iterator: An output iterator is an iterator used to modify the value of a container, but it does not read the value from a container. Therefore, we can say that an output iterator is a write-only iterator. Operators used for an output iterator are: Increment operator(++), Assignment operator(=). Forward Iterator: A forward iterator is an iterator used to read and write to a container. It is a multi-pass iterator. Operators used for a Forward iterator are: Increment operator(++), Assignment operator(=), Equal operator(=), Not equal operator(!=). Bidirectional iterator: A bidirectional iterator is an iterator supports all the features of a forward iterator plus it adds one more feature, i.e., decrement operator(--). We can move backward by decrementing an iterator. Operators used for a Bidirectional iterator are: Increment operator(++), Assignment operator(=), Equal operator(=), Not equal operator(!=), Decrement operator(--). Random Access Iterator: A Random Access iterator is an iterator provides random access of an element at an arbitrary location. It has all the features of a bidirectional iterator plus it adds one more feature, i.e., pointer addition and pointer subtraction to provide random access to an element. Following are the disadvantages of an iterator: • If we want to move from one data structure to another at the same time, iterators won't work. • If we want to update the structure which is being iterated, an iterator won?t allow us to do because of the way it stores the position. • If we want to backtrack while processing through a list, the iterator will not work in this case. Following are the advantages of an iterator: • Ease in programming: It is convenient to use iterators rather than using a subscript operator[] to access the elements of a container. If we use subscript operator[] to access the elements, then we need to keep the track of the number of elements added at the runtime, but this would not happen in the case of an iterator. • Code Reusability: A code can be reused if we use iterators. In the above example, if we replace vector with the list, and then the subscript operator[] would not work to access the elements as the list does not support the random access. However, we use iterators to access the elements, then we can also access the list elements. • Dynamic Processing: C++ iterators provide the facility to add or delete the data dynamically.
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; }
string::npos in C++ Language
Maximum value for size_t. This value, when used as the value for a len parameter in string's member functions, means until the end of the string. This constant is defined with a value of -1. Since size_t is an unsigned integral type, -1 is the largest possible representable value for this type. To put it simply, think of npos as no-position. As a return value, it is usually used to indicate that no matches were found in the string. Thus, if it returns true, matches were found at no positions (i.e., no matches).
Syntax for string::npos in C++
static const size_t npos = -1;
npos is a static member constant value with the greatest possible value for an element of type size_t. This value, when used as the value for a len (or sublen) parameter in string's member functions, means "until the end of the string". As a return value, it is usually used to indicate no matches. This constant is defined with a value of -1, which because size_t is an unsigned integral type, it is the largest possible representable value for this type.
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
/* string::npos is a static member value with the maximum value for an element of type size_t which is the end of the string. As the Return value indicates no matches are found in the string. It simply states "no-position". */ // C++ program code example to demonstrate the use of string::npos // Function that using string::npos to find the index of the occurrence of any string in the given string void fun(string s1, string s2) { // Find position of string s2 int found = s1.find(s2); // Check if position is -1 or not if (found != string::npos) { cout << "first " << s2 << " found at: " << (found) << endl; } else cout << s2 << " is not in" << "the string" << endl; } // Driver Code int main() { // Given strings string s1 = "HappyCodings"; string s2 = "ppy"; string s3 = "no"; // Function Call fun(s1, s2); 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; }
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; }
String Library append() Function in C++
Append to string. This function is used to extend the string by appending at the end of the current value. Extends the string by appending additional characters at the end of its current value. Append is a special function in the string library of C++ which is used to append string of characters to another string and returns * this operator. This is similar to push_back or += operator, but it allows multiple characters to append at the same time. This means a character array can also be appended but it doesn't allow appending a single character. It also allows to append a specific part of the second string to the first string or defining the number of time a string must be appended. An iterator range is also provided to iterate over the character of strings.
Syntax for String append() Function in C++
#include <string> //string (1) string& append (const string& str); //substring (2) string& append (const string& str, size_t subpos, size_t sublen); //c-string (3) string& append (const char* s); //buffer (4) string& append (const char* s, size_t n); //fill (5) string& append (size_t n, char c); //range (6) template <class InputIterator> string& append (InputIterator first, InputIterator last); //initializer list(7) string& append (initializer_list<char> il);
str
Another string object, whose value is appended.
subpos
Position of the first character in str that is copied to the object as a substring. If this is greater than str's length, it throws out_of_range. Note: The first character in str is denoted by a value of 0 (not 1).
sublen
Length of the substring to be copied (if the string is shorter, as many characters as possible are copied). A value of string::npos indicates all characters until the end of str.
s
Pointer to an array of characters (such as a c-string).
n
Number of characters to copy.
c
Character value, repeated n times.
first, last
Input iterators to the initial and final positions in a range. The range used is [first,last), which includes all the characters between first and last, including the character pointed by first but not the character pointed by last. The function template argument InputIterator shall be an input iterator type that points to elements of a type convertible to char. If InputIterator is an integral type, the arguments are casted to the proper types so that signature (5) is used instead.
il
An initializer_list object. These objects are automatically constructed from initializer list declarators. size_t is an unsigned integral type. Function returns *this (1) string: Appends a copy of str. (2) substring: Appends a copy of a substring of str. The substring is the portion of str that begins at the character position subpos and spans sublen characters (or until the end of str, if either str is too short or if sublen is string::npos). (3) c-string: Appends a copy of the string formed by the null-terminated character sequence (C-string) pointed by s. (4) buffer: Appends a copy of the first n characters in the array of characters pointed by s. (5) fill: Appends n consecutive copies of character c. (6) range: Appends a copy of the sequence of characters in the range [first,last), in the same order. (7) initializer list: Appends a copy of each of the characters in il, in the same order.
Complexity
Unspecified, but generally up to linear in the new string length.
Iterator validity
Any iterators, pointers and references related to this object may be invalidated.
Data races
The object is modified.
Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the string. If s does not point to an array long enough, or if the range specified by [first,last) is not valid, it causes undefined behavior. If subpos is greater than str's length, an out_of_range exception is thrown. If the resulting string length would exceed the max_size, a length_error exception is thrown. A bad_alloc exception is thrown if the function needs to allocate storage and fails. Therefore, we can append() multiple strings to this string, in a single statement. str1.append(str2).append(str3);
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
/* appends characters in the end of string by append() function code example */ // CPP code to demonstrate append(const char* chars, size_type chars_len) #include <iostream> #include <string> using namespace std; // Function to demonstrate append() void appendDemo(string str1, string str2) { // Appends 5 characters from 0th index of // str2 to str1 str1.append(str2, 0, 5); cout << "Using append() : "; cout << str1; } // Driver code int main() { string str1("HappyCodings "); string str2("Hello World! "); cout << "Original String : " << str1 << endl; appendDemo(str1, str2); 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; }
Break Statement in C++
Break statement in C++ is a loop control statement defined using the break keyword. It is used to stop the current execution and proceed with the next one. When a compiler calls the break statement, it immediately stops the execution of the loop and transfers the control outside the loop and executes the other statements. In the case of a nested loop, break the statement stops the execution of the inner loop and proceeds with the outer loop. The statement itself says it breaks the loop. When the break statement is called in the program, it immediately terminates the loop and transfers the flow control to the statement mentioned outside the loop.
Syntax for Break Statement in C++
// jump-statement; break;
The break statement is used in the following scenario: • When a user is not sure about the number of iterations in the program. • When a user wants to stop the program based on some condition. The break statement terminates the loop where it is defined and execute the other. If the condition is mentioned in the program, based on the condition, it executes the loop. If the condition is true, it executes the conditional statement, and if the break statement is mentioned, it will immediately break the program. otherwise, the loop will iterate until the given condition fails. if the condition is false, it stops the program.
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
/* break statement with while loop code example */ // program to find the sum of positive numbers // if the user enters a negative numbers, break ends the loop // the negative number entered is not added to sum #include <iostream> using namespace std; int main() { int number; int sum = 0; while (true) { // take input from the user cout << "Enter a number: "; cin >> number; // break condition if (number < 0) { break; } // add all positive numbers sum += number; } // display the sum cout << "The sum is " << sum << endl; return 0; }
String Library insert() Function in C++
Insert into string. Inserts additional characters into the string right before the character indicated by pos (or p): insert() is used to insert characters in string at specified position. It supports various syntaxes to facilitate same, here we will describe them.
Syntax for String insert() Function in C++
#include <string> //string (1) string& insert (size_t pos, const string& str); //substring (2) string& insert (size_t pos, const string& str, size_t subpos, size_t sublen); //c-string (3) string& insert (size_t pos, const char* s); //buffer (4) string& insert (size_t pos, const char* s, size_t n); //fill (5) string& insert (size_t pos, size_t n, char c); iterator insert (const_iterator p, size_t n, char c); //single character (6) iterator insert (const_iterator p, char c); //range (7) template <class InputIterator> iterator insert (iterator p, InputIterator first, InputIterator last); //initializer list (8) string& insert (const_iterator p, initializer_list<char> il);
pos
Insertion point: The new contents are inserted before the character at position pos. If this is greater than the object's length, it throws out_of_range. The first character is denoted by a value of 0 (not 1).
str
Another string object.
subpos
Position of the first character in str that is inserted into the object as a substring. If this is greater than str's length, it throws out_of_range. The first character in str is denoted by a value of 0 (not 1).
sublen
Length of the substring to be copied (if the string is shorter, as many characters as possible are copied). A value of npos indicates all characters until the end of str.
s
Pointer to an array of characters (such as a c-string).
n
Number of characters to insert.
c
Character value.
p
Iterator pointing to the insertion point: The new contents are inserted before the character pointed by p. iterator is a member type, defined as a random access iterator type that points to characters of the string.
first, last
Input iterators to the initial and final positions in a range. The range used is [first,last), which includes all the characters between first and last, including the character pointed by first but not the character pointed by last. The function template argument InputIterator shall be an input iterator type that points to elements of a type convertible to char.
il
An initializer_list object. These objects are automatically constructed from initializer list declarators. • (1) string Inserts a copy of str. • (2) substring Inserts a copy of a substring of str. The substring is the portion of str that begins at the character position subpos and spans sublen characters (or until the end of str, if either str is too short or if sublen is npos). • (3) c-string Inserts a copy of the string formed by the null-terminated character sequence (C-string) pointed by s. • (4) buffer Inserts a copy of the first n characters in the array of characters pointed by s. • (5) fill Inserts n consecutive copies of character c. • (6) single character Inserts character c. • (7) range Inserts a copy of the sequence of characters in the range [first,last), in the same order. • (8) initializer list Inserts a copy of each of the characters in il, in the same order. size_t is an unsigned integral type (the same as member type string::size_type). Function returns the signatures returning a reference to string, return *this. Those returning an iterator, return an iterator pointing to the first character inserted. Member type iterator is a random access iterator type that points to characters of the string.
Complexity
Unspecified, but generally up to linear in the new string length.
Iterator validity
Any iterators, pointers and references related to this object may be invalidated.
Data races
The object is modified.
Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the string. If s does not point to an array long enough, or if either p or the range specified by [first,last) is not valid, it causes undefined behavior. If pos is greater than the string length, or if subpos is greater than str's length, an out_of_range exception is thrown. If the resulting string length would exceed the max_size, a length_error exception is thrown. A bad_alloc exception is thrown if the function needs to allocate storage and fails.
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
/* insert() string function is used to insert a new character, before the character indicated by the position pos. */ /* Insert into string by insert() function code example */ // CPP code for insert(size_ type idx, const char* cstr) #include <iostream> #include <string> using namespace std; // Function to demonstrate insert void insertDemo(string str) { // Inserts " are " at 5th index of str str.insert(5, " are "); cout << "Using insert : "; cout << str; } // Driver code int main() { string str("HappyCodings "); cout << "Original String : " << str << endl; insertDemo(str); return 0; }
Switch Case Statement in C++
Switch statement in C tests the value of a variable and compares it with multiple cases. Once the case match is found, a block of statements associated with that particular case is executed. Each case in a block of a switch has a different name/number which is referred to as an identifier. The value provided by the user is compared with all the cases inside the switch block until the match is found. If a case match is NOT found, then the default statement is executed, and the control goes out of the switch block.
Syntax for Switch Case Statement in C++
switch( expression ) { case value-1: Block-1; Break; case value-2: Block-2; Break; case value-n: Block-n; Break; default: Block-1; Break; } Statement-x;
• The expression can be integer expression or a character expression. • Value-1, 2, n are case labels which are used to identify each case individually. Remember that case labels should not be same as it may create a problem while executing a program. Suppose we have two cases with the same label as '1'. Then while executing the program, the case that appears first will be executed even though you want the program to execute a second case. This creates problems in the program and does not provide the desired output. • Case labels always end with a colon ( : ). Each of these cases is associated with a block. • A block is nothing but multiple statements which are grouped for a particular case. • Whenever the switch is executed, the value of test-expression is compared with all the cases which we have defined inside the switch. Suppose the test expression contains value 4. This value is compared with all the cases until case whose label four is found in the program. As soon as a case is found the block of statements associated with that particular case is executed and control goes out of the switch. • The break keyword in each case indicates the end of a particular case. If we do not put the break in each case then even though the specific case is executed, the switch in C will continue to execute all the cases until the end is reached. This should not happen; hence we always have to put break keyword in each case. Break will terminate the case once it is executed and the control will fall out of the switch. • The default case is an optional one. Whenever the value of test-expression is not matched with any of the cases inside the switch, then the default will be executed. Otherwise, it is not necessary to write default in the switch. • Once the switch is executed the control will go to the statement-x, and the execution of a program will continue.
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
/* the switch statement helps in testing the equality of a variable against a set of values */ #include <iostream> using namespace std; int main () { // local variable declaration: char grade = 'D'; switch(grade) { case 'A' : cout << "Excellent!" << endl; break; case 'B' : case 'C' : cout << "Well done" << endl; break; case 'D' : cout << "You passed" << endl; break; case 'F' : cout << "Better try again" << endl; break; default : cout << "Invalid grade" << endl; } cout << "Your grade is " << grade << endl; return 0; }
Strings in C++ Language
Strings are objects that represent sequences of characters. The standard string class provides support for such objects with an interface similar to that of a standard container of bytes, but adding features specifically designed to operate with strings of single-byte characters. The string class is an instantiation of the basic_string class template that uses char (i.e., bytes) as its character type, with its default char_traits and allocator types. Note that this class handles bytes independently of the encoding used: If used to handle sequences of multi-byte or variable-length characters (such as UTF-8), all members of this class (such as length or size), as well as its iterators, will still operate in terms of bytes (not actual encoded characters).
Declaration for Strings in C++
char str[4] = "C++ Programming"; char str[] = {'C','+','+','\0'}; char str[4] = {'C','+','+','\0'};
In C programming, the collection of characters is stored in the form of arrays. This is also supported in C++ programming. Hence it's called C-strings. C-strings are arrays of type char terminated with null character, that is, \0 (ASCII value of null character is 0). • A character array is simply an array of characters that can be terminated by a null character. A string is a class that defines objects that be represented as a stream of characters. • The size of the character array has to be allocated statically, more memory cannot be allocated at run time if required. Unused allocated memory is wasted in the case of the character array. In the case of strings, memory is allocated dynamically. More memory can be allocated at run time on demand. As no memory is preallocated, no memory is wasted. • There is a threat of array decay in the case of the character array. As strings are represented as objects, no array decay occurs. • Implementation of character array is faster than std:: string. Strings are slower when compared to implementation than character array. • Character arrays do not offer many inbuilt functions to manipulate strings. String class defines a number of functionalities that allow manifold operations on strings.
String Functions in C++
• int compare(const string& str): It is used to compare two string objects. • int length(): It is used to find the length of the string. • void swap(string& str): It is used to swap the values of two string objects. • string substr(int pos,int n): It creates a new string object of n characters. • int size(): It returns the length of the string in terms of bytes. • void resize(int n): It is used to resize the length of the string up to n characters. • string& replace(int pos,int len,string& str): It replaces portion of the string that begins at character position pos and spans len characters. • string& append(const string& str): It adds new characters at the end of another string object. • char& at(int pos): It is used to access an individual character at specified position pos. • int find(string& str,int pos,int n): It is used to find the string specified in the parameter. • int find_first_of(string& str,int pos,int n): It is used to find the first occurrence of the specified sequence. • int find_first_not_of(string& str,int pos,int n ): It is used to search the string for the first character that does not match with any of the characters specified in the string. • int find_last_of(string& str,int pos,int n): It is used to search the string for the last character of specified sequence. • int find_last_not_of(string& str,int pos): It searches for the last character that does not match with the specified sequence. • string& insert(): It inserts a new character before the character indicated by the position pos. • int max_size(): It finds the maximum length of the string. • void push_back(char ch): It adds a new character ch at the end of the string. • void pop_back(): It removes a last character of the string. • string& assign(): It assigns new value to the string. • int copy(string& str): It copies the contents of string into another. • char& back(): It returns the reference of last character. • Iterator begin(): It returns the reference of first character. • int capacity(): It returns the allocated space for the string. • const_iterator cbegin(): It points to the first element of the string. • const_iterator cend(): It points to the last element of the string. • void clear(): It removes all the elements from the string. • const_reverse_iterator crbegin(): It points to the last character of the string. • const_char* data(): It copies the characters of string into an array. • bool empty(): It checks whether the string is empty or not. • string& erase(): It removes the characters as specified. • char& front(): It returns a reference of the first character. • string& operator+=(): It appends a new character at the end of the string. • string& operator=(): It assigns a new value to the string. • char operator[](pos): It retrieves a character at specified position pos. • int rfind(): It searches for the last occurrence of the string. • iterator end(): It references the last character of the string. • reverse_iterator rend(): It points to the first character of the string. • void shrink_to_fit(): It reduces the capacity and makes it equal to the size of the string. • char* c_str(): It returns pointer to an array that contains null terminated sequence of characters. • const_reverse_iterator crend(): It references the first character of the string. • reverse_iterator rbegin(): It reference the last character of the string. • void reserve(inr len): It requests a change in capacity. • allocator_type get_allocator();: It returns the allocated object associated with the string.
Non-member Function Overloads
• operator+ Concatenate strings (function ) • relational operators Relational operators for string (function ) • swap Exchanges the values of two strings (function ) • operator>> Extract string from stream (function ) • operator<< Insert string into stream (function ) • getline Get line from stream into string (function )
Operators used for String Objects
• =: assignment • +: concatenation • ==: Equality • !=: Inequality • <: Less than • <=: Less than or equal • >: Greater than • >=: Greater than or equal • []: Subscription • <<: Output • >>: Input
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
/* C++ String Library */ /* The C-Style Character String */ // C++ Program to demonstrate the working of getline(), push_back() and pop_back() #include <iostream> #include <string> // for string class using namespace std; // Driver Code int main() { // Declaring string string str; // Taking string input using getline() getline(cin, str); // Displaying string cout << "The initial string is : "; cout << str << endl; // Inserting a character str.push_back('s'); // Displaying string cout << "The string after push_back operation is : "; cout << str << endl; // Deleting a character str.pop_back(); // Displaying string cout << "The string after pop_back operation is : "; cout << str << endl; 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; }
String Library erase() Function in C++
Erase characters from string. Erases part of the string, reducing its length. erase() string function removes the characters as specified, reducing its length by one. • sequence (1) Erases the portion of the string value that begins at the character position pos and spans len characters (or until the end of the string, if either the content is too short or if len is string::npos. Notice that the default argument erases all characters in the string (like member function clear). • character (2) Erases the character pointed by p. • range (3) Erases the sequence of characters in the range [first,last).
Syntax for String erase() Function in C++
#include <string> //sequence (1) string& erase (size_t pos = 0, size_t len = npos); //character (2) iterator erase (const_iterator p); //range (3) iterator erase (const_iterator first, const_iterator last);
pos
Position of the first character to be erased. If this is greater than the string length, it throws out_of_range. The first character in str is denoted by a value of 0 (not 1).
len
Number of characters to erase (if the string is shorter, as many characters as possible are erased). A value of string::npos indicates all characters until the end of the string.
p
Iterator to the character to be removed.
first, last
Iterators specifying a range within the string] to be removed: [first,last). i.e., the range includes all the characters between first and last, including the character pointed by first but not the one pointed by last. size_t is an unsigned integral type (the same as member type string::size_type). Member types iterator and const_iterator are random access iterator types that point to characters of the string. The sequence version (1) returns *this. The others return an iterator referring to the character that now occupies the position of the first character erased, or string::end if no such character exists. Member type iterator is a random access iterator type that points to characters of the string.
Complexity
Unspecified, but generally up to linear in the new string length.
Iterator validity
Any iterators, pointers and references related to this object may be invalidated.
Data races
The object is modified
Exception safety
For (1) and (3), if an exception is thrown, there are no changes in the string (strong guarantee). For (2), it never throws exceptions (no-throw guarantee). If pos is greater than the string length, an out_of_range exception is thrown. An invalid range in (3), causes 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 27 28 29 30
/* erase function will delete specific characters, starting from the iterator begin position before the iterator end position. It does not delete the character at iterator end. */ /* Erase characters from string by string erase() function code example */ #include <iostream> #include <string> using namespace std; // Function to demo erase() void eraseDemo(string str) { // Deletes all characters str.erase(); cout << "After erase() : "; cout << str; } // Driver code int main() { string str("Hello World!"); cout << "Before erase() : "; cout << str << endl; eraseDemo(str); return 0; }
length() Function in C++
Return length of string. Returns the length of the string, in terms of bytes. This function is used to find the length of the string in terms of bytes. This is the actual number of bytes that conform the contents of the string , which is not necessarily equal to the storage capacity. This is the number of actual bytes that conform the contents of the string, which is not necessarily equal to its storage capacity. Note that string objects handle bytes without knowledge of the encoding that may eventually be used to encode the characters it contains. Therefore, the value returned may not correspond to the actual number of encoded characters in sequences of multi-byte or variable-length characters (such as UTF-8).
Syntax for length() Function in C++
size_t length() const noexcept;
This function does not accept any parameter. Function returns the number of bytes in the string. size_t is an unsigned integral type (the same as member type string::size_type). Both string::size and string::length are synonyms and return the exact same value. The length() function is also defined inside the string.h header file and works in the same way size() does. Both functions return the same values and are also used in the same way. This function contains single parameter. This function returns the integer value in terms of bytes.
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
/* return length of string by length() function code example */ #include<iostream> #include<cstring> using namespace std; main() { string myStr = "This is a sample string"; char myStrChar[] = "This is a sample string"; cout << "String length using string::length() function: " << myStr.length() <<endl; cout << "String length using string::size() function: " << myStr.size() <<endl; cout << "String length using strlen() function for c like string: " << strlen(myStrChar) <<endl; cout << "String length using while loop: "; char *ch = myStrChar; int count = 0; while(*ch != '\0'){ count++; ch++; } cout << count << endl; cout << "String length using for loop: "; count = 0; for(int i = 0; myStrChar[i] != '\0'; i++){ count++; } cout << count; }
String Library replace() Function in C++
Replace portion of string. Replaces the portion of the string that begins at character pos and spans len characters (or the part of the string in the range between [i1,i2)) by new contents. The replace() function is a part of the string functions which C++ provides. It helps in replacing a part of the string which will begin with a certain position which will act as a start and it will extend till a certain number of characters. This string will be replaced with the specified string. The string to be replaced with the start and end positions should be given to the replace() function as parameters that help us in replacing the string.
Syntax for String replace() Function in C++
#include <string> //string (1) string& replace (size_t pos, size_t len, const string& str); string& replace (const_iterator i1, const_iterator i2, const string& str); //substring (2) string& replace (size_t pos, size_t len, const string& str, size_t subpos, size_t sublen); //c-string (3) string& replace (size_t pos, size_t len, const char* s); string& replace (const_iterator i1, const_iterator i2, const char* s); //buffer (4) string& replace (size_t pos, size_t len, const char* s, size_t n); string& replace (const_iterator i1, const_iterator i2, const char* s, size_t n); //fill (5) string& replace (size_t pos, size_t len, size_t n, char c); string& replace (const_iterator i1, const_iterator i2, size_t n, char c); //range (6) template <class InputIterator> string& replace (const_iterator i1, const_iterator i2, InputIterator first, InputIterator last); //initializer list (7) string& replace (const_iterator i1, const_iterator i2, initializer_list<char> il);
str
Another string object, whose value is copied.
pos
Position of the first character to be replaced. If this is greater than the string length, it throws out_of_range.
len
Number of characters to replace (if the string is shorter, as many characters as possible are replaced). A value of string::npos indicates all characters until the end of the string.
subpos
Position of the first character in str that is copied to the object as replacement. If this is greater than str's length, it throws out_of_range.
sublen
Length of the substring to be copied (if the string is shorter, as many characters as possible are copied). A value of string::npos indicates all characters until the end of str.
s
Pointer to an array of characters (such as a c-string).
n
Number of characters to copy.
c
Character value, repeated n times.
first, last
Input iterators to the initial and final positions in a range. The range used is [first,last), which includes all the characters between first and last, including the character pointed by first but not the character pointed by last. The function template argument InputIterator shall be an input iterator type that points to elements of a type convertible to char.
il
An initializer_list object. These objects are automatically constructed from initializer list declarators. size_t is an unsigned integral type (the same as member type string::size_type). Function returns *this
Complexity
Unspecified, but generally up to linear in the new string length.
Iterator validity
Any iterators, pointers and references related to this object may be invalidated.
Data races
The object is modified.
Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the string. If s does not point to an array long enough, or if the range specified by [first,last) is not valid, it causes undefined behavior. If pos is greater than the string length, or if subpos is greater than str's length, an out_of_range exception is thrown. If the resulting string length would exceed the max_size, a length_error exception is thrown. A bad_alloc exception is thrown if the function needs to allocate storage and fails.
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
/* replace the portion of string that begins at character position pos and spans len characters by replace() function code example. */ // CPP code example to demonstrate replace() function #include <iostream> using namespace std; // Function for demonstration void replaceDemo(string s1, string s2, string s3, string s4) { // Replaces 7 characters from 0th index by s2 s1.replace(0, 7, s2); cout << s1 << endl; // Replaces 3 characters from 0th index with "Hello" s4.replace(0, 3, "Hello "); cout << s4 << endl; // Replaces 5 characters from 6th index of s4 with // 5 characters from 0th of s3 s4.replace(6, 5, s3, 0, 5); cout << s4 << endl; // Replaces 5 characters from 6th index of s4 with // 6 characters from string "to all" s4.replace(6, 5, "to all", 6); cout << s4 << endl; // Replaces 1 character from 12th index of s4 with // 3 copies of '!' s4.replace(12, 1, 3, '!'); cout << s4 << endl; } // Driver code int main() { string s1 = "Example of replace"; string s2 = "Demonstration"; string s3 = "Happy8)Codings"; string s4 = "HeyWorld !"; replaceDemo(s1, s2, s3, s4); 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; }
Standard Input Stream (cin) in C++
The cin object is used to accept input from the standard input device i.e. keyboard. It is defined in the iostream header file. C++ cin statement is the instance of the class istream and is used to read input from the standard input device which is usually a keyboard. The extraction operator(>>) is used along with the object cin for reading inputs. The extraction operator extracts the data from the object cin which is entered using the keyboard.
Syntax for Standard Input Stream (cin) in C++
cin >> var_name;
>>
is the extraction operator.
var_name
is usually a variable, but can also be an element of containers like arrays, vectors, lists, etc. The "c" in cin refers to "character" and "in" means "input". Hence cin means "character input". The cin object is used along with the extraction operator >> in order to receive a stream of characters. The >> operator can also be used more than once in the same statement to accept multiple inputs. The cin object can also be used with other member functions such as getline(), read(), etc. Some of the commonly used member functions are: • cin.get(char &ch): Reads an input character and stores it in ch. • cin.getline(char *buffer, int length): Reads a stream of characters into the string buffer, It stops when: it has read length-1 characters or when it finds an end-of-line character '\n' or the end of the file eof. • cin.read(char *buffer, int n): Reads n bytes (or until the end of the file) from the stream into the buffer. • cin.ignore(int n): Ignores the next n characters from the input stream. • cin.eof(): Returns a non-zero value if the end of file (eof) is reached. The prototype of cin as defined in the iostream header file is: extern istream cin; The cin object in C++ is an object of class istream. It is associated with the standard C input stream stdin. The cin object is ensured to be initialized during or before the first time an object of type ios_base::Init is constructed. After the cin object is constructed, cin.tie() returns &cout. This means that any formatted input operation on cin forces a call to cout.flush() if any characters are pending for 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
/* Standard Input Stream (cin) in C++ language */ // cin with Member Functions #include <iostream> using namespace std; int main() { char name[20], address[20]; cout << "Name: "; // use cin with getline() cin.getline(name, 20); cout << "Address: "; cin.getline(address, 20); cout << endl << "You entered " << endl; cout << "Name = " << name << endl; cout << "Address = " << address; return 0; }
String Library find() Function in C++
Find content in string. Searches the string for the first occurrence of the sequence specified by its arguments. When pos is specified, the search only includes characters at or after position pos, ignoring any possible occurrences that include characters before pos. Notice that unlike member find_first_of, whenever more than one character is being searched for, it is not enough that just one of these characters match, but the entire sequence must match.
Syntax for String find() Function in C++
#include <string> //string (1) size_t find (const string& str, size_t pos = 0) const noexcept; //c-string (2) size_t find (const char* s, size_t pos = 0) const; //buffer (3) size_t find (const char* s, size_t pos, size_type n) const; //character (4) size_t find (char c, size_t pos = 0) const noexcept;
str
Another string with the subject to search for.
pos
Position of the first character in the string to be considered in the search. If this is greater than the string length, the function never finds matches. Note: The first character is denoted by a value of 0 (not 1): A value of 0 means that the entire string is searched.
s
Pointer to an array of characters. If argument n is specified (3), the sequence to match are the first n characters in the array. Otherwise (2), a null-terminated sequence is expected: the length of the sequence to match is determined by the first occurrence of a null character.
n
Length of sequence of characters to match.
c
Individual character to be searched for. size_t is an unsigned integral type (the same as member type string::size_type). Function returns the position of the first character of the first match. If no matches were found, the function returns string::npos. size_t is an unsigned integral type (the same as member type string::size_type).
Complexity
Unspecified, but generally up to linear in length()-pos times the length of the sequence to match (worst case).
Iterator validity
No changes
Data races
The object is accessed
Exception safety
If s does not point to an array long enough, it causes undefined behavior. Otherwise, the function never throws exceptions (no-throw 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
/* String find is used to find the first occurrence of sub-string in the specified string being called upon. It returns the index of the first occurrence of the substring in the string from given starting position. The default value of starting position is 0. */ // CPP code example to demonstrate working of string find to search a string #include <iostream> #include <string> using namespace std; int main() { string str = "HappyCodings a computer science"; string str1 = "Happy"; // Find first occurrence of "Happy" size_t found = str.find(str1); if (found != string::npos) cout << "First occurrence is " << found << endl; // Find next occurrence of "Happy". Note here we pass // "Happy" as C style string. char arr[] = "Happy"; found = str.find(arr, found+1); if (found != string::npos) cout << "Next occurrence is " << found << endl; return 0; }
While Loop Statement in C++
In while loop, condition is evaluated first and if it returns true then the statements inside while loop execute, this happens repeatedly until the condition returns false. When condition returns false, the control comes out of loop and jumps to the next statement in the program after while loop. The important point to note when using while loop is that we need to use increment or decrement statement inside while loop so that the loop variable gets changed on each iteration, and at some point condition returns false. This way we can end the execution of while loop otherwise the loop would execute indefinitely. A while loop that never stops is said to be the infinite while loop, when we give the condition in such a way so that it never returns false, then the loops becomes infinite and repeats itself indefinitely.
Syntax for While Loop Statement in C++
while (condition) { // body of the loop }
• A while loop evaluates the condition • If the condition evaluates to true, the code inside the while loop is executed. • The condition is evaluated again. • This process continues until the condition is false. • When the condition evaluates to false, the loop terminates. Do not forget to increase the variable used in the condition, otherwise the loop will never end!
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
/* While Loop Statement in C++ language */ // program to find the sum of positive numbers // if the user enters a negative number, the loop ends // the negative number entered is not added to the sum #include <iostream> using namespace std; int main() { int number; int sum = 0; // take input from the user cout << "Enter a number: "; cin >> number; while (number >= 0) { // add all positive numbers sum += number; // take input again if the number is positive cout << "Enter a number: "; cin >> number; } // display the sum cout << "\nThe sum is " << sum << endl; return 0; }
String Library end() Function in C++
Return iterator to end. Returns an iterator pointing to the past-the-end character of the string. The past-the-end character is a theoretical character that would follow the last character in the string. It shall not be dereferenced. Because the ranges used by functions of the standard library do not include the element pointed by their closing iterator, this function is often used in combination with string::begin to specify a range including all the characters in the string. If the object is an empty string, this function returns the same as string::begin.
Syntax for String end() Function in C++
#include <string> iterator end() noexcept; const_iterator end() const noexcept;
This function does not accept any parameter. Function returns an iterator to the past-the-end of the string. If the string object is const-qualified, the function returns a const_iterator. Otherwise, it returns an iterator. Member types iterator and const_iterator are random access iterator types (pointing to a character and to a const character, respectively).
Complexity
Unspecified, but generally constant
Iterator validity
No changes
Data races
The object is accessed (neither the const nor the non-const versions modify it). The iterator returned can be used to access or modify characters. Concurrently accessing or modifying different characters is safe.
Exception safety
No-throw guarantee: this member function never throws exceptions. The copy construction or assignment of the returned iterator is also guaranteed to never throw.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/* returns the iterator pointing to the past-the-last character of the string by string::end function code example. */ #include <iostream> #include <string> using namespace std; int main (){ string str = "Learn C++"; string::iterator it; it = str.end(); it--; cout<<*it<<" "; it--; cout<<*it<<" "; it--; cout<<*it<<" "; 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.
#include <header_file>
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; }
exit() Function in C++
The exit function terminates the program normally. Automatic objects are not destroyed, but static objects are. Then, all functions registered with atexit are called in the opposite order of registration. The code is returned to the operating system. An exit code of 0 or EXIT_SUCCESS means successful completion. If code is EXIT_FAILURE, an indication of program failure is returned to the operating system. Other values of code are implementation-defined.
Syntax for exit() Function in C++
void exit (int status);
status
Status code. If this is 0 or EXIT_SUCCESS, it indicates success. If it is EXIT_FAILURE, it indicates failure. Calls all functions registered with the atexit() function, and destroys C++ objects with static storage duration, all in last-in-first-out (LIFO) order. C++ objects with static storage duration are destroyed in the reverse order of the completion of their constructor. (Automatic objects are not destroyed as a result of calling exit().) Functions registered with atexit() are called in the reverse order of their registration. A function registered with atexit(), before an object obj1 of static storage duration is initialized, will not be called until obj1's destruction has completed. A function registered with atexit(), after an object obj2 of static storage duration is initialized, will be called before obj2's destruction starts. Normal program termination performs the following (in the same order): • Objects associated with the current thread with thread storage duration are destroyed (C++11 only). • Objects with static storage duration are destroyed (C++) and functions registered with atexit are called. • All C streams (open with functions in <cstdio>) are closed (and flushed, if buffered), and all files created with tmpfile are removed. • Control is returned to the host environment. Note that objects with automatic storage are not destroyed by calling exit (C++). If status is zero or EXIT_SUCCESS, a successful termination status is returned to the host environment. If status is EXIT_FAILURE, an unsuccessful termination status is returned to the host environment. Otherwise, the status returned depends on the system and library implementation. Flushes all buffers, and closes all open files. All files opened with tmpfile() are deleted. Returns control to the host environment from the program. exit() returns no values.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* terminate the process normally, performing the regular cleanup for terminating programs by exit() function code example */ #include<iostream> using namespace std; int main() { int i; cout<<"Enter a non-zero value: "; //user input cin>>i; if(i) // checks whether the user input is non-zero or not { cout<<"Valid input.\n"; } else { cout<<"ERROR!"; //the program exists if the value is 0 exit(0); } cout<<"The input was : "<<i; }
String Library begin() Function in C++
Return iterator to beginning. Returns an iterator pointing to the first character of the string. This function gives a reference to the first element. The C++ string::begin function returns the iterator pointing to the first character of the string. Note that, Unlike the string::front function, which returns a direct reference to the first character, it returns the iterator pointing to the same character of the string.
Syntax for String begin() Function in C++
#include <string> iterator begin() noexcept; const_iterator begin() const noexcept;
This function does not return any value. Function returns an iterator to the beginning of the string. If the string object is const-qualified, the function returns a const_iterator. Otherwise, it returns an iterator. Member types iterator and const_iterator are random access iterator types (pointing to a character and to a const character, respectively).
Complexity
Unspecified, but generally constant.
Iterator validity
No changes
Data races
The object is accessed (neither the const nor the non-const versions modify it). The iterator returned can be used to access or modify characters. Concurrently accessing or modifying different characters is safe.
Exception safety
No-throw guarantee: this member function never throws exceptions. The copy construction or assignment of the returned iterator is also guaranteed to never throw.
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
/* returns an iterator pointing to the first character of the string by string::begin function code example. */ #include <iostream> #include <string> using namespace std; int main (){ string str = "Learn C++"; string::iterator it; std::string str2 ("Test string"); for ( std::string::iterator it=str2.begin(); it!=str2.end(); ++it) std::cout << *it; std::cout << '\n'; it = str.begin(); cout<<*it<<" "; it++; cout<<*it<<" "; it++; cout<<*it<<" "; 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; }
String Library size() Function in C++
Return length of string. Returns the length of the string, in terms of bytes. This is the number of actual bytes that conform the contents of the string, which is not necessarily equal to its storage capacity. Note that string objects handle bytes without knowledge of the encoding that may eventually be used to encode the characters it contains. Therefore, the value returned may not correspond to the actual number of encoded characters in sequences of multi-byte or variable-length characters (such as UTF-8). Both string::size and string::length are synonyms and return the same value.
Syntax for String size() Function in C++
#include <string> size_t size() const noexcept;
This function does not accept any parameter. Function returns the number of bytes in the string. size_t is an unsigned integral type (the same as member type string::size_type).
Complexity
Constant
Iterator validity
No changes
Data races
The object is accessed.
Exception safety
No-throw guarantee: this member 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 23 24 25 26
/* return the length of the string in terms of bytes by string size() function code example. */ #include <iostream> #include <string> using namespace std; int main() { string s1("Quick! from book www.com."); string s2("Lord test "); string s3("Don't test"); s1.erase(0, 7); s1.replace(9, 5, s2); s1.replace(0, 1, "s"); s1.insert(0, s3); s1.erase(s1.size()-1, 1); s1.append(3, '!'); int x = s1.find(' '); //find a space while( x < s1.size() ) //loop while spaces remain { s1.replace(x, 1, "/"); //replace with slash x = s1.find(' '); //find next space } cout << "s1: " << s1 << endl; return 0; }


We have two classes XYZ and ABC. The XYZ class has two "private data members" ch and num, this class declares 'ABC' as Friend Class. This means that 'ABC' can access the private
All the "variables" must be declared before to use or initial statements of the block or main or function or global. Variables should specify with data type. And it binds a "data type" and