C++ Programming Code Examples

C++ > Data Structures and Algorithm Analysis in C++ Code Examples

Test program for determinstic skip lists

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
/* Test program for determinstic skip lists */ #include <iostream.h> #include "DSL.h" // Test program int main( ) { const int ITEM_NOT_FOUND = 99999999; DSL<int> t( ITEM_NOT_FOUND ); int NUMS = 3900; const int GAP = 37; int i; cout << "Checking... (no more output means success)" << endl; for( i = GAP; i != 0; i = ( i + GAP ) % NUMS ) t.insert( i ); if( NUMS < 40 ) t.printList( ); if( t.findMin( ) != 1 || t.findMax( ) != NUMS - 1 ) cout << "FindMin or FindMax error!" << endl; for( i = 1; i < NUMS; i++ ) if( t.find( i ) != i ) cout << "Find error1!" << endl; if( t.find( 0 ) != ITEM_NOT_FOUND ) cout << "ITEM_NOT_FOUND failed!" << endl; return 0; }
Algorithm Library min() Function in C++
Return the smallest. Returns the smallest of a and b. If both are equivalent, a is returned. min() function is a library function of algorithm header, it is used to find the smallest value from given two values, it accepts two values and returns the smallest value and if both the values are the same it returns the first value. The versions for initializer lists (3) return the smallest of all the elements in the list. Returning the first of them if these are more than one. The function uses operator< (or comp, if provided) to compare the values.
Syntax for Algorithm min() Function in C++
#include <algorithm> //default (1) template <class T> const T& min (const T& a, const T& b); //custom (2) template <class T, class Compare> const T& min (const T& a, const T& b, Compare comp); //initializer list (3) template <class T> T min (initializer_list<T> il); template <class T, class Compare> T min (initializer_list<T> il, Compare comp);
a, b
Values to compare
comp
Binary function that accepts two values of type T as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered less than the second. The function shall not modify any of its arguments. This can either be a function pointer or a function object.
il
An initializer_list object. These objects are automatically constructed from initializer list declarators. T shall support being compared with operator<. For (3), T shall be copy constructible. Function returns the lesser of the values passed as arguments.
Complexity
Linear in one less than the number of elements compared (constant for (1) and (2)).
Exceptions
Throws if any comparison throws. Note that invalid arguments cause undefined behavior.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
/* std::min is defined in the header file <algorithm> and is used to find out the smallest of the number passed to it. It returns the first of them, if there are more than one. */ /* accept two values and return the smaller one by min() function code example. */ #include <iostream> #include <algorithm> using namespace std; // Defining the binary function bool comp(int a, int b) { return (a < b); } int main() { int a = 5; int b = 7; cout << std::min(a, b, comp) << "\n"; // Returns the first one if both the numbers // are same cout << std::min(7, 7, comp); return 0; }
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; }
Relational Operators in C++
A relational operator is used to check the relationship between two operands. C++ Relational Operators are used to relate or compare given operands. Relational operations are like checking if two operands are equal or not equal, greater or lesser, etc. Relational Operators are also called Comparison Operators. • == Is Equal To 4 == 9 gives us false • != Not Equal To 4 != 9 gives us true • > Greater Than 4 > 9 gives us false • < Less Than 4 < 9 gives us true • >= Greater Than or Equal To 4 >= 9 give us false • <= Less Than or Equal To 4 <= 9 gives us true
==
Equal To Operator (==) is used to compare both operands and returns 1 if both are equal or the same, and 0 represents the operands that are not equal. The equal to == operator returns true - if both the operands are equal or the same false - if the operands are unequal int x = 10; int y = 15; int z = 10; x == y // false x == z // true The relational operator == is not the same as the assignment operator =. The assignment operator = assigns a value to a variable, constant, array, or vector. It does not compare two operands.
!=
Not Equal To Operator (!=) is the opposite of the Equal To Operator and is represented as the (!=) operator. The Not Equal To Operator compares two operands and returns 1 if both operands are not the same; otherwise, it returns 0. The not equal to != operator returns true - if both operands are unequal false - if both operands are equal. int x = 10; int y = 15; int z = 10; x != y // true x != z // false
>
Greater than Operator (>) checks the value of the left operand is greater than the right operand, and if the statement is true, the operator is said to be the Greater Than Operator. The greater than > operator returns true - if the left operand is greater than the right false - if the left operand is less than the right int x = 10; int y = 15; x > y // false y > x // true
<
Less than Operator (<) is used to check whether the value of the left operand is less than the right operand, and if the statement is true, the operator is known as the Less than Operator. The less than operator < returns true - if the left operand is less than the right false - if the left operand is greater than right int x = 10; int y = 15; x < y // true y < x // false
>=
Greater than Equal To Operator (>=) checks whether the left operand's value is greater than or equal to the right operand. If the statement is true, the operator is said to be the Greater than Equal to Operator. The greater than or equal to >= operator returns true - if the left operand is either greater than or equal to the right false - if the left operand is less than the right int x = 10; int y = 15; int z = 10; x >= y // false y >= x // true z >= x // true
<=
Less than Equal To Operator (<=) checks whether the value of the left operand is less than or equal to the right operand, and if the statement is true, the operator is said to be the Less than Equal To Operator. The less than or equal to operator <= returns true - if the left operand is either less than or equal to the right false - if the left operand is greater than right int x = 10; int y = 15; x > y // false y > x // true
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
/* Relational Operators are used for the comparison of the values of two operands. For example, checking if one operand is equal to the other operand or not, an operand is greater than the other operand or not, etc. Some of the relational operators are (==, >= , <= ). */ #include <iostream> using namespace std; main() { int a = 21; int b = 10; int c ; if( a == b ) { cout << "Line 1 - a is equal to b" << endl ; } else { cout << "Line 1 - a is not equal to b" << endl ; } if( a < b ) { cout << "Line 2 - a is less than b" << endl ; } else { cout << "Line 2 - a is not less than b" << endl ; } if( a > b ) { cout << "Line 3 - a is greater than b" << endl ; } else { cout << "Line 3 - a is not greater than b" << endl ; } /* Let's change the values of a and b */ a = 5; b = 20; if( a <= b ) { cout << "Line 4 - a is either less than \ or equal to b" << endl ; } if( b >= a ) { cout << "Line 5 - b is either greater than \ or equal to b" << 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; }
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; }
Arithmetic Operators in C++
Arithmetic Operator is used to performing mathematical operations such as addition, subtraction, multiplication, division, modulus, etc., on the given operands. For example: 6 + 3 = 9, 5 - 3 = 2, 3 * 4 = 12, etc. are the examples of arithmetic operators. Let's discuss the different types of Arithmetic Operators in the C programming.
+
Plus Operator is a simple Plus (+) Operator used to add two given operands. We can use Plus Operator with different data types such as integer, float, long, double, enumerated and string type data to add the given operand.
-
The minus operator is denoted by the minus (-) symbol. It is used to return the subtraction of the first number from the second number. The data type of the given number can be different types, such as int, float, double, long double, etc., in the programing language.
*
The multiplication operator is represented as an asterisk (*) symbol, and it is used to return the product of n1 and n2 numbers. The data type of the given number can be different types such as int, float, and double in the C programing language.
/
The division operator is an arithmetic operator that divides the first (n1) by the second (n2) number. Using division operator (/), we can divide the int, float, double and long data types variables.
%
The modulus operator is represented by the percentage sign (%), and it is used to return the remainder by dividing the first number by the second number.
++
Increment Operator is the type of Arithmetic operator, which is denoted by double plus (++) operator. It is used to increase the integer value by 1.
--
Decrement Operator is denoted by the double minus (--) symbol, which decreases the operand value by 1.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
/* Perhaps you have warm memories of doing arithmetic drills in grade school. You can give that same pleasure to your computer. C++ uses operators to do arithmetic. It provides operators for five basic arithmetic calculations: addition, subtraction, multiplication, division, and taking the modulus. Each of these operators uses two values (called operands) to calculate a final answer. Together, the operator and its operands constitute an expression. */ #include <iostream> using namespace std; int main() { int a, b; a = 7; b = 2; // printing the sum of a and b cout << "a + b = " << (a + b) << endl; // printing the difference of a and b cout << "a - b = " << (a - b) << endl; // printing the product of a and b cout << "a * b = " << (a * b) << endl; // printing the division of a by b cout << "a / b = " << (a / b) << endl; // printing the modulo of a by b cout << "a % b = " << (a % b) << endl; return 0; }
Return Statement in C++
A return statement ends the processing of the current function and returns control to the caller of the function. A value-returning function should include a return statement, containing an expression. If an expression is not given on a return statement in a function declared with a non-void return type, the compiler issues an error message. If the data type of the expression is different from the function return type, conversion of the return value takes place as if the value of the expression were assigned to an object with the same function return type.
Syntax for Return Statement in C++
return[expression];
For a function of return type void, a return statement is not strictly necessary. If the end of such a function is reached without encountering a return statement, control is passed to the caller as if a return statement without an expression were encountered. In other words, an implicit return takes place upon completion of the final statement, and control automatically returns to the calling function. If a return statement is used, it must not contain an expression. The following are examples of return statements:
return; /* Returns no value */ return result; /* Returns the value of result */ return 1; /* Returns the value 1 */ return (x * x); /* Returns the value of x * x */
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
/* illustrate Methods returning a value using return statement in C++ code example */ #include <iostream> using namespace std; // non-void return type // function to calculate sum int SUM(int a, int b) { int s1 = a + b; // method using the return // statement to return a value return s1; } // Driver method int main() { int num1 = 10; int num2 = 10; int sum_of = SUM(num1, num2); cout << "The sum is " << sum_of; 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; }
Logical Operators in C++
Logical Operators are used to compare and connect two or more expressions or variables, such that the value of the expression is completely dependent on the original expression or value or variable. We use logical operators to check whether an expression is true or false. If the expression is true, it returns 1 whereas if the expression is false, it returns 0. Assume variable A holds 1 and variable B holds 0:
&&
Called Logical AND operator. If both the operands are non-zero, then condition becomes true. (A && B) is false. The logical AND operator && returns true - if and only if all the operands are true. false - if one or more operands are false.
||
Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true. (A || B) is true. The logical OR operator || returns true - if one or more of the operands are true. false - if and only if all the operands are false.
!
Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true, then Logical NOT operator will make false. !(A && B) is true. The logical NOT operator ! is a unary operator i.e. it takes only one operand. It returns true when the operand is false, and false when the operand is true.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
/* The operator ! is the C++ operator for the Boolean operation NOT. It has only one operand, to its right, and inverts it, producing false if its operand is true, and true if its operand is false. Basically, it returns the opposite Boolean value of evaluating its operand. The logical operators && and || are used when evaluating two expressions to obtain a single relational result. The operator && corresponds to the Boolean logical operation AND, which yields true if both its operands are true, and false otherwise. */ #include <iostream> using namespace std; main() { int a = 5; int b = 20; int c ; if(a && b) { cout << "Line 1 - Condition is true"<< endl ; } if(a || b) { cout << "Line 2 - Condition is true"<< endl ; } /* Let's change the values of a and b */ a = 0; b = 10; if(a && b) { cout << "Line 3 - Condition is true"<< endl ; } else { cout << "Line 4 - Condition is not true"<< endl ; } if(!(a && b)) { cout << "Line 5 - Condition is true"<< endl ; } return 0; }
#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.