Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes


C++ Programming Code Examples

C++ > Computer Graphics Code Examples

Program to Find the Connected Components of an UnDirected Graph

/* Program to Find the Connected Components of an UnDirected Graph This is a C++ Program to find the connected components of the undirected graph. This can be done using depth first search */ // Implementation of Kosaraju's algorithm to print all SCCs #include <iostream> #include <list> #include <stack> using namespace std; class Graph { int V; // No. of vertices list<int> *adj; // An array of adjacency lists // Fills Stack with vertices (in increasing order of finishing times) // The top element of stack has the maximum finishing time void fillOrder(int v, bool visited[], stack<int> &Stack); // A recursive function to print DFS starting from v void DFSUtil(int v, bool visited[]); public: Graph(int V); void addEdge(int v, int w); // The main function that finds and prints strongly connected components int printSCCs(); // Function that returns reverse (or transpose) of this graph Graph getTranspose(); }; Graph::Graph(int V) { this->V = V; adj = new list<int> [V]; } // A recursive function to print DFS starting from v void Graph::DFSUtil(int v, bool visited[]) { // Mark the current node as visited and print it visited[v] = true; cout << v << " "; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFSUtil(*i, visited); } Graph Graph::getTranspose() { Graph g(V); for (int v = 0; v < V; v++) { // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) { g.adj[*i].push_back(v); } } return g; } void Graph::addEdge(int v, int w) { adj[v].push_back(w); // Add w to v's list. } void Graph::fillOrder(int v, bool visited[], stack<int> &Stack) { // Mark the current node as visited and print it visited[v] = true; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) fillOrder(*i, visited, Stack); // All vertices reachable from v are processed by now, push v to Stack Stack.push(v); } // The main function that finds and prints all strongly connected components int Graph::printSCCs() { stack<int> Stack; // Mark all the vertices as not visited (For first DFS) bool *visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; // Fill vertices in stack according to their finishing times for (int i = 0; i < V; i++) if (visited[i] == false) fillOrder(i, visited, Stack); // Create a reversed graph Graph gr = getTranspose(); // Mark all the vertices as not visited (For second DFS) for (int i = 0; i < V; i++) visited[i] = false; int count = 0; // Now process all vertices in order defined by Stack while (Stack.empty() == false) { // Pop a vertex from stack int v = Stack.top(); Stack.pop(); // Print Strongly connected component of the popped vertex if (visited[v] == false) { gr.DFSUtil(v, visited); cout << endl; } count++; } return count; } // Driver program to test above functions int main() { // Create a graph given in the above diagram Graph g(5); g.addEdge(1, 0); g.addEdge(0, 2); g.addEdge(2, 1); g.addEdge(0, 3); g.addEdge(3, 4); cout << "Following are strongly connected components in given graph \n"; if (g.printSCCs() > 1) { cout << "Graph is weakly connected."; } else { cout << "Graph is strongly connected."; } return 0; }

A program shall contain a global function named main, which is the designated start of the program in hosted environment. main() function is the entry point of any C++ program. It is the point at which execution of program is started. When a C++ program is executed, the execution control goes directly to the main() function. Every C++ program have a main() function.

In computer programming, we use the if statement to run a block code only when a certain condition is met. An if statement can be followed by an optional else statement, which executes when the boolean expression is false. There are three forms of if...else statements in C++: • if statement, • if...else statement, • if...else if...else statement, The if statement evaluates the condition inside the parentheses ( ). If the condition evaluates to true, the code inside the body of if is executed. If the condition evaluates to false, the code inside the body of if is skipped.

Access next element. Returns a reference to the top element in the stack. stack::top() function is an inbuilt function in C++ STL, which is defined in <stack> header file. top() is used to access the element at the top of the stack container. In a stack, the top element is the element that is inserted at the last or most recently inserted element. Since stacks are last-in first-out containers, the top element is the last element inserted into the stack. This member function effectively calls member back of the underlying container object. No parameter is required.

List is a popularly used sequence container. Container is an object that holds data of same type. List container is implemented as doubly linked-list, hence it provides bidirectional sequential access to it's data. List doesn't provide fast random access, it only supports sequential access in both directions. List allows insertion and deletion operation anywhere within a sequence in constant time. Elements of list can be scattered in different chunks of memory. Container stores necessary information to allow sequential access to it's data. Lists can shrink or expand as needed from both ends at run time. The storage requirement is fulfilled automatically by internal allocator. Zero sized lists are also valid. In that case list.begin() and list.end() points to same location. But behavior of calling front() or back() is undefined. To define the std::list, we have to import the <list> header file.

Every object in C++ has access to its own address through an important pointer called this pointer. The this pointer is an implicit parameter to all member functions. Therefore, inside a member function, this may be used to refer to the invoking object. Friend functions do not have a this pointer, because friends are not members of a class. Only member functions have a this pointer. In C++ programming, this is a keyword that refers to the current instance of the class. There can be 3 main usage of this keyword in C++: • It can be used to pass current object as a parameter to another method. • It can be used to refer current class instance variable. • It can be used to declare indexers. To understand 'this' pointer, it is important to know how objects look at functions and data members of a class.

An array is defined as the collection of similar type of data items stored at contiguous memory locations. Arrays are the derived data type in C++ programming language which can store the primitive type of data such as int, char, double, float, etc. It also has the capability to store the collection of derived data types, such as pointers, structure, etc. The array is the simplest data structure where each data element can be randomly accessed by using its index number. C++ array is beneficial if you have to store similar elements. For example, if we want to store the marks of a student in 6 subjects, then we don't need to define different variables for the marks in the different subject. Instead of that, we can define an array which can store the marks in each subject at the contiguous memory locations.

Return iterator to beginning. Returns an iterator pointing to the first element in the list container. Notice that, unlike member list::front, which returns a reference to the first element, this function returns a bidirectional iterator pointing to it. If the container is empty, the returned iterator value shall not be dereferenced. begin() function is used to return an iterator pointing to the first element of the list container. It is different from the front() function because the front function returns a reference to the first element of the container but begin() function returns a bidirectional iterator to the first element of the container. This function does not accept any parameter. Function returns an iterator to the beginning of the sequence container.

The pointer in C++ language is a variable, it is also known as locator or indicator that points to an address of a value. In C++, a pointer refers to a variable that holds the address of another variable. Like regular variables, pointers have a data type. For example, a pointer of type integer can hold the address of a variable of type integer. A pointer of character type can hold the address of a variable of character type. You should see a pointer as a symbolic representation of a memory address. With pointers, programs can simulate call-by-reference. They can also create and manipulate dynamic data structures. In C++, a pointer variable refers to a variable pointing to a specific address in a memory pointed by another variable.

In while loop, condition is evaluated first and if it returns true then the statements inside while loop execute, this happens repeatedly until the condition returns false. When condition returns false, the control comes out of loop and jumps to the next statement in the program after while loop. The important point to note when using while loop is that we need to use increment or decrement statement inside while loop so that the loop variable gets changed on each iteration, and at some point condition returns false. This way we can end the execution of while loop otherwise the loop would execute indefinitely. A while loop that never stops is said to be the infinite while loop, when we give the condition in such a way so that it never returns false, then the loops becomes infinite and repeats itself indefinitely.

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.

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.

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.

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.

Return iterator to end. Returns an iterator referring to the past-the-end element in the list container. The past-the-end element is the theoretical element that would follow the last element in the list container. It does not point to any element, and thus shall not be dereferenced. Because the ranges used by functions of the standard library do not include the element pointed by their closing iterator, this function is often used in combination with list::begin to specify a range including all the elements in the container. If the container is empty, this function returns the same as list::begin. This function does not accept any parameter.

Consider a situation, when we have two persons with the same name, jhon, in the same class. Whenever we need to differentiate them definitely we would have to use some additional information along with their name, like either the area, if they live in different area or their mother's or father's name, etc. Same situation can arise in your C++ applications. For example, you might be writing some code that has a function called xyz() and there is another library available which is also having same function xyz(). Now the compiler has no way of knowing which version of xyz() function you are referring to within your code.

C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of statements inside another loop. Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number of loops. The nesting level can be defined at n times. You can define any type of loop inside another loop; for example, you can define 'while' loop inside a 'for' loop. A loop inside another loop is called a nested loop. The depth of nested loop depends on the complexity of a problem. We can have any number of nested loops as required. Consider a nested loop where the outer loop runs n times and consists of another loop inside it. The inner loop runs m times. Then, the total number of times the inner loop runs during the program execution is n*m.

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.

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. No parameter passed. Function returns true if the underlying container's size is 0, false otherwise.

Allocate storage space. Default allocation functions (single-object form). A new operator is used to create the object while a delete operator is used to delete the object. When the object is created by using the new operator, then the object will exist until we explicitly use the delete operator to delete the object. Therefore, we can say that the lifetime of the object is not related to the block structure of the program.

In computer programming, loops are used to repeat a block of code. For example, when you are displaying number from 1 to 100 you may want set the value of a variable to 1 and display it 100 times, increasing its value by 1 on each loop iteration. When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop. A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

Add element at the end. Adds a new element at the end of the list container, after its current last element. The content of val is copied (or moved) to the new element. This effectively increases the container size by one. The list:push_back() function in C++ STL is used to add a new element to an existing list container. It takes the element to be added as a parameter and adds it to the list container. This function accepts a single parameter which is mandatory value. This refers to the element needed to be added to the list, list_name. This function does not return any value.

Iterators are just like pointers used to access the container elements. Iterators are one of the four pillars of the Standard Template Library or STL in C++. An iterator is used to point to the memory address of the STL container classes. For better understanding, you can relate them with a pointer, to some extent. Iterators act as a bridge that connects algorithms to STL containers and allows the modifications of the data present inside the container. They allow you to iterate over the container, access and assign the values, and run different operators over them, to get the desired result. • Iterators are used to traverse from one element to another element, a process is known as iterating through the container. • The main advantage of an iterator is to provide a common interface for all the containers type. • Iterators make the algorithm independent of the type of the container used.

#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program.

In C++, where first, the 'dictionary' is created by taking an input by the user for the words and their meanings. Next, these are stored in a "Binary Search Tree", after which the file is

The algorithm tells whether a text contains a substring which is "approximately equal" to a given pattern, where approximate equality is defined in terms of Levenshtein distance and


There are different "Preprocessor Directives" that perform different tasks. Lets categorize preprocessor directives. Inclusion directives: "#include": specifies the files to be included,


Insert x into the tree; duplicates are ignored. Remove x from the tree. Nothing is done if x is not found. Find the "smallest item" in the tree. Find the "largest item" in the tree. Find

It isn't too smart to prevent you from winning but it is worth playing it. "opening headerfile" iostream for in-out. Opening headerfile conio for clrscr(); Opening headerfile stdlib for. And


A C++ Program to "check and find" if the path between two nodes exists. By running "DFS" on given graph we can find out whether path exists between two nodes. Class represents a



C++ program performs Naive string matching without using any specific library functions. A text and a Pattern is given as input. Pattern is searched for in a text and all 'instances' of the