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

C++ Program to Find Largest Rectangular Area in a Histogram

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
/* C++ Program to Find Largest Rectangular Area in a Histogram */ #include <iostream> #include <cmath> #include <climits> #include <algorithm> #define max(x, y, z) max(max(x, y) , z) using namespace std; /* get minimum of two numbers in hist[] */ int minVal(int *hist, int i, int j) { if (i == -1) return j; if (j == -1) return i; return (hist[i] < hist[j])? i : j; } /* get the middle index from corner indexes. */ int getMid(int s, int e) { return s + (e -s)/2; } /* get the index of minimum value in a given range of indexes. */ int RMQUtil(int *hist, int *st, int ss, int se, int qs, int qe, int index) { if (qs <= ss && qe >= se) return st[index]; if (se < qs || ss > qe) return -1; int mid = getMid(ss, se); return minVal(hist, RMQUtil(hist, st, ss, mid, qs, qe, 2 * index + 1), RMQUtil(hist, st, mid + 1, se, qs, qe, 2 * index + 2)); } /* Return index of minimum element in range from index qs to qe */ int RMQ(int *hist, int *st, int n, int qs, int qe) { if (qs < 0 || qe > n - 1 || qs > qe) { cout << "Invalid Input"; return -1; } return RMQUtil(hist, st, 0, n - 1, qs, qe, 0); } /* constructs Segment Tree for hist[ss..se]. */ int constructSTUtil(int hist[], int ss, int se, int *st, int si) { if (ss == se) return (st[si] = ss); int mid = getMid(ss, se); st[si] = minVal(hist, constructSTUtil(hist, ss, mid, st, si * 2 + 1), constructSTUtil(hist, mid + 1, se, st, si * 2 + 2)); return st[si]; } /* construct segment tree from given array. */ int *constructST(int hist[], int n) { int x = (int)(ceil(log2(n))); int max_size = 2 * (int)pow(2, x) - 1; int *st = new int[max_size]; constructSTUtil(hist, 0, n - 1, st, 0); return st; } /* find the maximum rectangular area. */ int getMaxAreaRec(int *hist, int *st, int n, int l, int r) { if (l > r) return INT_MIN; if (l == r) return hist[l]; int m = RMQ(hist, st, n, l, r); return max (getMaxAreaRec(hist, st, n, l, m - 1), getMaxAreaRec(hist, st, n, m + 1, r), (r - l + 1) * (hist[m])); } /* find max area */ int getMaxArea(int hist[], int n) { int *st = constructST(hist, n); return getMaxAreaRec(hist, st, n, 0, n - 1); } /* Main */ int main() { int hist[] = {6, 1, 5, 4, 5, 2, 6}; int n = sizeof(hist)/sizeof(hist[0]); cout << "Maximum area is " << getMaxArea(hist, n)<<endl; 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++
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; }
Math ceil() Function in C++
Round up value. Rounds x upward, returning the smallest integral value that is not less than x. The ceil function returns the smallest possible integer value which is equal to the value or greater than that. This function is declared in "cmath" header file in C++ language. It takes single value whoes ceil value is to be calculated. The datatype of variable should be double/float/long double only.
Syntax for Math ceil() Function in C++
#include <cmath> double ceil (double x); float ceil (float x); long double ceil (long double x); double ceil (T x); // additional overloads for integral types
Value to round up. Function returns the smallest integral value that is not less than x (as a floating-point value). Additional overloads are provided in this header (<cmath>) for the integral types: These overloads effectively cast x to a double before calculations (defined for T being any integral type). In mathematics and computer science, the floor and ceiling functions map a real number to the greatest preceding or the least succeeding integer, 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 34 35 36 37
/* ceil() function returns the smallest integer that is greater than or equal to x (i.e : rounds up the nearest integer). */ /* round the value to the nearest integer which is not less than the given value by ceil() function code example. */ #include <iostream> #include <math.h> using namespace std; int main(int argc, const char * argv[]) { // Positive ∞ infinite value cout << "The ceiling value of inf is " << ceil(std::numeric_limits<float>::infinity()) << endl; // Negative ∞ infinite value cout << "The ceiling value of -inf is " << ceil(-std::numeric_limits<float>::infinity()) << endl; // Positive floating point value cout << "The ceiling value of -1.5698 is " << ceil(-1.5698) << endl; cout << "The ceiling value of -1.3093 is " << ceil(-1.3093) << endl; cout << "The ceiling value of -1.0087 is " << ceil(-1.0087) << endl; cout << "The ceiling value of -1.1038 is " << ceil(-1.1038) << endl; cout << "The ceiling value of -1.9573 is " << ceil(-1.9573) << endl; cout << "The ceiling value of -1.7462 is " << ceil(-1.7462) << endl; cout << "The ceiling value of -1.6427 is " << ceil(-1.6427) << endl; cout << "The ceiling value of -1.4128 is " << ceil(-1.4128) << endl; cout << "The ceiling value of -1.8099 is " << ceil(-1.8099) << endl; cout << "The ceiling value of -1.2743 is " << ceil(-1.2743) << endl; cout << "The ceiling value of -2.0001 is " << ceil(-2.0001) << endl; 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; }
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; }
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 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 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; }
#define Directive in C++
In the C++ Programming Language, the #define directive allows the definition of macros within your source code. These macro definitions allow constant values to be declared for use throughout your code. Macro definitions are not variables and cannot be changed by your program code like variables. You generally use this syntax when creating constants that represent numbers, strings or expressions. The syntax for creating a constant using #define in the C++ is: #define token value
Syntax for #define Directive in C++
#define macro-name replacement-text
• Using #define to create Macros Macros also follow the same structure as Symbolic Constants; however, Macros allow arguments to be included in the identifier:
#define SQUARE_AREA(l) ((l) * (l))
Unlike in functions, the argument here is enclosed in parenthesis in the identifier and does not have a type associated with it. Before compilation, the compiler will replace every instance of SQUARE_AREA(l) by ((l) * (l)), where l can be any expression. • Conditional Compilation There are several directives, which can be used to compile selective portions of your program's source code. This process is called conditional compilation. The conditional preprocessor construct is much like the 'if' selection structure. Consider the following preprocessor code:
#ifndef NULL #define NULL 0 #endif
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
/* #define directive in C++ language */ #include <bits/stdc++.h> using namespace std; void func1(); void func2(); #pragma startup func1 #pragma exit func2 void func1() { cout << "Inside func1()\n"; } void func2() { cout << "Inside func2()\n"; } int main() { void func1(); void func2(); cout << "Inside main()\n"; return 0; }
What is an Array in C++ Language
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. By using the array, we can access the elements easily. Only a few lines of code are required to access the elements of the array.
Properties of Array
The array contains the following properties. • Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes. • Elements of the array are stored at contiguous memory locations where the first element is stored at the smallest memory location. • Elements of the array can be randomly accessed since we can calculate the address of each element of the array with the given base address and the size of the data element.
Advantage of C++ Array
• 1) Code Optimization: Less code to the access the data. • 2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily. • 3) Ease of sorting: To sort the elements of the array, we need a few lines of code only. • 4) Random Access: We can access any element randomly using the array.
Disadvantage of C++ Array
• 1) Allows a fixed number of elements to be entered which is decided at the time of declaration. Unlike a linked list, an array in C++ is not dynamic. • 2) Insertion and deletion of elements can be costly since the elements are needed to be managed in accordance with the new memory allocation.
Declaration of C++ Array
To declare an array in C++, a programmer specifies the type of the elements and the number of elements required by an array as follows
type arrayName [ arraySize ];
This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C++ data type. For example, to declare a 10-element array called balance of type double, use this statement
double balance[10];
Here balance is a variable array which is sufficient to hold up to 10 double numbers.
Initializing Arrays
You can initialize an array in C++ either one by one or using a single statement as follows
double balance[5] = {850, 3.0, 7.4, 7.0, 88};
The number of values between braces { } cannot be larger than the number of elements that we declare for the array between square brackets [ ]. If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write
double balance[] = {850, 3.0, 7.4, 7.0, 88};
Accessing Array Elements
An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array.
double salary = balance[9];
The above statement will take the 10th element from the array and assign the value to salary variable.
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
/* arrays in C++ Language */ #include <iostream> using namespace std; int main() { // initialize an array without specifying size double numbers[] = {7, 5, 6, 12, 35, 27}; double sum = 0; double count = 0; double average; cout << "The numbers are: "; // print array elements // use of range-based for loop for (const double &n : numbers) { cout << n << " "; // calculate the sum sum += n; // count the no. of array elements ++count; } // print the sum cout << "\nTheir Sum = " << sum << endl; // find the average average = sum / count; cout << "Their Average = " << average << 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; }
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; }
Math Library pow() Function in C++
Raise to power. The pow() function returns the result of the first argument raised to the power of the second argument. This function is defined in the cmath header file. pow() function is a library function of cmath header, it is used to find the raise to the power, it accepts two arguments and returns the first argument to the power of the second argument. power = baseexponent
Syntax for Math pow() Function in C++
#include<cmath> double pow (double base , double exponent); float pow (float base , float exponent); long double pow (long double base, long double exponent); double pow (Type1 base , Type2 exponent); // additional overloads
Base value
Exponent value Additional overloads are provided in this header (<cmath>) for other combinations of arithmetic types (Type1 and Type2): These overloads effectively cast its arguments to double before calculations, except if at least one of the arguments is of type long double (in which case both are casted to long double instead). This function is also overloaded in <complex> and <valarray>. Function returns the result of raising base to the power exponent. If the base is finite negative and the exponent is finite but not an integer value, it causes a domain error. If both base and exponent are zero, it may also cause a domain error on certain implementations. If base is zero and exponent is negative, it may cause a domain error or a pole error (or none, depending on the library implementation). The function may also cause a range error if the result is too great or too small to be represented by a value of the return type.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/* get base raised to the power exponent by pow() function */ // CPP program code example to illustrate power function #include <bits/stdc++.h> using namespace std; int main() { double x = 6.1, y = 4.8; // Storing the answer in result. double result = pow(x, y); // printing the result upto 2 // decimal place cout << fixed << setprecision(2) << result << endl; return 0; }
Standard end line (endl) in C++
A predefined object of the class called iostream class is used to insert the new line characters while flushing the stream is called endl in C++. This endl is similar to \n which performs the functionality of inserting new line characters but it does not flush the stream whereas endl does the job of inserting the new line characters while flushing the stream. Hence the statement cout<<endl; will be equal to the statement cout<< '\n' << flush; meaning the new line character used along with flush explicitly becomes equivalent to the endl statement in C++.
Syntax for end line (endl) in C++
cout<< statement to be executed <<endl;
Whenever the program is writing the output data to the stream, all the data will not be written to the terminal at once. Instead, it will be written to the buffer until enough data is collected in the buffer to output to the terminal. But if are using flush in our program, the entire output data will be flushed to the terminal directly without storing anything in the buffer. Whenever there is a need to insert the new line character to display the output in the next line while flushing the stream, we can make use of endl in C++. Whenever there is a need to insert the new line character to display the output in the next line, we can make use of endl in '\n' character but it does not do the job of flushing the stream. So if we want to insert a new line character along with flushing the stream, we make use of endl in C++. Whenever the program is writing the output data to the stream, all the data will not be written to the terminal at once. Instead, it will be written to the buffer until enough data is collected in the buffer to output to the terminal. • It is a manipulator. • It doesn't occupy any memory. • It is a keyword and would not specify any meaning when stored in a string. • We cannot write 'endl' in between double quotations. • It is only supported by C++. • It keeps flushing the queue in the output buffer throughout the process.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* Standard end line (endl) in C++ language */ //The header file iostream is imported to enable us to use cout in the program #include <iostream> //a namespace called std is defined using namespace std; //main method is called int main( ) { //cout is used to output the statement cout<< "Welcome to "; //cout is used to output the statement along with endl to start the next statement in the new line and flush the output stream cout<< "C#"<<endl; //cout is used to output the statement along with endl to start the next statement in the new line and flush the output stream cout<< "Learning is fun"<<endl; }
Namespaces in C++ Language
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. A namespace is designed to overcome this difficulty and is used as additional information to differentiate similar functions, classes, variables etc. with the same name available in different libraries. Using namespace, you can define the context in which names are defined. In essence, a namespace defines a scope.
Defining a Namespace
A namespace definition begins with the keyword namespace followed by the namespace name as follows:
namespace namespace_name { // code declarations }
To call the namespace-enabled version of either function or variable, prepend (::) the namespace name as follows:
name::code; // code could be variable or function.
Using Directive
You can also avoid prepending of namespaces with the using namespace directive. This directive tells the compiler that the subsequent code is making use of names in the specified namespace.
Discontiguous Namespaces
A namespace can be defined in several parts and so a namespace is made up of the sum of its separately defined parts. The separate parts of a namespace can be spread over multiple files. So, if one part of the namespace requires a name defined in another file, that name must still be declared. Writing a following namespace definition either defines a new namespace or adds new elements to an existing one:
namespace namespace_name { // code declarations }
Nested Namespaces
Namespaces can be nested where you can define one namespace inside another name space as follows:
namespace namespace_name1 { // code declarations namespace namespace_name2 { // code declarations } }
• Namespace is a feature added in C++ and not present in C. • A namespace is a declarative region that provides a scope to the identifiers (names of the types, function, variables etc) inside it. • Multiple namespace blocks with the same name are allowed. All declarations within those blocks are declared in the named scope. • Namespace declarations appear only at global scope. • Namespace declarations can be nested within another namespace. • Namespace declarations don't have access specifiers. (Public or private) • No need to give semicolon after the closing brace of definition of namespace. • We can split the definition of namespace over several units.
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
/* namespaces in C++ language */ // A C++ code to demonstrate that we can define // methods outside namespace. #include <iostream> using namespace std; // Creating a namespace namespace ns { void display(); class happy { public: void display(); }; } // Defining methods of namespace void ns::happy::display() { cout << "ns::happy::display()\n"; } void ns::display() { cout << "ns::display()\n"; } // Driver code int main() { ns::happy obj; ns::display(); obj.display(); 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 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.
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.
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; }
Structures in C++ Language
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.
Syntax for Structures in C++
struct structureName{ member1; member2; member3; . . . memberN; };
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. Consider the following situation:
struct Teacher { char name[20]; int id; int age; }
In the above case, Teacher is a structure contains three variables name, id, and age. When the structure is declared, no memory is allocated. When the variable of a structure is created, then the memory is allocated. Let's understand this scenario. Structures in C++ can contain two types of members: • Data Member: These members are normal C++ variables. We can create a structure with variables of different data types in C++. • Member Functions: These members are normal C++ functions. Along with variables, we can also include functions inside a structure declaration. Structure variable can be defined as: Teacher s; Here, s is a structure variable of type Teacher. When the structure variable is created, the memory will be allocated. Teacher structure contains one char variable and two integer variable. Therefore, the memory for one char variable is 1 byte and two ints will be 2*4 = 8. The total memory occupied by the s variable is 9 byte. The variable of the structure can be accessed by simply using the instance of the structure followed by the dot (.) operator and then the field of the structure.
s.id = 4;
We are accessing the id field of the structure Teacher by using the dot(.) operator and assigns the value 4 to the id field. In C++, the struct keyword is optional before in declaration of a variable. In C, it is mandatory.
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
/* Structure is a collection of variables of different data types under a single name. It is similar to a class in that, both holds a collecion of data of different data types. */ #include <iostream> using namespace std; struct Person { char name[50]; int age; float salary; }; int main() { Person p1; cout << "Enter Full name: "; cin.get(p1.name, 50); cout << "Enter age: "; cin >> p1.age; cout << "Enter salary: "; cin >> p1.salary; cout << "\nDisplaying Information." << endl; cout << "Name: " << p1.name << endl; cout <<"Age: " << p1.age << endl; cout << "Salary: " << p1.salary; return 0; }

Any words in a line after "//" are "ignored" by the compiler. if you want to write a comment about 'what is about code doing' you have to write it in the following way: The "//" symbols
This is a C++ Program to find 'Prime number' between the given range using 'Wheel Seive' method. "Wheel Factorization" is a graphical method for manually performing preliminary
If the reversed integer is equal to the integer then, that number is a palindrome if not that number is not a palindrome. In program, use is asked to enter a 'positive number' which is
To add two numbers using pointer in the C++, you have to enter the 2 number, then make 2 'pointer' type variable of same type say *ptr1 and *ptr2 to initialize the address of both the