# C++ Programming Code Examples

## C++ > Sorting Searching Code Examples

### Program to Find ith Largest Number from a Given List Using Order-Statistic Algorithm

/* Program to Find ith Largest Number from a Given List Using Order-Statistic Algorithm - Implements Order-Statistic tree. - It is an improvement in BST by adding two more key functions- rank() and select(). - The time complexity of Order-statistic tree generation is O(n+n*log(n)). - Once the tree is constructed, this algorithm takes O(log(n)) to find Kth largest number. - Construct Order-Statistic tree for the given unsorted data array. - Using the select function get the kth largest number from the given data set. - Print the result. - Exit. */ #include<iostream> using namespace std; static int count = 0; // A structure representing a node of a tree. struct node { int data; int rank; node *left; node *right; }; // A function creating new node of tree and assigning the data. node* CreateNode(int data) { node *newnode = new node; newnode->data = data; newnode->rank = 0; newnode->left = NULL; newnode->right = NULL; return newnode; } // A function to create binary search tree. node* Insert(node* root, int data) { // Create node using data from argument list. node *temp = CreateNode(data); node *t = new node; t = root; // If root is null, assign it to the node created. if(root == NULL) root = temp; else { // Find the position for the new node to be inserted. while(t != NULL) { if(t->data < data ) { if(t->right == NULL) { // If current node is NULL then insert the node. t->right = temp; break; } // Shift pointer to the left. t = t->right; } else if(t->data > data) { if(t->left == NULL) { // If current node is NULL then insert the node. t->left = temp; break; } // Shift pointer to the left. t = t->left; } } } return root; } // A function to assign a rank to each node of the tree. void AssignRank(node *root) { if(root->left != NULL) AssignRank(root->left); root->rank = count; count++; if(root->right != NULL) AssignRank(root->right); } // A function to search Kth smallest element from the data stored in the tree. int Select(node* root, int k) { // Search for the entered rank and shift the pointer accordingly, if rank not matched. if(root->rank == k) return root->data; else if(root->rank > k) return Select(root->left, k); else return Select(root->right, k); } // A function to take an inorder traversal of the tree and print the tree data of each node. void print(node *root) { if(root->left != NULL) print(root->left); cout<<"\n data: "<<root->data<<" rank: "<<root->rank; if(root->right != NULL) print(root->right); } int main() { char ch; int n, i, k, a[20]={40, 54, 96, 1, 9, 66, 78, 73, 36, 74, 44, 23, 35, 96, 38, 41, 49, 88, 27, 97}; node *root = new node; root = NULL; // Construct the BST. for(i = 0; i < 20; i++) root = Insert(root, a[i]); cout<<"Enter the k value: "; cin>>k; // Assign rank to each of the nodes of the Binary Search tree. AssignRank(root); // Inorder traversal of the tree and displaying the data and the rank corresponding to that data. cout<<"\nRank associated to each node:-"; print(root); // Print the result. cout<<"\n\nThe kth Largest element is: "<<Select(root, 20-k); return 0; }

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.

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, 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.

In C++, classes and structs are blueprints that are used to create the instance of a class. Structs are used for lightweight objects such as Rectangle, color, Point, etc. Unlike class, structs in C++ are value type than reference type. It is useful if you have data that is not intended to be modified after creation of struct. C++ Structure is a collection of different data types. It is similar to the class that holds different types of data. A structure is declared by preceding the struct keyword followed by the identifier(structure name). Inside the curly braces, we can declare the member variables of different types.

Allocate storage space. Default allocation functions (single-object form). A new operator is used to create the object while a delete operator is used to delete the object. When the object is created by using the new operator, then the object will exist until we explicitly use the delete operator to delete the object. Therefore, we can say that the lifetime of the object is not related to the block structure of the program.

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.

The if...else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities. The if...else ladder allows you to check between multiple test expressions and execute different 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.

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.

Static is a keyword in C++ used to give special characteristics to an element. Static elements are allocated storage only once in a program lifetime in static storage area. And they have a scope till the program lifetime. In C++, static is a keyword or modifier that belongs to the type not instance. So instance is not required to access the static members. In C++, static can be field, method, constructor, class, properties, operator and event. Advantage of C++ static keyword: Memory efficient. Now we don't need to create instance for accessing the static members, so it saves memory. Moreover, it belongs to the type, so it will not get memory each time when instance is created.

Compute natural logarithm. Returns the natural logarithm of x. The natural logarithm is the base-e logarithm: the inverse of the natural exponential function (exp). For common (base-10) logarithms, see log10. The C/C++ library function double log(double x) returns the natural logarithm (base-e logarithm) of x. Function returns natural logarithm of x. If x is negative, it causes a domain error. If x is zero, it may cause a pole error (depending on the library implementation).

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. 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.

An array is defined as the collection of similar type of data items stored at contiguous memory locations. Arrays are the derived data type in C++ programming language which can store the primitive type of data such as int, char, double, float, etc. It also has the capability to store the collection of derived data types, such as pointers, structure, etc. The array is the simplest data structure where each data element can be randomly accessed by using its index number. C++ array is beneficial if you have to store similar elements. For example, if we want to store the marks of a student in 6 subjects, then we don't need to define different variables for the marks in the different subject. Instead of that, we can define an array which can store the marks in each subject at the contiguous memory locations.

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.

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.

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.

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. 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.

#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.

The pointer in C++ language is a variable, it is also known as locator or indicator that points to an address of a value. In C++, a pointer refers to a variable that holds the address of another variable. Like regular variables, pointers have a data type. For example, a pointer of type integer can hold the address of a variable of type integer. A pointer of character type can hold the address of a variable of character type. You should see a pointer as a symbolic representation of a memory address. With pointers, programs can simulate call-by-reference. They can also create and manipulate dynamic data structures. In C++, a pointer variable refers to a variable pointing to a specific address in a memory pointed by another variable.

To calculate "grade of a student" on the basis of his total marks in C++ Programming, ask to the user to enter marks obtained in some subjects (5 subjects here). To calculate grade

2 const variables row & col are used to define size. If we do not make both const then error found because without "const reserve word" they are behaving as variable. Before placing