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++ > Games Code Examples


/* Maze */ #include #include #include "maze.h" // =============================> Maze Objects <==================== // Maze object data members: // int _max_row; // int _max_col; // char _map[MAX_MAZE_DIM+1][MAX_MAZE_DIM+1]; // ============================> report_err <======================= static void report_err(const char* message) { cout << "FATAL ERROR (Maze): " << message << endl; exit(1); } // ========================> member functions <===================== // ========================> Constructors <================== Maze::Maze() { *this = Maze(7,7); } Maze::Maze(int rows, int cols) { if (rows > MAX_MAZE_DIM || cols > MAX_MAZE_DIM) report_err("Attempted to create overly large Maze"); _max_row = rows; _max_col = cols; for(int row = 1; row <= rows; row++) for(int col = 1; col <= cols; col++) _map[row][col] = '.'; } // =======================> max_row <======================== int Maze::max_row() const { return _max_row; } // ======================> max_col <========================= int Maze::max_col() const { return _max_col; } // =====================> is_open <========================== int Maze::is_open(int i, int j) const // PRE: VALID_POS(i, j) // POST: FCTVAL == position (i, j) of this maze is open (contains a '.') { if (i < 1 || i > _max_row) report_err("Attempted to check cell row outside of maze dimensions"); if (j < 1 || j > _max_col) report_err("Attempted to check cell column outside of maze dimensions"); if (_map[i][j] == '.') // if current spot in maze is passible return (1); // return 1 ==> TRUE else return (0); } // ====================> mark <============================== void Maze::mark(int row, int col, char marker) { if (!is_open(row,col)) report_err("Attempt to mark an non-open Maze cell"); _map[row][col] = marker; } // ===================> unmark <============================= void Maze::unmark(int row, int col) // PRE: VALID_POS(row, col) && // _map[row][col] != '*' // POST: is_open(row, col) { if (_map[row][col] != '*') _map[row][col] = '.'; // reset current spot in maze to passible return; } // ===================> stream output <====================== ostream& operator<<(ostream& stream, Maze m) { for(int row = 1; row <= m._max_row; row++) { for(int col = 1; col <= m._max_col; col++) stream.put(m._map[row][col]); stream << endl; } stream << flush; return stream; } // ==================> stream input <======================= istream& operator>>(istream& stream, Maze& m) { char ch; for(int row = 1; row <= m._max_row; row++) { for(int col = 1; col <= m._max_col; col++) { stream.get(ch); if (ch == '.' || ch == ' ') m._map[row][col] = '.'; else m._map[row][col] = '*'; } stream.ignore(50,'\n'); } return stream; }

Get characters. Extracts characters from the stream, as unformatted input. The get() function is used to read a character(at a time) from a file. The classes istream and ostream define two member functions get(), put() respectively to handle the single character input/output operations. There are two types of get() functions. Both get(char *) and get(void) prototype can be used to fetch a character including the blank space,tab and newline character. The get(char *) version assigns the input character to its argument and the get(void) version returns the input character. Since these functions are members of input/output Stream classes, these must be invoked using appropriate objects.

Static is a keyword in C++ used to give special characteristics to an element. Static elements are allocated storage only once in a program lifetime in static storage area. And they have a scope till the program lifetime. In C++, static is a keyword or modifier that belongs to the type not instance. So instance is not required to access the static members. In C++, static can be field, method, constructor, class, properties, operator and event. Advantage of C++ static keyword: Memory efficient. Now we don't need to create instance for accessing the static members, so it saves memory. Moreover, it belongs to the type, so it will not get memory each time when instance is created.

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

The cout is a predefined object of ostream class. It is connected with the standard output device, which is usually a display screen. The cout is used in conjunction with stream insertion operator (<<) to display the output on a console. On most program environments, the standard output by default is the screen, and the C++ stream object defined to access it is cout. The "c" in cout refers to "character" and "out" means "output". Hence cout means "character output". The cout object is used along with the insertion operator << in order to display a stream of characters.

A return statement ends the processing of the current function and returns control to the caller of the function. A value-returning function should include a return statement, containing an expression. If an expression is not given on a return statement in a function declared with a non-void return type, the compiler issues an error message. If the data type of the expression is different from the function return type, conversion of the return value takes place as if the value of the expression were assigned to an object with the same function return type.

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

The exit function terminates the program normally. Automatic objects are not destroyed, but static objects are. Then, all functions registered with atexit are called in the opposite order of registration. The code is returned to the operating system. An exit code of 0 or EXIT_SUCCESS means successful completion. If code is EXIT_FAILURE, an indication of program failure is returned to the operating system. Other values of code are implementation-defined. Calls all functions registered with the atexit() function, and destroys C++ objects with static storage duration, all in last-in-first-out (LIFO) order. C++ objects with static storage duration are destroyed in the reverse order of the completion of their constructor. (Automatic objects are not destroyed as a result of calling exit().)

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.

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.

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.

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.

Extract and discard characters. Extracts characters from the input sequence and discards them, until either n characters have been extracted, or one compares equal to delim. The function also stops extracting characters if the end-of-file is reached. If this is reached prematurely (before either extracting n characters or finding delim), the function sets the eofbit flag. Internally, the function accesses the input sequence by first constructing a sentry object (with noskipws set to true). Then (if good), it extracts characters from its associated stream buffer object as if calling its member functions sbumpc or sgetc, and finally destroys the sentry object before returning. Function returns the istream object (*this).

Check if file is open. Returns whether the stream is currently associated to a file. Streams can be associated to files by a successful call to member open or directly on construction, and disassociated by calling close or on destruction. The file association of a stream is kept by its internal stream buffer: Internally, the function calls rdbuf()->is_open(). The function does not accept any parameter. Function returns true if a file is open and associated with this stream object.

The function in C++ language is also known as procedure or subroutine in other programming languages. To perform any task, we can create function. A function can be called many times. It provides modularity and code reusability. Functions are used to provide modularity to a program. Creating an application using function makes it easier to understand, edit, check... Function declaration, is done to tell the compiler about the existence of the function. Function's return type, its name & parameter list is mentioned. Function body is written in its definition. Functions are called by their names. If the function is without argument, it can be called directly using its name. But for functions with arguments, we have two ways to call them:

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:

An array is a collection of data items, all of the same type, accessed using a common name. A one-dimensional array is like a list; A two dimensional array is like a table; The C++ language places no limits on the number of dimensions in an array, though specific implementations may. Some texts refer to one-dimensional arrays as vectors, two-dimensional arrays as matrices, and use the general term arrays when the number of dimensions is unspecified or unimportant. (2D) array in C++ programming is also known as matrix. A matrix can be represented as a table of rows and columns. In C/C++, we can define multi dimensional arrays in simple words as array of arrays. Data in multi dimensional arrays are stored in tabular form (in row major order).

Put character. Inserts character c into the stream. Internally, the function accesses the output sequence by first constructing a sentry object. Then (if good), it inserts c into its associated stream buffer object as if calling its member function sputc, and finally destroys the sentry object before returning. Function returns the ostream object (*this).