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++ > Algorithms Code Examples

Binary Search Tree Program

/* Binary Search Tree Program */ #include <iostream> #include <cstdlib> using namespace std; class BinarySearchTree { private: struct tree_node { tree_node* left; tree_node* right; int data; }; tree_node* root; public: BinarySearchTree() { root = NULL; } bool isEmpty() const { return root==NULL; } void print_inorder(); void inorder(tree_node*); void print_preorder(); void preorder(tree_node*); void print_postorder(); void postorder(tree_node*); void insert(int); void remove(int); }; // Smaller elements go left // larger elements go right void BinarySearchTree::insert(int d) { tree_node* t = new tree_node; tree_node* parent; t->data = d; t->left = NULL; t->right = NULL; parent = NULL; // is this a new tree? if(isEmpty()) root = t; else { //Note: ALL insertions are as leaf nodes tree_node* curr; curr = root; // Find the Node's parent while(curr) { parent = curr; if(t->data > curr->data) curr = curr->right; else curr = curr->left; } if(t->data < parent->data) parent->left = t; else parent->right = t; } } void BinarySearchTree::remove(int d) { //Locate the element bool found = false; if(isEmpty()) { cout<<" This Tree is empty! "<<endl; return; } tree_node* curr; tree_node* parent; curr = root; while(curr != NULL) { if(curr->data == d) { found = true; break; } else { parent = curr; if(d>curr->data) curr = curr->right; else curr = curr->left; } } if(!found) { cout<<" Data not found! "<<endl; return; } // 3 cases : // 1. We're removing a leaf node // 2. We're removing a node with a single child // 3. we're removing a node with 2 children // Node with single child if((curr->left == NULL && curr->right != NULL)|| (curr->left != NULL && curr->right == NULL)) { if(curr->left == NULL && curr->right != NULL) { if(parent->left == curr) { parent->left = curr->right; delete curr; } else { parent->right = curr->right; delete curr; } } else // left child present, no right child { if(parent->left == curr) { parent->left = curr->left; delete curr; } else { parent->right = curr->left; delete curr; } } return; } //We're looking at a leaf node if( curr->left == NULL && curr->right == NULL) { if(parent->left == curr) parent->left = NULL; else parent->right = NULL; delete curr; return; } //Node with 2 children // replace node with smallest value in right subtree if (curr->left != NULL && curr->right != NULL) { tree_node* chkr; chkr = curr->right; if((chkr->left == NULL) && (chkr->right == NULL)) { curr = chkr; delete chkr; curr->right = NULL; } else // right child has children { //if the node's right child has a left child // Move all the way down left to locate smallest element if((curr->right)->left != NULL) { tree_node* lcurr; tree_node* lcurrp; lcurrp = curr->right; lcurr = (curr->right)->left; while(lcurr->left != NULL) { lcurrp = lcurr; lcurr = lcurr->left; } curr->data = lcurr->data; delete lcurr; lcurrp->left = NULL; } else { tree_node* tmp; tmp = curr->right; curr->data = tmp->data; curr->right = tmp->right; delete tmp; } } return; } } void BinarySearchTree::print_inorder() { inorder(root); } void BinarySearchTree::inorder(tree_node* p) { if(p != NULL) { if(p->left) inorder(p->left); cout<<" "<<p->data<<" "; if(p->right) inorder(p->right); } else return; } void BinarySearchTree::print_preorder() { preorder(root); } void BinarySearchTree::preorder(tree_node* p) { if(p != NULL) { cout<<" "<<p->data<<" "; if(p->left) preorder(p->left); if(p->right) preorder(p->right); } else return; } void BinarySearchTree::print_postorder() { postorder(root); } void BinarySearchTree::postorder(tree_node* p) { if(p != NULL) { if(p->left) postorder(p->left); if(p->right) postorder(p->right); cout<<" "<<p->data<<" "; } else return; } int main() { BinarySearchTree b; int ch,tmp,tmp1; while(1) { cout<<endl<<endl; cout<<" Binary Search Tree Operations "<<endl; cout<<" ----------------------------- "<<endl; cout<<" 1. Insertion/Creation "<<endl; cout<<" 2. In-Order Traversal "<<endl; cout<<" 3. Pre-Order Traversal "<<endl; cout<<" 4. Post-Order Traversal "<<endl; cout<<" 5. Removal "<<endl; cout<<" 6. Exit "<<endl; cout<<" Enter your choice : "; cin>>ch; switch(ch) { case 1 : cout<<" Enter Number to be inserted : "; cin>>tmp; b.insert(tmp); break; case 2 : cout<<endl; cout<<" In-Order Traversal "<<endl; cout<<" -------------------"<<endl; b.print_inorder(); break; case 3 : cout<<endl; cout<<" Pre-Order Traversal "<<endl; cout<<" -------------------"<<endl; b.print_preorder(); break; case 4 : cout<<endl; cout<<" Post-Order Traversal "<<endl; cout<<" --------------------"<<endl; b.print_postorder(); break; case 5 : cout<<" Enter data to be deleted : "; cin>>tmp1; b.remove(tmp1); break; case 6 : system("pause"); return 0; break; } } }

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.

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.

Execute system command. Invokes the command processor to execute a command. If command is a null pointer, the function only checks whether a command processor is available through this function, without invoking any command. The effects of invoking a command depend on the system and library implementation, and may cause a program to behave in a non-standard manner or to terminate.

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

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.

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.

In C++, constructor is a special method which is invoked automatically at the time of object creation. It is used to initialize the data members of new object generally. The constructor in C++ has the same name as class or structure. Constructors are special class functions which performs initialization of every object. The Compiler calls the Constructor whenever an object is created. Constructors initialize values to object members after storage is allocated to the object. Whereas, Destructor on the other hand is used to destroy the class object. • Default Constructor: A constructor which has no argument is known as default constructor. It is invoked at the time of creating object.

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.

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.

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.

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

Deallocate storage space. Default deallocation functions (single-object form). A delete operator is used to deallocate memory space that is dynamically created using the new operator, calloc and malloc() function, etc., at the run time of a program in C++ language. In other words, a delete operator is used to release array and non-array (pointer) objects from the heap, which the new operator dynamically allocates to put variables on heap memory. We can use either the delete operator or delete [ ] operator in our program to delete the deallocated space. A delete operator has a void return type, and hence, it does not return a value.

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

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.

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:

The main purpose of C++ programming is to add object orientation to the C programming language and classes are the central feature of C++ that supports object-oriented programming and are often called user-defined types. A class is used to specify the form of an object and it combines data representation and methods for manipulating that data into one neat package. The data and functions within a class are called members of the class.

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.

C++ Program to check whether an undirected 'graph is tree' or not. Graph is tree if it doesn't contain cycles. A recursive function that uses visited[] & parent to detect cycle in subgraph

Problem takes 'E edges' as input and outputs dominant set of the graph, implementing the following heuristic. Dominant set of a graph's to find, a set of vertices S, such that for every

In C++ language, The mode is the maximum of the "count of occurrence" of the different data element. This algorithm is beneficial for large dataset with high repetition frequency