C++ Programming Code Examples
C++ > Data Structures Code Examples
Code to create binary tree, find mirror image of it, find height,
/* Code to create binary tree, find mirror image of it, find height,
print original tree and mirrot image tree level wise, display leaf
nodes */
#include<iostream.h>
#include<conio.h>
#include<stdlib.h> //header for standard library function exit();
typedef class bin_tree
{
public:
int data,status;
class bin_tree *lchild,*rchild; //pointers to class bin_tree
bin_tree():data(0),lchild(NULL),rchild(NULL),status(0){}//constructor
class bin_tree* createbt(class bin_tree*,int data); //create
function
void leafnodes(class bin_tree*);
void display(class bin_tree*);
class bin_tree* mirrorimage(class bin_tree*,class bin_tree*);
void levelprint(class bin_tree*,int&);
}nodebt;//typedef for simplicity
typedef class queue
{
public:
nodebt *data;
class queue *next;
queue():data(NULL),next(NULL){}
nodebt* deletefront(queue **front,queue **rear);
queue *insertrear(queue **front,queue **rear,nodebt *data);
}que;
void nodebt::levelprint(class bin_tree* r,int &height)
{
que q1;
nodebt *check=NULL,*pt=r;
que *front=NULL,*rear=NULL;
q1.insertrear(&front,&rear,r);
q1.insertrear(&front,&rear,check);
while(front!=NULL)//q not empty
{
while(pt!=NULL)
{
pt=q1.deletefront(&front,&rear);
if(pt==NULL)
{
cout<<endl;
height++;
q1.insertrear(&front,&rear,check);
pt=q1.deletefront(&front,&rear);
}
if(front==NULL)
return;
cout<<pt->data<<" ";
if(pt->lchild!=NULL)
q1.insertrear(&front,&rear,pt->lchild);
if(pt->rchild!=NULL)
q1.insertrear(&front,&rear,pt->rchild);
}
}
}
nodebt* que::deletefront(que **front,que **rear)
{
nodebt *temp=NULL;
if(*front==NULL)
{
cout<<"
queue is empty";
}
else
{ temp=(*front)->data;
(*front)=(*front)->next;
if((*front)==NULL)
{
*rear=NULL;
}
}
return temp;
}
que *que::insertrear(que **front,que **rear,nodebt *data)
{
que *temp=NULL;
temp=new queue;
temp->data=data;
temp->next=NULL;
if(*front==NULL)
{
*front=temp;
*rear=temp;
}
else
{
(*rear)->next=temp;
*rear=(*rear)->next;
}
return *front;
}
nodebt* nodebt::mirrorimage(class bin_tree *r,class bin_tree* m)
{
nodebt *ret=NULL;
if(r==NULL)
return r;
if(r->status==2)
{
nodebt *temp=new nodebt;
temp->data=r->data;
temp->status=2;
m=temp;
ret=temp;
}
if(r->status==0)
{
nodebt *temp=new nodebt;
temp->data=r->data;
temp->status=1;
m->rchild=temp;
m=m->rchild;
}
if(r->status==1)
{
nodebt *temp=new nodebt;
temp->data=r->data;
temp->status=0;
m->lchild=temp;
m=m->lchild;
}
mirrorimage(r->lchild,m);
mirrorimage(r->rchild,m);
return ret;
}
void nodebt::leafnodes(class bin_tree* r)
{
if(r==NULL)
return;
if(r->lchild==NULL && r->lchild==NULL)
cout<<r->data<<" ";
leafnodes(r->lchild);
leafnodes(r->rchild);
}
void nodebt::display(class bin_tree* r)
{
if(r==NULL)
return;
cout<<" "<<r->data<<" ";
display(r->lchild);
display(r->rchild);
}
nodebt* nodebt::createbt(nodebt *r,int data)
{
int ch=0;
if(r==NULL)
{
nodebt *temp=new nodebt;
temp->data=data;
temp->status=2;
r=temp;
}
else
{
cout<<"
1.INSERT AT LEFT OF"<<" "<<r->data;
cout<<"
2.INSERT AT RIGHT OF"<<" "<<r->data;
cout<<"
ENTER YOUR CHOICE=";
cin>>ch;
switch(ch)
{
case 1:if(r->lchild==NULL)
{
nodebt *temp=new nodebt;
temp->data=data;
temp->status=0;
r->lchild=temp;
}
else
createbt(r->lchild,data);
break;
case 2:if(r->rchild==NULL)
{
nodebt *temp=new nodebt;
temp->data=data;
temp->status=1;
r->rchild=temp;
}
else
createbt(r->rchild,data);
break;
}
}
return r;
}
int main()
{ int ch=0,data=0,height=0;
nodebt *head=NULL,*m=NULL;
nodebt t2;
do
{ clrscr();
cout<<"
MENU";
cout<<"
1.CREATE OR INSERT BINARY TREE";
cout<<"
2.PRINT LEAF NODES";
cout<<"
3.FIND MIRROR IMAGE OF THE TREE";
cout<<"
4.PRINT ORIGINAL AND MIRROR IMAGE LEVELWISE";
cout<<"
5.HEIGHT OF TREE";
cout<<"
6.EXIT";
cout<<"
ENTER YOUR CHOICE=";
cin>>ch;
switch(ch)
{
case 1: nodebt t1;
do
{
cout<<"
ENTER THE DATA=";cin>>data;
head=t1.createbt(head,data);
cout<<"
DO U WANT TO ADD MORE NODES(1.YES/2.NO)";
cout<<"
ENTER YOUR CHOICE";
cin>>ch;
}while(ch!=2);
t1.display(head);
break;
case 2:t1.leafnodes(head);
break;
case 3:m=t2.mirrorimage(head,m);
cout<<"
MIRRORIMAGE TREE LEVELWISE
";
height=0;
t2.levelprint(m,height);
break;
case 4: cout<<"
ORIGINAL TREE LEVELWISE
";
t1.levelprint(head,height);
m=t2.mirrorimage(head,m);
cout<<"
MIRRORIMAGE TREE LEVELWISE
";
height=0;
t2.levelprint(m,height);
cout<<"
HEIGHT OF BINARY TREE="<<height-1;
break;
case 5:cout<<"
HEIGHT OF BINARY TREE="<<height-1;
break;
case 6:exit(1);
}
getch();
}while(ch!=6);
return 1;
}
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 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.
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 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 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++.
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.
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.
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 exit function terminates the program normally. Automatic objects are not destroyed, but static objects are. Then, all functions registered with atexit are called in the opposite order of registration. The code is returned to the operating system. An exit code of 0 or EXIT_SUCCESS means successful completion. If code is EXIT_FAILURE, an indication of program failure is returned to the operating system. Other values of code are implementation-defined. Calls all functions registered with the atexit() function, and destroys C++ objects with static storage duration, all in last-in-first-out (LIFO) order. C++ objects with static storage duration are destroyed in the reverse order of the completion of their constructor. (Automatic objects are not destroyed as a result of calling exit().)
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
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.
C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of statements inside another loop. Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number of loops. The nesting level can be defined at n times. You can define any type of loop inside another loop; for example, you can define 'while' loop inside a 'for' loop. A loop inside another loop is called a nested loop. The depth of nested loop depends on the complexity of a problem. We can have any number of nested loops as required. Consider a nested loop where the outer loop runs n times and consists of another loop inside it. The inner loop runs m times. Then, the total number of times the inner loop runs during the program execution is n*m.
The getch() is a predefined non-standard function that is defined in conio.h header file. It is mostly used by the Dev C/C++, MS- DOS's compilers like Turbo C to hold the screen until the user passes a single value to exit from the console screen. It can also be used to read a single byte character or string from the keyboard and then print. It does not hold any parameters. It has no buffer area to store the input character in a program. The getch() function does not accept any parameter from the user. It returns the ASCII value of the key pressed by the user as an input.
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 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.
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 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.
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.
#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++ program, a positive integer is asked to enter which is stored in the variable origNum. The number is copied to variable num. This is done because we need to check the origNum
The first program uses temporary variable to swap numbers, whereas the second program doesn't use temporary variables. To perform 'swapping' in above example, three variables