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++ > Data Structures and Algorithm Analysis in C++ Code Examples

Concordance program not using STL

/* Concordance program not using STL */ #include <iostream.h> #include <fstream.h> #ifdef unix #include <strstream.h> #else #include <strstrea.h> // <strstream.h> on UNIX machines #endif #include "mystring.h" #include "AvlTree.h" #include "LinkedList.h" struct WordEntry { WordEntry( ) : word( "" ), lines( NULL ) { } bool operator<( const WordEntry & rhs ) const { return word < rhs.word; } bool operator==( const WordEntry & rhs ) const { return word == rhs.word; } string word; List<int> *lines; ListItr<int> *listEnd; }; ostream & operator<<( ostream & out, const WordEntry & rhs ) { out << rhs.word << ": "; if( rhs.lines != NULL && !rhs.lines->isEmpty( ) ) { ListItr<int> itr = rhs.lines->first( ); out << '\t' << itr.retrieve( ); for( itr.advance( ); !itr.isPastEnd( ); itr.advance( ) ) out << ", " << itr.retrieve( ); } return out; } int main( int argc, char *argv[ ] ) { if( argc != 2 ) { cerr << "Usage: " << argv[ 0 ] << " filename" << endl; return 1; } ifstream inFile( argv[ 1 ] ); if( !inFile ) { cerr << "Cannot open " << argv[ 1 ] << endl; return 1; } const WordEntry ITEM_NOT_FOUND; // "" is the word member AvlTree<WordEntry> wordMap( ITEM_NOT_FOUND ); string oneLine; WordEntry entry; // Read the words; add them to wordMap for( int lineNum = 1; getline( inFile, oneLine ); lineNum++ ) { istrstream st( (char *) oneLine.c_str( ) ); // Deprecated form of string streams while( st >> entry.word ) { const WordEntry & match = wordMap.find( entry ); if( match == ITEM_NOT_FOUND ) { entry.lines = new List<int>; entry.lines->insert( lineNum, entry.lines->zeroth( ) ); entry.listEnd = new ListItr<int>( entry.lines->first( ) ); wordMap.insert( entry ); } else { match.lines->insert( lineNum, *match.listEnd ); match.listEnd->advance( ); } } } wordMap.printTree( ); return 0; }

Get line from stream into string. The cin is an object which is used to take input from the user but does not allow to take the input in multiple lines. To accept the multiple lines, we use the getline() function. It is a pre-defined function defined in a <string.h> header file used to accept a line or a string from the input stream until the delimiting character is encountered. Extracts characters from is and stores them into str until the delimitation character delim is found (or the newline character, '\n', for (2)). The extraction also stops if the end of file is reached in is or if some other error occurs during the input operation. If the delimiter is found, it is extracted and discarded (i.e. it is not stored and the next input operation will begin after it).

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.

In C++, classes and structs are blueprints that are used to create the instance of a class. Structs are used for lightweight objects such as Rectangle, color, Point, etc. Unlike class, structs in C++ are value type than reference type. It is useful if you have data that is not intended to be modified after creation of struct. C++ Structure is a collection of different data types. It is similar to the class that holds different types of data. A structure is declared by preceding the struct keyword followed by the identifier(structure name). Inside the curly braces, we can declare the member variables of different types.

Enumeration is a user defined datatype in C/C++ language. It is used to assign names to the integral constants which makes a program easy to read and maintain. The keyword "enum" is used to declare an enumeration. It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST) etc. The C++ enum constants are static and final implicitly. C++ Enums can be thought of as classes that have fixed set of constants.

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.

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.

Advance iterator. Advances the iterator it by n element positions. If it is a random-access iterator, the function uses just once operator+ or operator-. Otherwise, the function uses repeatedly the increase or decrease operator (operator++ or operator--) until n elements have been advanced. This function does not return any value.

Standard output stream for errors. Object of class ostream that represents the standard error stream oriented to narrow characters (of type char). It corresponds to the C stream stderr. The standard error stream is a destination of characters determined by the environment. This destination may be shared by more than one standard object (such as cout or clog). As an object of class ostream, characters can be written to it either as formatted data using the insertion operator (operator<<) or as unformatted data, using member functions such as write. The object is declared in header <iostream> with external linkage and static duration: it lasts the entire duration of the program.

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

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

Get C string equivalent. Returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object. The basic_string::c_str() is a builtin function in C++ which returns a pointer to an array that contains a null-terminated sequence of characters representing the current value of the basic_string object. This array includes the same sequence of characters that make up the value of the basic_string object plus an additional terminating null-character at the end. This array includes the same sequence of characters that make up the value of the string object plus an additional terminating null-character ('\0') at the end. This function does not accept any parameter. Function returns a pointer to the c-string representation of the string object's value.

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.

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

In C++ programming we are using the iostream standard library, it provides cin and cout methods for reading from input and writing to output respectively. To read and write from a file we are using the standard C++ library called fstream. Let us see the data types define in fstream library is: • ofstream: This data type represents the output file stream and is used to create files and to write information to files. • ifstream: This data type represents the input file stream and is used to read information from files. • fstream: This data type represents the file stream generally, and has the capabilities of both ofstream and ifstream which means it can create files, write information to files, and read information from files.

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


To declare such a function, precede its name with * and &. In the body of the function, you can do whatever is appropriate. An important rule with this type of "function" is that it must





2 const variables row & col are used to define size. If we do not make both const then error found because without "const reserve word" they are behaving as variable. Before placing

In the program, the decimal number is stored in the variable decimalNumber and passed to function decimalToOctal(). Function converts the 'decimal number' passed to its equivalent