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++ > Data Structures Code Examples

AVL tree with insertion, deletion and balancing height

/* AVL tree with insertion, deletion and balancing height */ # include <iostream.h> # include <stdlib.h> # include <conio.h> struct node { int element; node *left; node *right; int height; }; typedef struct node *nodeptr; class bstree { public: void insert(int,nodeptr &); void del(int, nodeptr &); int deletemin(nodeptr &); void find(int,nodeptr &); nodeptr findmin(nodeptr); nodeptr findmax(nodeptr); void copy(nodeptr &,nodeptr &); void makeempty(nodeptr &); nodeptr nodecopy(nodeptr &); void preorder(nodeptr); void inorder(nodeptr); void postorder(nodeptr); int bsheight(nodeptr); nodeptr srl(nodeptr &); nodeptr drl(nodeptr &); nodeptr srr(nodeptr &); nodeptr drr(nodeptr &); int max(int,int); int nonodes(nodeptr); }; // Inserting a node void bstree::insert(int x,nodeptr &p) { if (p == NULL) { p = new node; p->element = x; p->left=NULL; p->right = NULL; p->height=0; if (p==NULL) cout<<"Out of Space"; } else { if (x<p->element) { insert(x,p->left); if ((bsheight(p->left) - bsheight(p->right))==2) { if (x < p->left->element) p=srl(p); else p = drl(p); } } else if (x>p->element) { insert(x,p->right); if ((bsheight(p->right) - bsheight(p->left))==2) { if (x > p->right->element) p=srr(p); else p = drr(p); } } else cout<<"Element Exists"; } int m,n,d; m=bsheight(p->left); n=bsheight(p->right); d=max(m,n); p->height = d + 1; } // Finding the Smallest nodeptr bstree::findmin(nodeptr p) { if (p==NULL) { cout<<" Empty Tree "; return p; } else { while(p->left !=NULL) p=p->left; return p; } } // Finding the Largest nodeptr bstree::findmax(nodeptr p) { if (p==NULL) { cout<<" Empty Tree "; return p; } else { while(p->right !=NULL) p=p->right; return p; } } // Finding an element void bstree::find(int x,nodeptr &p) { if (p==NULL) cout<<" Element not found "; else if (x < p->element) find(x,p->left); else if (x>p->element) find(x,p->right); else cout<<" Element found ! "; } // Copy a tree void bstree::copy(nodeptr &p,nodeptr &p1) { makeempty(p1); p1 = nodecopy(p); } // Make a tree empty void bstree::makeempty(nodeptr &p) { nodeptr d; if (p != NULL) { makeempty(p->left); makeempty(p->right); d=p; free(d); p=NULL; } } // Copy the nodes nodeptr bstree::nodecopy(nodeptr &p) { nodeptr temp; if (p==NULL) return p; else { temp = new node; temp->element = p->element; temp->left = nodecopy(p->left); temp->right = nodecopy(p->right); return temp; } } // Deleting a node void bstree::del(int x,nodeptr &p) { nodeptr d; if (p==NULL) cout<<"Element not found "; else if ( x < p->element) del(x,p->left); else if (x > p->element) del(x,p->right); else if ((p->left == NULL) && (p->right == NULL)) { d=p; free(d); p=NULL; cout<<" Element deleted ! "; } else if (p->left == NULL) { d=p; free(d); p=p->right; cout<<" Element deleted ! "; } else if (p->right == NULL) { d=p; p=p->left; free(d); cout<<" Element deleted ! "; } else p->element = deletemin(p->right); } int bstree::deletemin(nodeptr &p) { int c; cout<<"inside deltemin "; if (p->left == NULL) { c=p->element; p=p->right; return c; } else { c=deletemin(p->left); return c; } } void bstree::preorder(nodeptr p) { if (p!=NULL) { cout<<p->element<<"-->"; preorder(p->left); preorder(p->right); } } // Inorder Printing void bstree::inorder(nodeptr p) { if (p!=NULL) { inorder(p->left); cout<<p->element<<"-->"; inorder(p->right); } } // PostOrder Printing void bstree::postorder(nodeptr p) { if (p!=NULL) { postorder(p->left); postorder(p->right); cout<<p->element<<"-->"; } } int bstree::max(int value1, int value2) { return ((value1 > value2) ? value1 : value2); } int bstree::bsheight(nodeptr p) { int t; if (p == NULL) return -1; else { t = p->height; return t; } } nodeptr bstree:: srl(nodeptr &p1) { nodeptr p2; p2 = p1->left; p1->left = p2->right; p2->right = p1; p1->height = max(bsheight(p1->left),bsheight(p1->right)) + 1; p2->height = max(bsheight(p2->left),p1->height) + 1; return p2; } nodeptr bstree:: srr(nodeptr &p1) { nodeptr p2; p2 = p1->right; p1->right = p2->left; p2->left = p1; p1->height = max(bsheight(p1->left),bsheight(p1->right)) + 1; p2->height = max(p1->height,bsheight(p2->right)) + 1; return p2; } nodeptr bstree:: drl(nodeptr &p1) { p1->left=srr(p1->left); return srl(p1); } nodeptr bstree::drr(nodeptr &p1) { p1->right = srl(p1->right); return srr(p1); } int bstree::nonodes(nodeptr p) { int count=0; if (p!=NULL) { nonodes(p->left); nonodes(p->right); count++; } return count; } int main() { clrscr(); nodeptr root,root1,min,max;//,flag; int a,choice,findele,delele,leftele,rightele,flag; char ch='y'; bstree bst; //system("clear"); root = NULL; root1=NULL; cout<<" AVL Tree "; cout<<" ======== "; do { cout<<" 1.Insertion 2.FindMin "; cout<<"3.FindMax 4.Find 5.Copy "; cout<<"6.Delete 7.Preorder 8.Inorder "; cout<<" 9.Postorder 10.height "; cout<<" Enter the choice: "; cin>>choice; switch(choice) { case 1: cout<<" New node's value ? "; cin>>a; bst.insert(a,root); break; case 2: if (root !=NULL) { min=bst.findmin(root); cout<<" Min element : "<<min->element; } break; case 3: if (root !=NULL) { max=bst.findmax(root); cout<<" Max element : "<<max->element; } break; case 4: cout<<" Search node : "; cin>>findele; if (root != NULL) bst.find(findele,root); break; case 5: bst.copy(root,root1); bst.inorder(root1); break; case 6: cout<<"Delete Node ? "; cin>>delele; bst.del(delele,root); bst.inorder(root); break; case 7: cout<<" Preorder Printing... : "; bst.preorder(root); break; case 8: cout<<" Inorder Printing.... : "; bst.inorder(root); break; case 9: cout<<" Postorder Printing... : "; bst.postorder(root); break; case 10: cout<<" Height and Depth is "; cout<<bst.bsheight(root); cout<<"No. of nodes:- "<<bst.nonodes(root); break; } cout<<" Do u want to continue (y/n) ? "; cin>>ch; }while(ch=='y'); return 0; }

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.

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

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.

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

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.

It is a predefined function in "conio.h" (console input output header file) used to clear the console screen. It is a predefined function, by using this function we can clear the data from console (Monitor). Using of clrscr() is always optional but it should be place after variable or function declaration only. It is often used at the beginning of the program (mostly after variable declaration but not necessarily) so that the console is clear for our output.

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.

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.

Deallocate memory block. A block of memory previously allocated by a call to malloc, calloc or realloc is deallocated, making it available again for further allocations. If ptr does not point to a block of memory allocated with the above functions, it causes undefined behavior. If ptr is a null pointer, the function does nothing. Notice that this function does not change the value of ptr itself, hence it still points to the same (now invalid) location. free() function in C++ <cstdlib> library is used to deallocate a memory block in C++. Whenever we call malloc, calloc or realloc function to allocate a memory block dynamically in C++, compiler allocates a block of size bytes of memory and returns a pointer to the start of the block. The new memory block allocated is not initialized but have intermediate values. free() method is used to free such block of memory. In case the pointer mentioned does not point to any memory block then it may lead to an undefined behavior, but does nothing in case of null

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.

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

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.

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

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.

In this algorithm Sorting of Data is done from least significant digit to most significant digit. Here we need 10 different spaces labeled 0 to 9. Assume we have "n" Number of inputs. Let

If a number passed to checkPrimeNumber() is a Prime Number, this function returns true, if not the Function returns false. If enters larger number first, 'code' will not work as intended.