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++ > Computer Graphics Code Examples

Program to Check if a Given Binary Tree is an AVL Tree or Not

/* Program to Check if a Given Binary Tree is an AVL Tree or Not This is a C++ Program to check if BST is AVL. An AVL tree is a self-balancing binary search tree. It was the first such data structure to be invented. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. Lookup, insertion, and deletion all take O(log n) time in both the average and worst cases, where n is the number of nodes in the tree prior to the operation. Insertions and deletions may require the tree to be rebalanced by one or more tree rotations. A tree is AVL if and only if it is Binary Search Tree and is Balanced. */ #include <iostream> #include <cstdlib> using namespace std; /* Class SBBSTNode */ class SBBSTNode { public: int height, data; SBBSTNode *left, *right; /* Constructor */ SBBSTNode() { left = NULL; right = NULL; data = 0; height = 0; } /* Constructor */ SBBSTNode(int n) { left = NULL; right = NULL; data = n; height = 0; } }; /* Class SelfBalancingBinarySearchTree */ class SelfBalancingBinarySearchTree { private: SBBSTNode *root; public: /* Constructor */ SelfBalancingBinarySearchTree() { root = NULL; } /* Function to check if tree is empty */ bool isEmpty() { return root == NULL; } /* Make the tree logically empty */ void makeEmpty() { root = NULL; } /* Function to insert data */ void insert(int data) { root = insert(data, root); } /* Function to get height of node */ int height(SBBSTNode *t) { return t == NULL ? -1 : t->height; } /* Function to max of left/right node */ int max(int lhs, int rhs) { return lhs > rhs ? lhs : rhs; } /* Function to insert data recursively */ SBBSTNode *insert(int x, SBBSTNode *t) { if (t == NULL) t = new SBBSTNode(x); else if (x < t->data) { t->left = insert(x, t->left); if (height(t->left) - height(t->right) == 2) if (x < t->left->data) t = rotateWithLeftChild(t); else t = doubleWithLeftChild(t); } else if (x > t->data) { t->right = insert(x, t->right); if (height(t->right) - height(t->left) == 2) if (x > t->right->data) t = rotateWithRightChild(t); else t = doubleWithRightChild(t); } t->height = max(height(t->left), height(t->right)) + 1; return t; } /* Rotate binary tree node with left child */ SBBSTNode *rotateWithLeftChild(SBBSTNode* k2) { SBBSTNode *k1 = k2->left; k2->left = k1->right; k1->right = k2; k2->height = max(height(k2->left), height(k2->right)) + 1; k1->height = max(height(k1->left), k2->height) + 1; return k1; } /* Rotate binary tree node with right child */ SBBSTNode *rotateWithRightChild(SBBSTNode *k1) { SBBSTNode *k2 = k1->right; k1->right = k2->left; k2->left = k1; k1->height = max(height(k1->left), height(k1->right)) + 1; k2->height = max(height(k2->right), k1->height) + 1; return k2; } /* Double rotate binary tree node: first left child with its right child; then node k3 with new left child */ SBBSTNode *doubleWithLeftChild(SBBSTNode *k3) { k3->left = rotateWithRightChild(k3->left); return rotateWithLeftChild(k3); } /* Double rotate binary tree node: first right child with its left child; then node k1 with new right child */ SBBSTNode *doubleWithRightChild(SBBSTNode *k1) { k1->right = rotateWithLeftChild(k1->right); return rotateWithRightChild(k1); } /* Functions to count number of nodes */ int countNodes() { return countNodes(root); } int countNodes(SBBSTNode *r) { if (r == NULL) return 0; else { int l = 1; l += countNodes(r->left); l += countNodes(r->right); return l; } } /* Functions to search for an element */ bool search(int val) { return search(root, val); } bool search(SBBSTNode *r, int val) { bool found = false; while ((r != NULL) && !found) { int rval = r->data; if (val < rval) r = r->left; else if (val > rval) r = r->right; else { found = true; break; } found = search(r, val); } return found; } /* Function for inorder traversal */ void inorder() { inorder(root); } void inorder(SBBSTNode *r) { if (r != NULL) { inorder(r->left); cout << r->data << " "; inorder(r->right); } } /* Function for preorder traversal */ void preorder() { preorder(root); } void preorder(SBBSTNode *r) { if (r != NULL) { cout << r->data << " "; preorder(r->left); preorder(r->right); } } /* Function for postorder traversal */ void postorder() { postorder(root); } void postorder(SBBSTNode *r) { if (r != NULL) { postorder(r->left); postorder(r->right); cout << r->data << " "; } } }; int main() { SelfBalancingBinarySearchTree sbbst; cout << "SelfBalancingBinarySearchTree Test\n"; int val; char ch; /* Perform tree operations */ do { cout << "\nSelfBalancingBinarySearchTree Operations\n"; cout << "1. Insert " << endl; cout << "2. Count nodes" << endl; cout << "3. Search" << endl; cout << "4. Check empty" << endl; cout << "5. Make empty" << endl; int choice; cout << "Enter your Choice: "; cin >> choice; switch (choice) { case 1: cout << "Enter integer element to insert: "; cin >> val; sbbst.insert(val); break; case 2: cout << "Nodes = " << sbbst.countNodes() << endl; break; case 3: cout << "Enter integer element to search: "; cin >> val; if (sbbst.search(val)) cout << val << " found in the tree" << endl; else cout << val << " not found" << endl; break; case 4: cout << "Empty status = "; if (sbbst.isEmpty()) cout << "Tree is empty" << endl; else cout << "Tree is non - empty" << endl; break; case 5: cout << "\nTree cleared\n"; sbbst.makeEmpty(); break; default: cout << "Wrong Entry \n "; break; } /* Display tree*/ cout << "\nPost order : "; sbbst.postorder(); cout << "\nPre order : "; sbbst.preorder(); cout << "\nIn order : "; sbbst.inorder(); cout << "\nDo you want to continue (Type y or n): "; cin >> ch; } while (ch == 'Y' || ch == 'y'); return 0; }

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

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.

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.

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.

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.

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.

Search range for subsequence. Searches the range [first1,last1) for the first occurrence of the sequence defined by [first2,last2), and returns an iterator to its first element, or last1 if no occurrences are found. The elements in both ranges are compared sequentially using operator== (or pred, in version (2)): A subsequence of [first1,last1) is considered a match only when this is true for all the elements of [first2,last2). This function returns the first of such occurrences. For an algorithm that returns the last instead, see find_end. The function shall not modify any of its arguments.

As the name already suggests, these operators help in assigning values to variables. These operators help us in allocating a particular value to the operands. The main simple assignment operator is '='. We have to be sure that both the left and right sides of the operator must have the same data type. We have different levels of operators. Assignment operators are used to assign the value, variable and function to another variable. Assignment operators in C are some of the C Programming Operator, which are useful to assign the values to the declared variables. Let's discuss the various types of the assignment operators such as =, +=, -=, /=, *= and %=. The following table lists the assignment operators supported by the C language:

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

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.


A function is like a black box. It takes in input, does something with it, and then spits out an answer. We have some "terminology" to refer to functions: A function, call it f, and that uses





C++ program opens a file named filename.txt to read the content present inside this file, if there is an error in opening a file then puts a message on the screen for the "error", and if


C++ program 'merge two files' and store the content of both file into another file. First file name and second file name (say file1.txt and file2.txt), then Third file name that is used to


To sort an array in ascending order by bubble sort in C++ language, you have to ask to user to enter the array size then ask to enter array elements, start sorting the array elements by