Happy Codings - Programming Code Examples

C++ Programming Code Examples

C++ > Code Snippets Code Examples

A four-function postfix calculator.

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
/* A four-function postfix calculator. */ #include <iostream> #include <stack> #include <string> #include <cmath> using namespace std; int main() { stack<double> stackObject; double a, b; string s; do { cout << ": "; cin >> s; switch( s[ 0 ]) { case 'q': // quit the calculator break; case '.': // show top-of-stack cout << stackObject.top() << endl; break; case '+': // add if(stackObject.size() < 2) { cout << "Operand Missing\n"; break; } a = stackObject.top(); stackObject.pop(); b = stackObject.top(); stackObject.pop(); cout << a + b << endl; stackObject.push(a + b); break; case '-': // subtract // see if user entering a negative number if(s.size() != 1) { // push value onto the stack stackObject.push(atof(s.c_str())); break; } // otherwise, is a subtraction if(stackObject.size() < 2) { cout << "Operand Missing\n"; break; } a = stackObject.top(); stackObject.pop(); b = stackObject.top(); stackObject.pop(); cout << b - a << endl; stackObject.push(b - a); break; case '*': // multiply if(stackObject.size() < 2) { cout << "Operand Missing\n"; break; } a = stackObject.top(); stackObject.pop(); b = stackObject.top(); stackObject.pop(); cout << a*b << endl; stackObject.push(a*b); break; case '/': // divide if(stackObject.size() < 2) { cout << "Operand Missing\n"; break; } a = stackObject.top(); stackObject.pop(); b = stackObject.top(); stackObject.pop(); cout << b/a << endl; stackObject.push(b/a); break; default: // push value onto the stack stackObject.push(atof(s.c_str())); break; } } while(s != "q"); return 0; }
Stack Library size() Function in C++
Return size. Returns the number of elements in the stack. stack::size() function is an inbuilt function in C++ STL, which is defined in <stack>header file. size() is used to check the associated container's size and return the result in an integer value, which is the number of elements in the container. If the container is empty the size() returns 0 This member function effectively calls member size of the underlying container object.
Syntax for Stack size() Function in C++
#include <stack> size_type size() const;
No parameter is required. Function returns the number of elements in the underlying container. Member type size_type is an unsigned integral type.
Complexity
Constant (calling size on the underlying container).
Data races
The container is accessed
Exception safety
Provides the same level of guarantees as the operation performed on the container (no-throw guarantee for standard container types).
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
/* C++ Stack size() function returns the number of stack elements. The number of stack elements is referred to the size of the stack. The size of the stack element is very important information as based on it we can deduce many other things such as the space required, etc. */ /* Find out the total number of elements in the stack by stack::size function code example. */ #include <iostream> #include <stack> using namespace std; int main (){ stack<int> MyStack; MyStack.push(10); MyStack.push(20); MyStack.push(30); MyStack.push(40); MyStack.push(50); cout<<"Stack size is: "<<MyStack.size()<<"\n"; cout<<"Three elements are added in the Stack.\n"; MyStack.push(60); MyStack.push(70); MyStack.push(80); cout<<"Now, Stack size is: "<<MyStack.size()<<"\n"; 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; }
Stack Library top() Function in C++
Access next element. Returns a reference to the top element in the stack. stack::top() function is an inbuilt function in C++ STL, which is defined in <stack> header file. top() is used to access the element at the top of the stack container. In a stack, the top element is the element that is inserted at the last or most recently inserted element. Since stacks are last-in first-out containers, the top element is the last element inserted into the stack. This member function effectively calls member back of the underlying container object.
Syntax for Stack top() Function in C++
#include <stack> reference top(); const_reference top() const;
No parameter is required. Function returns a reference to the top element in the stack.
Complexity
Constant (calling back on the underlying container).
Data races
The container is accessed (neither the const nor the non-const versions modify the container). The reference returned can be used to access or modify the top element.
Exception safety
Provides the same level of guarantees as the operation performed on the container (no-throw guarantee for standard non-empty containers).
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
/* C++ Stack top() function returns the value of the top element in the stack. The top element is the one which was recently added on the stack. The last added element is the top element. Of all the elements that are present in a stack the top element stands out and is more significant as all the major operations on the stack are performed at the top element. Be it push, pop or anything all the operations are done at the top most position. */ /* get the reference of the element at the top of the stack by stack top() function code example. */ #include <iostream> #include <stack> using namespace std; int main (){ stack<int> MyStack; MyStack.push(10); MyStack.push(20); MyStack.push(30); MyStack.push(40); MyStack.push(50); cout<<"The top element of MyStack is: "; cout<<MyStack.top()<<endl; cout<<"Delete the top element of MyStack.\n"; MyStack.pop(); cout<<"Now, The top element of MyStack is: "; cout<<MyStack.top(); return 0; }
Stack Library pop() Function in C++
Remove top element. Removes the element on top of the stack, effectively reducing its size by one. The C++ function std::stack::pop() removes top element from the stack and reduces size of stack by one. This function calls destructor on removed element. The element removed is the latest element inserted into the stack, whose value can be retrieved by calling member stack::top. This calls the removed element's destructor. This member function effectively calls the member function pop_back of the underlying container object.
Syntax for Stack pop() Function in C++
#include <stack> void pop();
The function takes no parameter and is used only for the deletion of the top element. Also since the stack follows LIFO principle we do not need to specify which element is to be deleted as it is by default understood that the top most element will be removed first. The function is used only for the removal of elements from the stack and has no return value. Hence we can say that the return type of the function is void.
Complexity
Constant (calling pop_back on the underlying container).
Data races
The container and up to all its contained elements are modified.
Exception safety
Provides the same level of guarantees as the operation performed on the underlying container object.
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
/* pop() function is used to remove or 'pop' an element from the top of the stack(newest or the topmost element in the stack). This is an inbuilt function from C++ Standard Template Library(STL). This function belongs to the <stack> header file. The element is removed from the stack container and the size of the stack is decreased by 1. */ /* removing the topmost element of the stack by Stack pop() function code example. */ #include <iostream> #include <stack> using namespace std; int main (){ stack<int> MyStack; MyStack.push(10); MyStack.push(20); MyStack.push(30); MyStack.push(40); MyStack.push(50); cout<<"The top element of the stack is: "<<MyStack.top(); //deletes top element of the stack MyStack.pop(); cout<<"\nNow, the top element of the stack is: "<<MyStack.top(); //deletes next top element of the stack MyStack.pop(); cout<<"\nNow, the top element of the stack is: "<<MyStack.top(); return 0; }
atof() Function in C++
Convert string to double. Parses the C string str, interpreting its content as a floating point number and returns its value as a double. The function first discards as many whitespace characters (as in isspace) as necessary until the first non-whitespace character is found. Then, starting from this character, takes as many characters as possible that are valid following a syntax resembling that of floating point literals (see below), and interprets them as a numerical value. The rest of the string after the last valid character is ignored and has no effect on the behavior of this function.
Syntax for atof() Function in C++
#include <cstdlib> double atof (const char* str);
str
C-string beginning with the representation of a floating-point number. A valid floating point number for atof using the "C" locale is formed by an optional sign character (+ or -), followed by one of: • A sequence of digits, optionally containing a decimal-point character (.), optionally followed by an exponent part (an e or E character followed by an optional sign and a sequence of digits). • A 0x or 0X prefix, then a sequence of hexadecimal digits (as in isxdigit) optionally containing a period which separates the whole and fractional number parts. Optionally followed by a power of 2 exponent (a p or P character followed by an optional sign and a sequence of hexadecimal digits). • INF or INFINITY (ignoring case). • NAN or NANsequence (ignoring case), where sequence is a sequence of characters, where each character is either an alphanumeric character (as in isalnum) or the underscore character (_). If the first sequence of non-whitespace characters in str does not form a valid floating-point number as just defined, or if no such sequence exists because either str is empty or contains only whitespace characters, no conversion is performed and the function returns 0.0. On success, the function returns the converted floating point number as a double value. If no valid conversion could be performed, the function returns zero (0.0). If the converted value would be out of the range of representable values by a double, it causes undefined behavior. See strtod for a more robust cross-platform alternative when this is a possibility.
Data races
The array pointed by str is accessed.
Exceptions
No-throw guarantee: this function never throws exceptions. If str does not point to a valid C-string, or if the converted value would be out of the range of values representable by a double, it 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 31 32 33 34 35 36
/* atof() function converts a C-type string, passed as an argument to function call, to double. It parses the C-string str interpreting its content as a floating point number, which is returned as a value of type double. The function discards the whitespace characters present at the beginning of the string until a non-whitespace character is found. If the sequence of non-whitespace characters in C-string str is not a valid floating point number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed and 0.0 is returned. */ /* convert a string to a floating-point value of datatype double by atof() function code example. */ #include <bits/stdc++.h> using namespace std; int main() { // char array char pi[] = "3.1415926535"; // Calling function to convert to a double double pi_val = atof(pi); // prints the double value cout << "Value of pi = " << pi_val << ""; // char array char acc_g[] = "9.8"; // Calling function to convert to a double double acc_g_val = atof(acc_g); // prints the double value cout << "Value of acceleration due to gravity = " << acc_g_val << ""; 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; }
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; }
Stack push() Function in C++
Insert element. Inserts a new element at the top of the stack, above its current top element. The content of this new element is initialized to a copy of val. This member function effectively calls the member function push_back of the underlying container object. C++ Stack push () function is used for adding new elements at the top of the stack. If we have an array of type stack and by using the push() function we can insert new elements in the stack. The elements are inserted at the top of the stack. The element which is inserted most initially is deleted at the end and vice versa as stacks follow LIFO principle.
Syntax for Stack push() Function in C++
void push (const value_type& val); void push (value_type&& val);
val
Value to which the inserted element is initialized. Member type value_type is the type of the elements in the container (defined as an alias of the first class template parameter, T). The function only inserts element and does not return any value. The return type of the function can be thought as void.
Complexity
One call to push_back on the underlying container.
Data races
The container and up to all its contained elements are modified.
Exception safety
Provides the same level of guarantees as the operation performed on the underlying container object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* demonstrate the use of the push() function of the stack by insertion of simple integer values */ #include <iostream> #include <stack> int main() { std::stack<int> newstack; newstack.push(11); newstack.push(22); newstack.push(33); newstack.push(44); std::cout << "Popping out elements?"; newstack.pop(); newstack.pop(); while (!newstack.empty () ) { std::cout << " " << newstack.top(); newstack.pop(); } std:: cout<<'\n'; return 0; }
Stack in C++ Language
LIFO stack. Stacks are a type of container adaptor, specifically designed to operate in a LIFO context (last-in first-out), where elements are inserted and extracted only from one end of the container. stacks are implemented as container adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access its elements. Elements are pushed/popped from the "back" of the specific container, which is known as the top of the stack.
Syntax for Stack in C++
template <class T, class Container = deque<T> > class stack;
T
Type of the elements. Aliased as member type stack::value_type.
Container
Type of the internal underlying container object where the elements are stored. Its value_type shall be T. Aliased as member type stack::container_type.
Member types
value_type The first template parameter (T) Type of the elements container_type The second template parameter (Container) Type of the underlying container reference container_type::reference usually, value_type& const_reference container_type::const_reference usually, const value_type& size_type an unsigned integral type usually, the same as size_t
Member functions
(constructor) Construct stack (public member function ) stack::emplace: Constructs and inserts new element at the top of stack. stack::empty: Tests whether stack is empty or not. stack::operator= copy version: Assigns new contents to the stack by replacing old ones. stack::operator= move version: Assigns new contents to the stack by replacing old ones. stack::pop: Removes top element from the stack. stack::push copy version: Inserts new element at the top of the stack. stack::push move version: Inserts new element at the top of the stack. stack::size: Returns the total number of elements present in the stack. stack::swap: Exchanges the contents of stack with contents of another stack. stack::top: Returns a reference to the topmost element of the stack.
Non-member function overloads
relational operators Relational operators for stack (function ) swap (stack) Exchange contents of stacks (public member function ) operator==: Tests whether two stacks are equal or not. operator!=: Tests whether two stacks are equal or not. operator<: Tests whether first stack is less than other or not. operator<=: Tests whether first stack is less than or equal to other or not. operator>: Tests whether first stack is greater than other or not. operator>=: Tests whether first stack is greater than or equal to other or not.
Non-member class specializations
uses_allocator<stack> Uses allocator for stack (class template ) The standard container classes vector, deque and list fulfill these requirements. By default, if no container class is specified for a particular stack class instantiation, the standard container deque is used. Stack is a data structure designed to operate in LIFO (Last in First out) context. In stack elements are inserted as well as get removed from only one end. Stack class is container adapter. Container is an objects that hold data of same type. Stack can be created from different sequence containers. If container is not provided it uses default deque container. Container adapters do not support iterators therefore we cannot use them for data manipulation. However they support push() and pop() member functions for data insertion and removal respectively.
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
/* Stack in C++ language */ #include <iostream> #include <stack> using namespace std; void newstack(stack <int> ss) { stack <int> sg = ss; while (!sg.empty()) { cout << '\t' << sg.top(); sg.pop(); } cout << '\n'; } int main () { stack <int> newst; newst.push(55); newst.push(44); newst.push(33); newst.push(22); newst.push(11); cout << "The stack newst is : "; newstack(newst); cout << "\n newst.size() : " << newst.size(); cout << "\n newst.top() : " << newst.top(); cout << "\n newst.pop() : "; newst.pop(); newstack(newst); 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; }
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; }
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; }
#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; }
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; }
String Library c_str() Function in C++
Get C string equivalent. Returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object. The basic_string::c_str() is a builtin function in C++ which returns a pointer to an array that contains a null-terminated sequence of characters representing the current value of the basic_string object. This array includes the same sequence of characters that make up the value of the basic_string object plus an additional terminating null-character at the end. This array includes the same sequence of characters that make up the value of the string object plus an additional terminating null-character ('\0') at the end.
Syntax for String c_str() Function in C++
#include <string> const char* c_str() const noexcept;
This function does not accept any parameter. Function returns a pointer to the c-string representation of the string object's value. The pointer returned points to the internal array currently used by the string object to store the characters that conform its value. Both string::data and string::c_str are synonyms and return the same value. The pointer returned may be invalidated by further calls to other member functions that modify the object.
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
/* c_str() function returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object. */ /* Get C string equivalent by c_str() function code example */ #include <bits/stdc++.h> #include <string> using namespace std; int main() { // declare a example string string s1 = "HappyCodings"; // check if the size of the string is same as the // size of character pointer given by c_str if (s1.size() == strlen(s1.c_str())) { cout << "s1.size is equal to strlen(s1.c_str()) " << endl; } else { cout << "s1.size is not equal to strlen(s1.c_str())" << endl; } // print the string printf("%s \n", s1.c_str()); }
Functions in C++
The function in C++ language is also known as procedure or subroutine in other programming languages. To perform any task, we can create function. A function can be called many times. It provides modularity and code reusability. Functions are used to provide modularity to a program. Creating an application using function makes it easier to understand, edit, check...
Defining a Function in C++
return-type function-name(parameter1, parameter2, ...) { // function-body }
return type
suggests what the function will return. It can be int, char, some pointer or even a class object. There can be functions which does not return anything, they are mentioned with void.
name
Function name is the name of the function, using the function name it is called.
parameters
Parameters are variables to hold values of arguments passed while function is called. A function may or may not contain parameter list.
body
Function body is the part where the code statements are written. Function declaration, is done to tell the compiler about the existence of the function. Function's return type, its name & parameter list is mentioned. Function body is written in its definition. Functions are called by their names. If the function is without argument, it can be called directly using its name. But for functions with arguments, we have two ways to call them: • Call by Value: In this calling technique we pass the values of arguments which are stored or copied into the formal parameters of functions. Hence, the original values are unchanged only the parameters inside function changes. • Call by Reference: In this we pass the address of the variable as arguments. In this case the formal parameter can be taken as a reference or a pointer, in both the case they will change the values of the original variable.
Advantage of Functions
• Code Reusability: By creating functions in C++, you can call it many times. So we don't need to write the same code again and again. • Code optimization: It makes the code optimized, we don't need to write much code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* function with parameters in C++ language */ // program to print a text #include <iostream> using namespace std; // display a number void displayNum(int n1, float n2) { cout << "The int number is " << n1; cout << "The double number is " << n2; } int main() { int num1 = 5; double num2 = 5.5; // calling the function displayNum(num1, num2); return 0; }
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; }
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; }


Finding the smallest item in the tree. Not the most efficient implementation ('two passes'), but has correct "amortized behavior". A good alternative is to first call Find with parameter