Happy Codings - Programming Code Examples

C++ Programming Code Examples

C++ > Data Structures Code Examples

Appending two linked list based upon two data members

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
/* Appending two linked list based upon two data members of individual linked list objects. */ class CClass1 { public: char mStringData[10];; long int mDataMember1; long int mDataMember2; CClass1 *structpNextValue; void SetValue(CString string, long int a, long int b) { strcpy(mStringData, string); mDataMember1 = a; mDataMember2 = b; } CClass1(void); ~CClass1(void); }; /////////////////////////////////////////////////////////////////////// class CClass2 { public: char mStringData[10]; long int mDataMember1; long int mDataMember2; CClass2 *structpNextValue; void SetValue(CString string, long int a, long int b) { strcpy(mStringData, string); mDataMember1 = a; mDataMember2 = b; } CClass2(void); ~CClass2(void); }; /////////////////////////////////////////////////////////////////////// CClass1 *pstrTemp; lTemp = lNumOrphanRecord; pstrTemp = (CClass1*)malloc(sizeof(CClass1)); pstrTemp->structpNextValue = NULL; CClass2 *pstrExcTemp = &mObject2[0]; while(lTemp > 0) { pstrTemp->mDataMember1 = pstrExcTemp->mDataMember1; strcpy(pstrTemp->mStringData, pstrExcTemp->mStringData); pstrTemp->mDataMember2 = pstrExcTemp->mDataMember2; pstrExcTemp = pstrExcTemp->structpNextValue; if (mObject1->mDataMember1 == 0) { mObject1 = pstrTemp; } else { CClass1 *pstrPrev = NULL; CClass1 *pstrCurr = mObject1; long int tempSeqNum = mObject1->mDataMember1; int Icount=0; while ( (pstrCurr) &&(pstrCurr->mDataMember1 !=0) && (pstrCurr->mDataMember1 < pstrTemp->mDataMember1) ) { pstrPrev = pstrCurr; pstrCurr = pstrCurr->structpNextValue; } if ((pstrCurr) && (pstrCurr->mDataMember1 == pstrTemp->mDataMember1) ) { if (pstrCurr->mDataMember2 < pstrTemp->mDataMember2) { pstrTemp->structpNextValue = pstrCurr->structpNextValue; free(pstrCurr); pstrCurr = pstrTemp; if (tempSeqNum == pstrTemp->mDataMember1) { mObject1 = pstrCurr; } if(pstrPrev) { pstrPrev->structpNextValue = pstrCurr; } } if(!pstrTemp) pstrTemp = NULL; lNumOrphanRecord--; } else { if (pstrPrev) { pstrPrev->structpNextValue = pstrTemp; pstrTemp->structpNextValue = pstrCurr; } else { pstrTemp->structpNextValue = pstrCurr; mObject1 = pstrTemp; } } } pstrTemp = (CClass1*)malloc(sizeof(CClass1)); pstrTemp->structpNextValue = NULL; lTemp--; } lNumRecord += lNumOrphanRecord; pstrExcTemp = &mObject2[0]; pstrExcTemp = pstrExcTemp->structpNextValue; while(mObject2->structpNextValue != NULL) { pstrExcTemp = mObject2->structpNextValue; mObject2->structpNextValue = pstrExcTemp->structpNextValue; if(!pstrExcTemp) pstrExcTemp = NULL; }
Destructors in C++
A destructor is a special member function that works just opposite to constructor, unlike constructors that are used for initializing an object, destructors destroy (or delete) the object. Destructors in C++ are members functions in a class that delete an object. They are called when the class object goes out of scope such as when the function ends, the program ends, a delete variable is called etc. Destructors are different from normal member functions as they don't take any argument and don't return anything. Also, destructors have the same name as their class and their name is preceded by a tilde(~).
Syntax for Destructor in C++
~class_name() { //Some code }
Similar to constructor, the destructor name should exactly match with the class name. A destructor declaration should always begin with the tilde(~) symbol as shown in the syntax above. A destructor is automatically called when: • The program finished execution. • When a scope (the { } parenthesis) containing local variable ends. • When you call the delete operator.
Destructor rules
• Name should begin with tilde sign(~) and must match class name. • There cannot be more than one destructor in a class. • Unlike constructors that can have parameters, destructors do not allow any parameter. • They do not have any return type, just like constructors. • When you do not specify any destructor in a class, compiler generates a default destructor and inserts it into your code.
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
/* Destructor is an instance member function which is invoked automatically whenever an object is going to be destroyed. Meaning, a destructor is the last function that is going to be called before an object is destroyed. The thing is to be noted here, if the object is created by using new or the constructor uses new to allocate memory which resides in the heap memory or the free store, the destructor should use delete to free the memory. */ #include <iostream> using namespace std; class HelloWorld{ public: //Constructor HelloWorld(){ cout<<"Constructor is called"<<endl; } //Destructor ~HelloWorld(){ cout<<"Destructor is called"<<endl; } //Member function void display(){ cout<<"Hello World!"<<endl; } }; int main(){ //Object created HelloWorld obj; //Member function called obj.display(); 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; }
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; }
Assignment Operators in C++
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:
=
Simple assignment operator. Assigns values from right side operands to left side operand
+=
Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand.
-=
Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand.
*=
Multiply AND assignment operator. It multiplies the right operand with the left operand and assigns the result to the left operand.
/=
Divide AND assignment operator. It divides the left operand with the right operand and assigns the result to the left operand.
%=
Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand.
<<=
Left shift AND assignment operator.
>>=
Right shift AND assignment operator.
&=
Bitwise AND assignment operator.
^=
Bitwise exclusive OR and assignment operator.
|=
Bitwise inclusive OR and assignment operator.
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
/* Assignment operators are used to assigning value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error. */ // C++ program to demonstrate working of Assignment operators #include <iostream> using namespace std; int main() { // Assigning value 10 to a // using "=" operator int a = 10; cout << "Value of a is "<<a<<"\n"; // Assigning value by adding 10 to a // using "+=" operator a += 10; cout << "Value of a is "<<a<<"\n"; // Assigning value by subtracting 10 from a // using "-=" operator a -= 10; cout << "Value of a is "<<a<<"\n"; // Assigning value by multiplying 10 to a // using "*=" operator a *= 10; cout << "Value of a is "<<a<<"\n"; // Assigning value by dividing 10 from a // using "/=" operator a /= 10; cout << "Value of a is "<<a<<"\n"; return 0; }
sizeof() Operator in C++
The sizeof() is an operator that evaluates the size of data type, constants, variable. It is a compile-time operator as it returns the size of any variable or a constant at the compilation time. The size, which is calculated by the sizeof() operator, is the amount of RAM occupied in the computer. The sizeof is a keyword, but it is a compile-time operator that determines the size, in bytes, of a variable or data type. The sizeof operator can be used to get the size of classes, structures, unions and any other user defined data type.
Syntax for sizeof() Operator in C++
sizeof(data_type);
data_type
data type whose size is to be calculated The data_type can be the data type of the data, variables, constants, unions, structures, or any other user-defined data type. If the parameter of a sizeof() operator contains the data type of a variable, then the sizeof() operator will return the size of the data type. sizeof() may give different output according to machine, we have run our program on 32 bit gcc compiler.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* The sizeof() is an operator in C and C++. It is an unary operator which assists a programmer in finding the size of the operand which is being used. */ #include <iostream> using namespace std; int main() { int arr[]={10,20,30,40,50}; std::cout << "Size of the array 'arr' is : "<<sizeof(arr) << std::endl; cout << "Size of char : " << sizeof(char) << endl; cout << "Size of int : " << sizeof(int) << endl; cout << "Size of short int : " << sizeof(short int) << endl; cout << "Size of long int : " << sizeof(long int) << endl; cout << "Size of float : " << sizeof(float) << endl; cout << "Size of double : " << sizeof(double) << endl; cout << "Size of wchar_t : " << sizeof(wchar_t) << endl; return 0; }
Logical Operators in C++
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:
&&
Called Logical AND operator. If both the operands are non-zero, then condition becomes true. (A && B) is false. The logical AND operator && returns true - if and only if all the operands are true. false - if one or more operands are false.
||
Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true. (A || B) is true. The logical OR operator || returns true - if one or more of the operands are true. false - if and only if all the operands are false.
!
Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true, then Logical NOT operator will make false. !(A && B) is true. The logical NOT operator ! is a unary operator i.e. it takes only one operand. It returns true when the operand is false, and false when the operand is true.
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
/* The operator ! is the C++ operator for the Boolean operation NOT. It has only one operand, to its right, and inverts it, producing false if its operand is true, and true if its operand is false. Basically, it returns the opposite Boolean value of evaluating its operand. The logical operators && and || are used when evaluating two expressions to obtain a single relational result. The operator && corresponds to the Boolean logical operation AND, which yields true if both its operands are true, and false otherwise. */ #include <iostream> using namespace std; main() { int a = 5; int b = 20; int c ; if(a && b) { cout << "Line 1 - Condition is true"<< endl ; } if(a || b) { cout << "Line 2 - Condition is true"<< endl ; } /* Let's change the values of a and b */ a = 0; b = 10; if(a && b) { cout << "Line 3 - Condition is true"<< endl ; } else { cout << "Line 4 - Condition is not true"<< endl ; } if(!(a && b)) { cout << "Line 5 - Condition is true"<< endl ; } return 0; }
Standard Library malloc() Function in C++
Allocate memory block. Allocates a block of size bytes of memory, returning a pointer to the beginning of the block. The content of the newly allocated block of memory is not initialized, remaining with indeterminate values. If size is zero, the return value depends on the particular library implementation (it may or may not be a null pointer), but the returned pointer shall not be dereferenced. Malloc function in C++ is used to allocate a specified size of the block of memory dynamically uninitialized. It allocates the memory to the variable on the heap and returns the void pointer pointing to the beginning address of the memory block. The values in the memory block allocated remain uninitialized and indeterminate. In case the size specified in the function is zero then pointer returned must not be dereferenced as it can be a null pointer, and in this case, behavior depends on particular library implementation. When a memory block is allocated dynamically memory is allocated on the heap but the pointer is allocated to the stack.
Syntax for malloc() Function in C++
#include <cstdlib> void* malloc (size_t size);
size
Size of the memory block, in bytes. size_t is an unsigned integral type. On success, a pointer to the memory block allocated by the function. The type of this pointer is always void*, which can be cast to the desired type of data pointer in order to be dereferenceable. If the function failed to allocate the requested block of memory, a null pointer is returned.
Advantages of malloc() in C++
There are a lot of advantages to using the malloc method in one's application: • Dynamic Memory allocation: Usually we create arrays at compile time in C++, the size of such arrays is fixed. In the case at run time we do not use all the space or extra space is required for more elements to be inserted in the array, then this leads to improper memory management or segmentation fault error. • Heap memory: Local arrays that are defined at compile time are allocated on the stack, which has lagged in memory management in case the number of data increases. Thus one needs to allocate memory out of the stack, thus malloc comes into the picture as it allocates the memory location on the heap and returns a pointer on the stack pointing to the starting address of the array type memory being allocated. • Variable-length array: This function helps to allocate memory for an array whose size can be defined at the runtime. Thus one can create the number of blocks as much as required at run time. • Better lifetime: Variable created using malloc method is proved to have a better life than the local arrays as a lifetime of local arrays depends on the scope they are being defined and cannot access out of their scope. But variables or arrays created using malloc exist till they are freed. This is of great importance for various data structures such as linked list, binary heap, etc.
Differences between the malloc() and new
• The new operator constructs an object, i.e., it calls the constructor to initialize an object while malloc() function does not call the constructor. The new operator invokes the constructor, and the delete operator invokes the destructor to destroy the object. This is the biggest difference between the malloc() and new. • The new is an operator, while malloc() is a predefined function in the stdlib header file. • The operator new can be overloaded while the malloc() function cannot be overloaded. • If the sufficient memory is not available in a heap, then the new operator will throw an exception while the malloc() function returns a NULL pointer. • In the new operator, we need to specify the number of objects to be allocated while in malloc() function, we need to specify the number of bytes to be allocated. • In the case of a new operator, we have to use the delete operator to deallocate the memory. But in the case of malloc() function, we have to use the free() function to deallocate the memory.
Data races
Only the storage referenced by the returned pointer is modified. No other storage locations are accessed by the call. If the function reuses the same unit of storage released by a deallocation function (such as free or realloc), the functions are synchronized in such a way that the deallocation happens entirely before the next allocation.
Exceptions
No-throw guarantee: this function never throws exceptions.
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
/* allocate the requested size of bytes and it returns a pointer to the first byte of allocated memory by malloc() function code example. */ #include <iostream> #include <cstdlib> using namespace std; int main() { // allocate 5 int memory blocks int* ptr = (int*) malloc(5 * sizeof(int)); // check if memory has been allocated successfully if (!ptr) { cout << "Memory Allocation Failed"; exit(1); } cout << "Initializing values..." << endl << endl; for (int i = 0; i < 5; i++) { ptr[i] = i * 2 + 1; } cout << "Initialized values" << endl; // print the values in allocated memories for (int i = 0; i < 5; i++) { // ptr[i] and *(ptr+i) can be used interchangeably cout << *(ptr + i) << endl; } // deallocate memory free(ptr); return 0; }
IOS Library eof() Function in C++
Check whether eofbit is set. Returns true if the eofbit error state flag is set for the stream. This flag is set by all standard input operations when the End-of-File is reached in the sequence associated with the stream. Note that the value returned by this function depends on the last operation performed on the stream (and not on the next). Operations that attempt to read at the End-of-File fail, and thus both the eofbit and the failbit end up set. This function can be used to check whether the failure is due to reaching the End-of-File or to some other reason.
Syntax for IOS eof() Function in C++
bool eof() const;
This function does not accept any parameter. Function returns true if the stream's eofbit error state flag is set (which signals that the End-of-File has been reached by the last input operation). false otherwise.
Data races
Accesses the stream object. Concurrent access to the same stream object may cause data races.
Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the stream.
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
/* The eof() method of ios class in C++ is used to check if the stream is has raised any EOF (End Of File) error. It means that this function will check if this stream has its eofbit set. */ // C++ code example to demonstrate the working of eof() function #include <iostream> #include <fstream> int main () { std::ifstream is("example.txt"); char c; while (is.get(c)) std::cout << c; if (is.eof()) std::cout << "[EoF reached]\n"; else std::cout << "[error reading]\n"; is.close(); return 0; }
Standard Library free() Function in C++
Deallocate memory block. A block of memory previously allocated by a call to malloc, calloc or realloc is deallocated, making it available again for further allocations. If ptr does not point to a block of memory allocated with the above functions, it causes undefined behavior. If ptr is a null pointer, the function does nothing. Notice that this function does not change the value of ptr itself, hence it still points to the same (now invalid) location. free() function in C++ <cstdlib> library is used to deallocate a memory block in C++. Whenever we call malloc, calloc or realloc function to allocate a memory block dynamically in C++, compiler allocates a block of size bytes of memory and returns a pointer to the start of the block. The new memory block allocated is not initialized but have intermediate values. free() method is used to free such block of memory. In case the pointer mentioned does not point to any memory block then it may lead to an undefined behavior, but does nothing in case of null pointer. Also after the memory block is made available still the pointer points to the same memory location.
Syntax for free() Function in C++
#include <cstdlib> void free (void* ptr);
ptr
Pointer to a memory block previously allocated with malloc, calloc or realloc. This function does not return any value. • Here ptr refers to a pointer pointing to memory block in C++ that has been previously allocated by malloc, calloc or realloc. Here type of pointer is void because it is capable to hold any type of the pointer and can be cast to any type while dereferencing. • In case pointer mentioned in free function is a null pointer then function does nothing as there is memory block for it to deallocate and returns nothing. • And in case the pointer points to a memory block that has not been allocated using any one of malloc, calloc or realloc method then the behavior of free function can not be predicted. The return type of free() function is void, that means this function returns nothing. All it does is simply deallocating the block of memory pointed by the referred pointer.
How free() Function work in C++?
• Free method is a great tool for dynamic memory management. It is present in <cstdlib> header file. • When a memory block is allocated using std::malloc, std::calloc or std::alloc.a pointer is returned. This pointer is passed to free function, for deallocation. This helps in memory management for the compiler dynamically. • In case the pointer is a null pointer then function does nothing as there is no memory being referenced by the pointer. • As the datatype for the pointer is void then its is capable for dereferencing any type of pointer. • In case the value of the pointer mentioned is not one allocated using these three methods then behavior of free function is undefined. Also it is undefined if the memory block being referenced by the pointer has already been deallocated using std::free or std::realloc method. • This method has no impact on the pointer it just frees the memory block, pointer keep referring to the memory block. • All the dynamic memory allocation and deallocation methods work in synchronize manner so that memory block being referred by the pointer for allocation must be free at that time. Differences in delete and free in C++
delete()
• It is an operator. • It de-allocates the memory dynamically. • It should only be used either for the pointers pointing to the memory allocated using the new operator or for a NULL pointer. • This operator calls the destructor after it destroys the allocated memory. • It is faster.
free()
• It is a library function. • It destroys the memory at the runtime. • It should only be used either for the pointers pointing to the memory allocated using malloc() or for a NULL pointer. • This function only frees the memory from the heap. It does not call the destructor. • It is comparatively slower than delete as it is a function.
Data races
Only the storage referenced by ptr is modified. No other storage locations are accessed by the call. If the function releases a unit of storage that is reused by a call to allocation functions (such as calloc or malloc), the functions are synchronized in such a way that the deallocation happens entirely before the next allocation.
Exceptions
No-throw guarantee: this function never throws exceptions. If ptr does not point to a memory block previously allocated with malloc, calloc or realloc, and is not a null pointer, it causes undefined behavior.
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
/* The free() function in C++ deallocates a block of memory previously allocated using calloc, malloc or realloc functions, making it available for further allocations code example. */ #include <iostream> #include <cstdlib> #include <cstring> using namespace std; int main() { char *ptr; ptr = (char*) malloc(10*sizeof(char)); strcpy(ptr,"Hello C++"); cout << "Before reallocating: " << ptr << endl; /* reallocating memory */ ptr = (char*) realloc(ptr,20); strcpy(ptr,"Hello, Welcome to C++"); cout << "After reallocating: " <<ptr << endl; free(ptr); /* prints a garbage value after ptr is free */ cout << endl << "Garbage Value: " << ptr; 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; }
strcpy() Function in C++
Copy string. Copies the C string pointed by source into the array pointed by destination, including the terminating null character (and stopping at that point). To avoid overflows, the size of the array pointed by destination shall be long enough to contain the same C string as source (including the terminating null character), and should not overlap in memory with source. strcpy() is a standard library function in C/C++ and is used to copy one string to another. In C it is present in string.h header file and in C++ it is present in cstring header file. It copies the whole string to the destination string. It replaces the whole string instead of appending it. It won't change the source string.
Syntax for strcpy() Function in C++
#include <cstring> char * strcpy ( char * destination, const char * source );
destination
Pointer to the destination array where the content is to be copied.
source
C string to be copied. destination is returned. After copying the source string to the destination string, the strcpy() function returns a pointer to the destination string. • This function copies the entire string to the destination string. It doesn't append the source string to the destination string. In other words, we can say that it replaces the content of destination string by the content of source string. • It does not affect the source string. The source string remains same after copying. • This function only works with C style strings and not C++ style strings i.e. it only works with strings of type char str[]; and not string s1; which are created using standard string data type available in C++ and not C.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* copy a character string from source to destination by strcpy() string function code example */ #include <cstring> #include <iostream> using namespace std; int main() { char src[20] = "I am the source."; // large enough to store content of src char dest[30] = "I am the destination."; cout << "dest[] before copy: " << dest << endl; // copy contents of src to dest strcpy(dest,src); cout << "dest[] after copy: " << dest; return 0; }
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; }
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; }


Problem takes E edges as input and outputs vertex cover of the graph, implementing the following heuristic. There is no "Polynomial" time algorithm "invented up to date" to find
First ask to enter the array size then it will ask to enter the array elements, then it will finally ask to enter a number to be search in array to check whether it is present in the array or not
Any programming language has built in data types. Data types are used to create variables or your new data types. Variable is a amount of memory that has its own name and value.
"Two dimensional" (2D) array can be made in C++ Language by using two for loops, first is outer for loop and the second one is inner for loop. Outer for Loop is responsible for rows