Happy Codings - Programming Code Examples

C++ Programming Code Examples

C++ > Data Structures Code Examples

Binary search tree with all the three recursive and non recursive traversals

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
/* Binary search tree with all the three recursive and non recursive traversals */ #include<iostream.h> #include<conio.h> #include<stdlib.h> class binarynode { public: int data; binarynode *left; binarynode *right; }; class binsrctree { private: binarynode *root; void inorder_rec(binarynode *); void inorder_non_rec(binarynode *); void preorder_rec(binarynode *); void preorder_non_rec(binarynode *); void postorder_rec(binarynode *); void postorder_non_rec(binarynode *); public: binsrctree() { root=NULL; } void insert(int ); void print_inorder_rec(); void print_inorder_non_rec(); void print_preorder_rec(); void print_preorder_non_rec(); void print_postorder_rec(); void print_postorder_non_rec(); }; class stack { int top; binarynode *stackel[20]; public: stack() { top=-1; } void push(binarynode *); binarynode* pop(); int empty() { if(top==-1) return(1); return(0); } }; void stack::push(binarynode *node) { stackel[++top]=node; } binarynode *stack::pop() { return(stackel[top--]); } class stack_int { int top; int stack_int[20]; public: stack_int() { top=-1; } void push(int flag); int pop(); int empty_int() { if(top==-1) return(1); return(0); } }; void stack_int::push(int flag) { stack_int[++top]=flag; } int stack_int::pop() { return(stack_int[top--]); } /*---------------------------------------------------------------------*/ /* FUNCTION TO INSERT A NODE IN THE TREE */ /*---------------------------------------------------------------------*/ void binsrctree::insert(int val) { binarynode *temp,*prev,*curr; temp=new binarynode; temp->data=val; temp->left=temp->right=NULL; if(root==NULL) { root=temp; } else { curr=root; while(curr!=NULL) { prev=curr; if(temp->data<curr->data) curr=curr->left; else curr=curr->right; } if(temp->data<prev->data) prev->left=temp; else prev->right=temp; } } /* ------------------------------------------------*/ /*INORDER RECURSIVE TRAVERSAL*/ /*-------------------------------------------------*/ void binsrctree::inorder_rec(binarynode *root) { if(root!=NULL) { inorder_rec(root->left); cout<<root->data<<" "; inorder_rec(root->right); } } /*--------------------------------------------------*/ /*INORDER NON RECURSIVE TRAVERSAL*/ /*--------------------------------------------------*/ void binsrctree::inorder_non_rec(binarynode *root) { stack stk; binarynode *temp; if(root!=NULL) { temp=root; do { while(temp!=NULL) { stk.push(temp); temp=temp->left; }/*end while*/ if(!stk.empty()) { temp=stk.pop(); cout<<temp->data<<" "; temp=temp->right; }/*end if*/ else break; }while(1); /*end do while*/ }/* end if */ else cout<<" Empty tree"; } /*end function */ /*--------------------------------------------------*/ /*PREORDER RECURSIVE TRAVERSAL */ /*---------------------------------------------------*/ void binsrctree::preorder_rec(binarynode *root) { if(root!=NULL) { cout<<root->data<<" "; preorder_rec(root->left); preorder_rec(root->right); } } /*--------------------------------------------------*/ /*PREORDER NON RECURSIVE TRAVERSAL */ /*---------------------------------------------------*/ void binsrctree::preorder_non_rec(binarynode *root) { stack stk; binarynode *temp=root; stk.push(temp); while(!stk.empty()) { temp=stk.pop(); if(temp!=NULL) { cout<<temp->data<<" "; stk.push(temp->right); stk.push(temp->left); } } } /*--------------------------------------------------*/ /*POSTRDER RECURSIVE TRAVERSAL */ /*---------------------------------------------------*/ void binsrctree::postorder_rec(binarynode *root) { if(root!=NULL) { postorder_rec(root->left); postorder_rec(root->right); cout<<root->data<<" "; } } /*--------------------------------------------------*/ /*POSTORDER NON RECURSIVE TRAVERSAL */ /*---------------------------------------------------*/ void binsrctree::postorder_non_rec(binarynode *root) { stack stk; stack_int stk1; int flag; binarynode *temp=root; do { if(temp!=NULL) { stk.push(temp); stk1.push(1); temp=temp->left; } else { if(stk.empty()) break; temp=stk.pop(); flag=stk1.pop(); if(flag==2) { cout<<temp->data; temp=NULL; } /*end if */ else { stk.push(temp); stk1.push(2); temp=temp->right; } /* end else */ } /* end if */ }while(1);/*end do while*/ }/*end function*/ /*--------------------------------------------------*/ /*FUNCTION TO PRINT INORDER RECURSIVE TRAVERSAL */ /*---------------------------------------------------*/ void binsrctree::print_inorder_rec() { cout<<" "; inorder_rec(root); cout<<" "; } /*--------------------------------------------------*/ /*FUNCTION TO PRINT INORDER NON RECURSIVE TRAVERSAL */ /*---------------------------------------------------*/ void binsrctree::print_inorder_non_rec() { cout<<" "; inorder_non_rec(root); cout<<" "; } /*--------------------------------------------------*/ /*FUNCTION TO PRINT PREORDER RECURSIVE TRAVERSAL */ /*---------------------------------------------------*/ void binsrctree::print_preorder_rec() { cout<<" "; preorder_rec(root); cout<<" "; } /*--------------------------------------------------*/ /*FUNCTION TO PRINT PREORDER NON RECURSIVE TRAVERSAL */ /*---------------------------------------------------*/ void binsrctree::print_preorder_non_rec() { cout<<" "; preorder_non_rec(root); cout<<" "; } /*--------------------------------------------------*/ /*FUNCTION TO PRINT POSTORDER RECURSIVE TRAVERSAL */ /*---------------------------------------------------*/ void binsrctree::print_postorder_rec() { cout<<" "; postorder_rec(root); cout<<" "; } /*--------------------------------------------------*/ /*FUNCTION TO PRINT POSTORDER NON RECURSIVE TRAVERSAL */ /*---------------------------------------------------*/ void binsrctree::print_postorder_non_rec() { cout<<" "; postorder_non_rec(root); cout<<" "; } /*--------------------------------------------------*/ /* MAIN FUNCTION */ /*---------------------------------------------------*/ void main() { binsrctree BST; int ch,element; clrscr(); do { cout<<" 1.Insert a node in binary tree"; cout<<" 2.Recursive Inorder traversal"; cout<<" 3.Non Recursive Inorder traversal"; cout<<" 4.Recursive preorder traversal"; cout<<" 5.Non recursive preorder traversal"; cout<<" 6.Recursive postorder traversal"; cout<<" 7.Non recursive postorder traversal"; cout<<" 8.Exit"; cout<<" Enter your choice"; cin>>ch; switch(ch) { case 1: cout<<" Enter the element you wnat to insert"; cin>>element; BST.insert(element); break; case 2: cout<<" Recursive Inorder traversal "; BST.print_inorder_rec(); break; case 3: cout<<" NonRecursive Inorder traversal "; BST.print_inorder_non_rec(); break; case 4: cout<<" Recursive preorder traversal "; BST.print_preorder_rec(); break; case 5: cout<<" Non recursive preorder traversal "; BST.print_preorder_non_rec(); break; case 6: cout<<" Recursive postorder traversal"; BST.print_postorder_rec(); break; case 7: cout<<" Non recursive postorder traversal "; BST.print_postorder_non_rec(); break; case 8: exit(1); } }while(ch<8); }
Standard Output Stream (cout) in C++
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.
Syntax for cout in C++
cout << var_name; //or cout << "Some String";
The syntax of the cout object in C++: cout << var_name; Or cout << "Some String";
<<
is the insertion operator
var_name
is usually a variable, but can also be an array element or elements of containers like vectors, lists, maps, etc. 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. The << operator can be used more than once with a combination of variables, strings, and manipulators. cout is used for displaying data on the screen. The operator << called as insertion operator or put to operator. The Insertion operator can be overloaded. Insertion operator is similar to the printf() operation in C. cout is the object of ostream class. Data flow direction is from variable to output device. Multiple outputs can be displayed using cout.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* standard output stream (cout) in C++ language */ #include <iostream> using namespace std; int main() { string str = "Do not interrupt me"; char ch = 'm'; // use cout with write() cout.write(str,6); cout << endl; // use cout with put() cout.put(ch); return 0; }
Stack push() Function in C++
Insert element. Inserts a new element at the top of the stack, above its current top element. The content of this new element is initialized to a copy of val. This member function effectively calls the member function push_back of the underlying container object. C++ Stack push () function is used for adding new elements at the top of the stack. If we have an array of type stack and by using the push() function we can insert new elements in the stack. The elements are inserted at the top of the stack. The element which is inserted most initially is deleted at the end and vice versa as stacks follow LIFO principle.
Syntax for Stack push() Function in C++
void push (const value_type& val); void push (value_type&& val);
val
Value to which the inserted element is initialized. Member type value_type is the type of the elements in the container (defined as an alias of the first class template parameter, T). The function only inserts element and does not return any value. The return type of the function can be thought as void.
Complexity
One call to push_back on the underlying container.
Data races
The container and up to all its contained elements are modified.
Exception safety
Provides the same level of guarantees as the operation performed on the underlying container object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* demonstrate the use of the push() function of the stack by insertion of simple integer values */ #include <iostream> #include <stack> int main() { std::stack<int> newstack; newstack.push(11); newstack.push(22); newstack.push(33); newstack.push(44); std::cout << "Popping out elements?"; newstack.pop(); newstack.pop(); while (!newstack.empty () ) { std::cout << " " << newstack.top(); newstack.pop(); } std:: cout<<'\n'; return 0; }
exit() Function in C++
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.
Syntax for exit() Function in C++
void exit (int status);
status
Status code. If this is 0 or EXIT_SUCCESS, it indicates success. If it is EXIT_FAILURE, it indicates failure. 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().) Functions registered with atexit() are called in the reverse order of their registration. A function registered with atexit(), before an object obj1 of static storage duration is initialized, will not be called until obj1's destruction has completed. A function registered with atexit(), after an object obj2 of static storage duration is initialized, will be called before obj2's destruction starts. Normal program termination performs the following (in the same order): • Objects associated with the current thread with thread storage duration are destroyed (C++11 only). • Objects with static storage duration are destroyed (C++) and functions registered with atexit are called. • All C streams (open with functions in <cstdio>) are closed (and flushed, if buffered), and all files created with tmpfile are removed. • Control is returned to the host environment. Note that objects with automatic storage are not destroyed by calling exit (C++). If status is zero or EXIT_SUCCESS, a successful termination status is returned to the host environment. If status is EXIT_FAILURE, an unsuccessful termination status is returned to the host environment. Otherwise, the status returned depends on the system and library implementation. Flushes all buffers, and closes all open files. All files opened with tmpfile() are deleted. Returns control to the host environment from the program. exit() returns no values.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* terminate the process normally, performing the regular cleanup for terminating programs by exit() function code example */ #include<iostream> using namespace std; int main() { int i; cout<<"Enter a non-zero value: "; //user input cin>>i; if(i) // checks whether the user input is non-zero or not { cout<<"Valid input.\n"; } else { cout<<"ERROR!"; //the program exists if the value is 0 exit(0); } cout<<"The input was : "<<i; }
Classes and Objects in C++ Language
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.
C++ Class Definitions
When you define a class, you define a blueprint for a data type. This doesn't actually define any data, but it does define what the class name means, that is, what an object of the class will consist of and what operations can be performed on such an object. A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a list of declarations. For example, we defined the Box data type using the keyword class as follows:
class Box { public: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box };
The keyword public determines the access attributes of the members of the class that follows it. A public member can be accessed from outside the class anywhere within the scope of the class object. You can also specify the members of a class as private or protected which we will discuss in a sub-section.
Define C++ Objects
A class provides the blueprints for objects, so basically an object is created from a class. We declare objects of a class with exactly the same sort of declaration that we declare variables of basic types. Following statements declare two objects of class Box:
Box Box1; // Declare Box1 of type Box Box Box2; // Declare Box2 of type Box
Both of the objects Box1 and Box2 will have their own copy of data members.
Accessing the Data Members
The public data members of objects of a class can be accessed using the direct member access operator (.). It is important to note that private and protected members can not be accessed directly using direct member access operator (.).
Classes and Objects in Detail
There are further interesting concepts related to C++ Classes and Objects which we will discuss in various sub-sections listed below: • Class Member Functions: A member function of a class is a function that has its definition or its prototype within the class definition like any other variable. • Class Access Modifiers: A class member can be defined as public, private or protected. By default members would be assumed as private. • Constructor & Destructor: A class constructor is a special function in a class that is called when a new object of the class is created. A destructor is also a special function which is called when created object is deleted. • Copy Constructor: The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously. • Friend Functions: A friend function is permitted full access to private and protected members of a class. • Inline Functions: With an inline function, the compiler tries to expand the code in the body of the function in place of a call to the function. • this Pointer: Every object has a special pointer this which points to the object itself. • Pointer to C++ Classes: A pointer to a class is done exactly the same way a pointer to a structure is. In fact a class is really just a structure with functions in it. • Static Members of a Class: Both data members and function members of a class can be declared as static.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
/* using public and private in C++ Class */ // Program to illustrate the working of // public and private in C++ Class #include <iostream> using namespace std; class Room { private: double length; double breadth; double height; public: // function to initialize private variables void initData(double len, double brth, double hgt) { length = len; breadth = brth; height = hgt; } double calculateArea() { return length * breadth; } double calculateVolume() { return length * breadth * height; } }; int main() { // create object of Room class Room room1; // pass the values of private variables as arguments room1.initData(42.5, 30.8, 19.2); cout << "Area of Room = " << room1.calculateArea() << endl; cout << "Volume of Room = " << room1.calculateVolume() << endl; return 0; }
Constructors in C++ Language
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.
Syntax for Default Constructor in C++
class_name(parameter1, parameter2, ...) { // constructor Definition }
• Parameterized Constructor: In C++, a constructor with parameters is known as a parameterized constructor. This is the preferred method to initialize member data. These are the constructors with parameter. Using this Constructor you can provide different values to data members of different objects, by passing the appropriate values as argument.
Syntax for Parameterized Constructor in C++
class class_name { public: class_name(variables) //Parameterized constructor declared. { } };
• Copy Constructors: These are special type of Constructors which takes an object as argument, and is used to copy values of data members of one object into other object.
Syntax for Copy Constructors in C++
classname (const classname &obj) { // body of constructor }
The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously. The copy constructor is used to - • Initialize one object from another of the same type. • Copy an object to pass it as an argument to a function. • Copy an object to return it from a function. If a copy constructor is not defined in a class, the compiler itself defines one.If the class has pointer variables and has some dynamic memory allocations, then it is a must to have a copy constructor. The most common form of copy constructor is shown here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
/* A constructor is a special type of member function that is called automatically when an object is created. In C++, a constructor has the same name as that of the class and it does not have a return type. */ #include <iostream> using namespace std; // declare a class class Wall { private: double length; double height; public: // initialize variables with parameterized constructor Wall(double len, double hgt) { length = len; height = hgt; } // copy constructor with a Wall object as parameter // copies data of the obj parameter Wall(Wall &obj) { length = obj.length; height = obj.height; } double calculateArea() { return length * height; } }; int main() { // create an object of Wall class Wall wall1(10.5, 8.6); // copy contents of wall1 to wall2 Wall wall2 = wall1; // print areas of wall1 and wall2 cout << "Area of Wall 1: " << wall1.calculateArea() << endl; cout << "Area of Wall 2: " << wall2.calculateArea(); return 0; }
main() Function 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.
Syntax for main() Function in C++
void main() { ............ ............ }
void
void is a keyword in C++ language, void means nothing, whenever we use void as a function return type then that function nothing return. here main() function no return any value.
main
main is a name of function which is predefined function in C++ library. In place of void we can also use int return type of main() function, at that time main() return integer type value. 1) It cannot be used anywhere in the program a) in particular, it cannot be called recursively b) its address cannot be taken 2) It cannot be predefined and cannot be overloaded: effectively, the name main in the global namespace is reserved for functions (although it can be used to name classes, namespaces, enumerations, and any entity in a non-global namespace, except that a function called "main" cannot be declared with C language linkage in any namespace). 3) It cannot be defined as deleted or (since C++11) declared with C language linkage, constexpr (since C++11), consteval (since C++20), inline, or static. 4) The body of the main function does not need to contain the return statement: if control reaches the end of main without encountering a return statement, the effect is that of executing return 0;. 5) Execution of the return (or the implicit return upon reaching the end of main) is equivalent to first leaving the function normally (which destroys the objects with automatic storage duration) and then calling std::exit with the same argument as the argument of the return. (std::exit then destroys static objects and terminates the program). 6) (since C++14) The return type of the main function cannot be deduced (auto main() {... is not allowed). 7) (since C++20) The main function cannot be a coroutine.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
/* simple code example by main() function in C++ */ #include <iostream> using namespace std; int main() { int day = 4; switch (day) { case 1: cout << "Monday"; break; case 2: cout << "Tuesday"; break; case 3: cout << "Wednesday"; break; case 4: cout << "Thursday"; break; case 5: cout << "Friday"; break; case 6: cout << "Saturday"; break; case 7: cout << "Sunday"; break; } return 0; }
If Else Statement in C++
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,
Syntax for If Statement in C++
if (condition) { // body of if 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.
Syntax for If...Else Statement
if (condition) { // block of code if condition is true } else { // block of code if condition is false }
The if..else statement evaluates the condition inside the parenthesis. If the condition evaluates true, the code inside the body of if is executed, the code inside the body of else is skipped from execution. If the condition evaluates false, the code inside the body of else is executed, the code inside the body of if is skipped from execution. The if...else statement is used to execute a block of code among two alternatives. However, if we need to make a choice between more than two alternatives, we use the if...else if...else statement.
Syntax for If...Else...Else If Statement in C++
if (condition1) { // code block 1 } else if (condition2){ // code block 2 } else { // code block 3 }
• If condition1 evaluates to true, the code block 1 is executed. • If condition1 evaluates to false, then condition2 is evaluated. • If condition2 is true, the code block 2 is executed. • If condition2 is false, the code block 3 is executed. There can be more than one else if statement but only one if and else 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.
Syntax for If Else If Ladder in C++
if (condition) statement 1; else if (condition) statement 2; . . else statement;
Working of the if-else-if ladder: 1. Control falls into the if block. 2. The flow jumps to Condition 1. 3. Condition is tested. If Condition yields true, goto Step 4. If Condition yields false, goto Step 5. 4. The present block is executed. Goto Step 7. 5. The flow jumps to Condition 2. If Condition yields true, goto step 4. If Condition yields false, goto Step 6. 6. The flow jumps to Condition 3. If Condition yields true, goto step 4. If Condition yields false, execute else block. Goto Step 7. 7. Exits the if-else-if ladder. • The if else ladder statement in C++ programming language is used to check set of conditions in sequence. • This is useful when we want to selectively executes one code block(out of many) based on certain conditions. • It allows us to check for multiple condition expressions and execute different code blocks for more than two conditions. • A condition expression is tested only when all previous if conditions in if-else ladder is false. • If any of the conditional expression evaluates to true, then it will execute the corresponding code block and exits whole if-else ladder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* If Else Statement in C++ Language */ #include <iostream> using namespace std; int main () { // local variable declaration: int a = 100; // check the boolean condition if( a < 20 ) { // if condition is true then print the following cout << "a is less than 20;" << endl; } else { // if condition is false then print the following cout << "a is not less than 20;" << endl; } cout << "value of a is : " << a << endl; return 0; }
Stack in C++ Language
LIFO stack. Stacks are a type of container adaptor, specifically designed to operate in a LIFO context (last-in first-out), where elements are inserted and extracted only from one end of the container. stacks are implemented as container adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access its elements. Elements are pushed/popped from the "back" of the specific container, which is known as the top of the stack.
Syntax for Stack in C++
template <class T, class Container = deque<T> > class stack;
T
Type of the elements. Aliased as member type stack::value_type.
Container
Type of the internal underlying container object where the elements are stored. Its value_type shall be T. Aliased as member type stack::container_type.
Member types
value_type The first template parameter (T) Type of the elements container_type The second template parameter (Container) Type of the underlying container reference container_type::reference usually, value_type& const_reference container_type::const_reference usually, const value_type& size_type an unsigned integral type usually, the same as size_t
Member functions
(constructor) Construct stack (public member function ) stack::emplace: Constructs and inserts new element at the top of stack. stack::empty: Tests whether stack is empty or not. stack::operator= copy version: Assigns new contents to the stack by replacing old ones. stack::operator= move version: Assigns new contents to the stack by replacing old ones. stack::pop: Removes top element from the stack. stack::push copy version: Inserts new element at the top of the stack. stack::push move version: Inserts new element at the top of the stack. stack::size: Returns the total number of elements present in the stack. stack::swap: Exchanges the contents of stack with contents of another stack. stack::top: Returns a reference to the topmost element of the stack.
Non-member function overloads
relational operators Relational operators for stack (function ) swap (stack) Exchange contents of stacks (public member function ) operator==: Tests whether two stacks are equal or not. operator!=: Tests whether two stacks are equal or not. operator<: Tests whether first stack is less than other or not. operator<=: Tests whether first stack is less than or equal to other or not. operator>: Tests whether first stack is greater than other or not. operator>=: Tests whether first stack is greater than or equal to other or not.
Non-member class specializations
uses_allocator<stack> Uses allocator for stack (class template ) The standard container classes vector, deque and list fulfill these requirements. By default, if no container class is specified for a particular stack class instantiation, the standard container deque is used. Stack is a data structure designed to operate in LIFO (Last in First out) context. In stack elements are inserted as well as get removed from only one end. Stack class is container adapter. Container is an objects that hold data of same type. Stack can be created from different sequence containers. If container is not provided it uses default deque container. Container adapters do not support iterators therefore we cannot use them for data manipulation. However they support push() and pop() member functions for data insertion and removal respectively.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
/* Stack in C++ language */ #include <iostream> #include <stack> using namespace std; void newstack(stack <int> ss) { stack <int> sg = ss; while (!sg.empty()) { cout << '\t' << sg.top(); sg.pop(); } cout << '\n'; } int main () { stack <int> newst; newst.push(55); newst.push(44); newst.push(33); newst.push(22); newst.push(11); cout << "The stack newst is : "; newstack(newst); cout << "\n newst.size() : " << newst.size(); cout << "\n newst.top() : " << newst.top(); cout << "\n newst.pop() : "; newst.pop(); newstack(newst); return 0; }
clrscr() Function in C++
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* clrscr() function is also a non-standard function defined in "conio.h" header. This function is used to clear the console screen. 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.*/ #include<iostream.h> #include<conio.h> void main() { int a=10, b=20; int sum=0; clrscr(); // use clrscr() after variable declaration sum=a+b; cout<<"Sum: "<<sum; //clear the console screen clrscr(); getch(); }
If Else If Ladder in C/C++
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.
Syntax of if...else Ladder in C++
if (Condition1) { Statement1; } else if(Condition2) { Statement2; } . . . else if(ConditionN) { StatementN; } else { Default_Statement; }
In the above syntax of if-else-if, if the Condition1 is TRUE then the Statement1 will be executed and control goes to next statement in the program following if-else-if ladder. If Condition1 is FALSE then Condition2 will be checked, if Condition2 is TRUE then Statement2 will be executed and control goes to next statement in the program following if-else-if ladder. Similarly, if Condition2 is FALSE then next condition will be checked and the process continues. If all the conditions in the if-else-if ladder are evaluated to FALSE, then Default_Statement will be executed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
/* write a C program which demonstrate use of if-else-if ladder statement */ /* Program to Print Day Names using Else If Ladder in C++*/ #include <iostream> using namespace std; int main() { int day; cout << "Enter Day Number: "; cin >> day; cout << "Day is "; if (day == 1) cout << "Sunday" << endl; else if (day == 2) cout << "Monday" << endl; else if (day == 3) cout << "Tuesday" << endl; else if (day == 4) cout << "Wednesday" << endl; else if (day == 5) cout << "Thursday" << endl; else if (day == 6) cout << "Friday" << endl; else cout << "Saturday" << endl; return 0; }
Switch Case Statement in C++
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.
Syntax for Switch Case Statement in C++
switch( expression ) { case value-1: Block-1; Break; case value-2: Block-2; Break; case value-n: Block-n; Break; default: Block-1; Break; } Statement-x;
• 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 does not provide the desired output. • Case labels always end with a colon ( : ). Each of these cases is associated with a block. • A block is nothing but multiple statements which are grouped for a particular case. • Whenever the switch is executed, the value of test-expression is compared with all the cases which we have defined inside the switch. Suppose the test expression contains value 4. This value is compared with all the cases until case whose label four is found in the program. As soon as a case is found the block of statements associated with that particular case is executed and control goes out of the switch. • The break keyword in each case indicates the end of a particular case. If we do not put the break in each case then even though the specific case is executed, the switch in C will continue to execute all the cases until the end is reached. This should not happen; hence we always have to put break keyword in each case. Break will terminate the case once it is executed and the control will fall out of the switch. • The default case is an optional one. Whenever the value of test-expression is not matched with any of the cases inside the switch, then the default will be executed. Otherwise, it is not necessary to write default in the switch. • Once the switch is executed the control will go to the statement-x, and the execution of a program will continue.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
/* the switch statement helps in testing the equality of a variable against a set of values */ #include <iostream> using namespace std; int main () { // local variable declaration: char grade = 'D'; switch(grade) { case 'A' : cout << "Excellent!" << endl; break; case 'B' : case 'C' : cout << "Well done" << endl; break; case 'D' : cout << "You passed" << endl; break; case 'F' : cout << "Better try again" << endl; break; default : cout << "Invalid grade" << endl; } cout << "Your grade is " << grade << endl; return 0; }
Stack Library empty() Function in C++
Test whether container is empty. Returns whether the stack is empty: i.e. whether its size is zero. stack::empty() function is an inbuilt function in C++ STL, which is defined in <stack>header file. empty() is used to check whether the associated container is empty or not and return true or false accordingly. This member function effectively calls member empty of the underlying container object.
Syntax for Stack empty() Function in C++
#include <stack> bool empty() const;
No parameter passed. Function returns true if the underlying container's size is 0, false otherwise.
Complexity
Constant (calling empty on the underlying container).
Data races
The container is accessed
Exception safety
Provides the same level of guarantees as the operation performed on the container (no-throw guarantee for standard container types).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
/* C++ Stack empty() function is used for testing whether the container is empty or not. In many cases, before extracting the actual elements from the stack, programmers give preference to check whether the stack does have some elements or not. Doing so is advantageous regarding memory and cost. */ /* Test the stack is empty or not by stack empty() function code example. */ #include <bits/stdc++.h> using namespace std; int main(){ cout<<"...use of empty function...\n"; int count=0; stack<int> st; //declare the stack st.push(4); //pushed 4 st.push(5); //pushed 5 st.push(6); cout<<"stack elements are:\n"; while(!st.empty()){//stack not empty cout<<"top element is:"<<st.top()<<endl;//print top element st.pop(); count++; } if(st.empty()) //to check for empty stack cout<<"stack empty\n"; cout<<count<<" pop operation performed total to make stack empty\n"; return 0; }
Break Statement in C++
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.
Syntax for Break Statement in C++
// jump-statement; break;
The break statement is used in the following scenario: • When a user is not sure about the number of iterations in the program. • When a user wants to stop the program based on some condition. The break statement terminates the loop where it is defined and execute the other. If the condition is mentioned in the program, based on the condition, it executes the loop. If the condition is true, it executes the conditional statement, and if the break statement is mentioned, it will immediately break the program. otherwise, the loop will iterate until the given condition fails. if the condition is false, it stops the program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
/* break statement with while loop code example */ // program to find the sum of positive numbers // if the user enters a negative numbers, break ends the loop // the negative number entered is not added to sum #include <iostream> using namespace std; int main() { int number; int sum = 0; while (true) { // take input from the user cout << "Enter a number: "; cin >> number; // break condition if (number < 0) { break; } // add all positive numbers sum += number; } // display the sum cout << "The sum is " << sum << endl; return 0; }
While Loop Statement in C++
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.
Syntax for While Loop Statement in C++
while (condition) { // body of the loop }
• A while loop evaluates the condition • If the condition evaluates to true, the code inside the while loop is executed. • The condition is evaluated again. • This process continues until the condition is false. • When the condition evaluates to false, the loop terminates. Do not forget to increase the variable used in the condition, otherwise the loop will never end!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
/* While Loop Statement in C++ language */ // program to find the sum of positive numbers // if the user enters a negative number, the loop ends // the negative number entered is not added to the sum #include <iostream> using namespace std; int main() { int number; int sum = 0; // take input from the user cout << "Enter a number: "; cin >> number; while (number >= 0) { // add all positive numbers sum += number; // take input again if the number is positive cout << "Enter a number: "; cin >> number; } // display the sum cout << "\nThe sum is " << sum << endl; return 0; }
Memory Management new Operator in C++
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.
Syntax for new Operator in C++
#include <new> //throwing (1) void* operator new (std::size_t size); //nothrow (2) void* operator new (std::size_t size, const std::nothrow_t& nothrow_value) noexcept; //placement (3) void* operator new (std::size_t size, void* ptr) noexcept;
size
Size in bytes of the requested memory block. This is the size of the type specifier in the new-expression when called automatically by such an expression. If this argument is zero, the function still returns a distinct non-null pointer on success (although dereferencing this pointer leads to undefined behavior). size_t is an integral type.
nothrow_value
The constant nothrow. This parameter is only used to distinguish it from the first version with an overloaded version. When the nothrow constant is passed as second parameter to operator new, operator new returns a null-pointer on failure instead of throwing a bad_alloc exception. nothrow_t is the type of constant nothrow.
ptr
A pointer to an already-allocated memory block of the proper size. If called by a new-expression, the object is initialized (or constructed) at this location. For the first and second versions, function returns a pointer to the newly allocated storage space. For the third version, ptr is returned. • (1) throwing allocation: Allocates size bytes of storage, suitably aligned to represent any object of that size, and returns a non-null pointer to the first byte of this block. On failure, it throws a bad_alloc exception. • (2) nothrow allocation: Same as above (1), except that on failure it returns a null pointer instead of throwing an exception. The default definition allocates memory by calling the the first version: ::operator new (size). If replaced, both the first and second versions shall return pointers with identical properties. • (3) placement: Simply returns ptr (no storage is allocated). Notice though that, if the function is called by a new-expression, the proper initialization will be performed (for class objects, this includes calling its default constructor). The default allocation and deallocation functions are special components of the standard library; They have the following unique properties: • Global: All three versions of operator new are declared in the global namespace, not within the std namespace. • Implicit: The allocating versions ((1) and (2)) are implicitly declared in every translation unit of a C++ program, no matter whether header <new> is included or not. • Replaceable: The allocating versions ((1) and (2)) are also replaceable: A program may provide its own definition that replaces the one provided by default to produce the result described above, or can overload it for specific types. If set_new_handler has been used to define a new_handler function, this new-handler function is called by the default definitions of the allocating versions ((1) and (2)) if they fail to allocate the requested storage. operator new can be called explicitly as a regular function, but in C++, new is an operator with a very specific behavior: An expression with the new operator, first calls function operator new (i.e., this function) with the size of its type specifier as first argument, and if this is successful, it then automatically initializes or constructs the object (if needed). Finally, the expression evaluates as a pointer to the appropriate type.
Data races
Modifies the storage referenced by the returned value. Calls to allocation and deallocation functions that reuse the same unit of storage shall occur in a single total order where each deallocation happens entirely before the next allocation. This shall also apply to the observable behavior of custom replacements for this function.
Exception safety
The first version (1) throws bad_alloc if it fails to allocate storage. Otherwise, it throws no exceptions (no-throw guarantee).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
/* C++ allows us to allocate the memory of a variable or an array in run time. This is known as dynamic memory allocation. The new operator denotes a request for memory allocation on the Free Store. If sufficient memory is available, new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable. */ /* Allocate storage space by operator new */ // C++ program code example to illustrate dynamic allocation and deallocation of memory using new and delete #include <iostream> using namespace std; int main () { // Pointer initialization to null int* p = NULL; // Request memory for the variable // using new operator p = new(nothrow) int; if (!p) cout << "allocation of memory failed\n"; else { // Store value at allocated address *p = 29; cout << "Value of p: " << *p << endl; } // Request block of memory // using new operator float *r = new float(75.25); cout << "Value of r: " << *r << endl; // Request block of memory of size n int n = 5; int *q = new(nothrow) int[n]; if (!q) cout << "allocation of memory failed\n"; else { for (int i = 0; i < n; i++) q[i] = i+1; cout << "Value store in block of memory: "; for (int i = 0; i < n; i++) cout << q[i] << " "; } // freed the allocated memory delete p; delete r; // freed the block of allocated memory delete[] q; return 0; }
Standard Input Stream (cin) in C++
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.
Syntax for Standard Input Stream (cin) in C++
cin >> var_name;
>>
is the extraction operator.
var_name
is usually a variable, but can also be an element of containers like arrays, vectors, lists, etc. 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 >> operator can also be used more than once in the same statement to accept multiple inputs. The cin object can also be used with other member functions such as getline(), read(), etc. Some of the commonly used member functions are: • cin.get(char &ch): Reads an input character and stores it in ch. • cin.getline(char *buffer, int length): Reads a stream of characters into the string buffer, It stops when: it has read length-1 characters or when it finds an end-of-line character '\n' or the end of the file eof. • cin.read(char *buffer, int n): Reads n bytes (or until the end of the file) from the stream into the buffer. • cin.ignore(int n): Ignores the next n characters from the input stream. • cin.eof(): Returns a non-zero value if the end of file (eof) is reached. The prototype of cin as defined in the iostream header file is: extern istream cin; The cin object in C++ is an object of class istream. It is associated with the standard C input stream stdin. The cin object is ensured to be initialized during or before the first time an object of type ios_base::Init is constructed. After the cin object is constructed, cin.tie() returns &cout. This means that any formatted input operation on cin forces a call to cout.flush() if any characters are pending for output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/* Standard Input Stream (cin) in C++ language */ // cin with Member Functions #include <iostream> using namespace std; int main() { char name[20], address[20]; cout << "Name: "; // use cin with getline() cin.getline(name, 20); cout << "Address: "; cin.getline(address, 20); cout << endl << "You entered " << endl; cout << "Name = " << name << endl; cout << "Address = " << address; return 0; }
Stack Library pop() Function in C++
Remove top element. Removes the element on top of the stack, effectively reducing its size by one. The C++ function std::stack::pop() removes top element from the stack and reduces size of stack by one. This function calls destructor on removed element. The element removed is the latest element inserted into the stack, whose value can be retrieved by calling member stack::top. This calls the removed element's destructor. This member function effectively calls the member function pop_back of the underlying container object.
Syntax for Stack pop() Function in C++
#include <stack> void pop();
The function takes no parameter and is used only for the deletion of the top element. Also since the stack follows LIFO principle we do not need to specify which element is to be deleted as it is by default understood that the top most element will be removed first. The function is used only for the removal of elements from the stack and has no return value. Hence we can say that the return type of the function is void.
Complexity
Constant (calling pop_back on the underlying container).
Data races
The container and up to all its contained elements are modified.
Exception safety
Provides the same level of guarantees as the operation performed on the underlying container object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
/* pop() function is used to remove or 'pop' an element from the top of the stack(newest or the topmost element in the stack). This is an inbuilt function from C++ Standard Template Library(STL). This function belongs to the <stack> header file. The element is removed from the stack container and the size of the stack is decreased by 1. */ /* removing the topmost element of the stack by Stack pop() function code example. */ #include <iostream> #include <stack> using namespace std; int main (){ stack<int> MyStack; MyStack.push(10); MyStack.push(20); MyStack.push(30); MyStack.push(40); MyStack.push(50); cout<<"The top element of the stack is: "<<MyStack.top(); //deletes top element of the stack MyStack.pop(); cout<<"\nNow, the top element of the stack is: "<<MyStack.top(); //deletes next top element of the stack MyStack.pop(); cout<<"\nNow, the top element of the stack is: "<<MyStack.top(); return 0; }
#include Directive in C++
#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.
Syntax for #include Directive in C++
#include "user-defined_file"
Including using " ": When using the double quotes(" "), the preprocessor access the current directory in which the source "header_file" is located. This type is mainly used to access any header files of the user's program or user-defined files.
#include <header_file>
Including using <>: While importing file using angular brackets(<>), the the preprocessor uses a predetermined directory path to access the file. It is mainly used to access system header files located in the standard system directories. Header File or Standard files: This is a file which contains C/C++ function declarations and macro definitions to be shared between several source files. Functions like the printf(), scanf(), cout, cin and various other input-output or other standard functions are contained within different header files. So to utilise those functions, the users need to import a few header files which define the required functions. User-defined files: These files resembles the header files, except for the fact that they are written and defined by the user itself. This saves the user from writing a particular function multiple times. Once a user-defined file is written, it can be imported anywhere in the program using the #include preprocessor. • In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename. • In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename. • You can use only comment after filename otherwise it will give error.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/* using #include directive in C language */ #include <stdio.h> int main() { /* * C standard library printf function * defined in the stdio.h header file */ printf("I love you Clementine"); printf("I love you so much"); printf("HappyCodings"); return 0; }


The 'C++ program' tries to count alphabetical letters from d to n, but a break makes it stop when it encounters k: In a for statement, the 'break' can stop the counting when particular
It's used in switch case control structure after the case blocks. Generally all cases in switch case are followed by a "Break Statement" to avoid the subsequent cases (see the example
Code sample about C++ language Function overloading. If a "C++ Class" have multiple member functions, having the same name but different parameters and programmers
Algorithm represents a 'graph' using Linked list. The time complexity of this algorithm is "O(e)". This algorithm takes the input of the number of vertex and edges. Take the input
Displaying the "Topological Sort Method" of finding whether a given graph contains cycle or not using Kosaraju's Algorithm. Enter the source and destination. Cycles exist in graph.