Happy Codings - Programming Code Examples

C++ Programming Code Examples

C++ > Data Structures Code Examples

C++ Program to Implement Bloom Filter

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 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
/* C++ Program to Implement Bloom Filter */ #include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> using namespace std; #define POLYNOMIAL 0x04C11DB7L // Standard CRC-32 polynomial #define M 32 // Number of bits in the Bloom filter #define K 4 // Number of bits set per mapping in filter typedef unsigned short int word16; typedef unsigned int word32; static word32 CrcTable[256]; // Table of 8-bit CRC32 remainders char BFilter[M / 8]; // Bloom filter array of M/8 bytes word32 NumBytes; // Number of bytes in Bloom filter void gen_crc_table(void); word32 update_crc(word32 crc_accum, char *data_ptr, word32 data_size); void mapBloom(word32 hash); int testBloom(word32 hash); /* Main Function */ int main() { FILE *fp1; FILE *fp2; char inFile1[256]; char inFile2[256]; char inString[1024]; word32 crc32; int retCode; word32 i; cout<<"------------------------------------------ "<<endl; cout<<"- Program to implement a general Bloom filter\n"; cout<<"------------------------------------------ "<<endl; // Determine number of bytes in Bloom Filter NumBytes = M / 8; if ((M % 8) != 0) { cout<<"*** ERROR - M value must be divisible by 8 \n"; exit(1); } // Clear the Bloom filter for (i = 0; i < NumBytes; i++) BFilter[i] = 0x00; // Initialize the CRC32 table gen_crc_table(); cout<<"File name of input list to add to filter ===========> "; cin>>inFile1; fp1 = fopen(inFile1, "r"); if (fp1 == NULL) { cout<<"ERROR in opening input file #1 ("<<inFile1<<") *** \n"; exit(1); } cout<<"File name of input list to check for match =========> "; cin>>inFile2; fp2 = fopen(inFile2, "r"); if (fp2 == NULL) { cout<<"ERROR in opening input file #1 ("<<inFile2<<") *** \n"; exit(1); } // Read input file #1 and map each string to Bloom filter while (1) { fgets(inString, 1024, fp1); if (feof(fp1)) break; for (i = 0; i < K; i++) { crc32 = update_crc(i, inString, strlen(inString)); mapBloom(crc32); } } fclose(fp1); // Output the Bloom filter cout<<"-------------------------------------------------------- \n"; cout<<"Bloom filter is (M = "<<M<<" bits and K = "<<K<<" mappings)... \n"; for (i = 0; i < NumBytes; i++) printf("%2d", i); cout<<endl; for (i = 0; i < NumBytes; i++) printf("%02X", BFilter[i]); cout<<endl; // Output results header cout<<"-----------------------------------------------------\n"; cout<<"Matching strings are... \n"; while(1) { fgets(inString, 1024, fp2); if (feof(fp2)) break; for (i = 0; i < K; i++) { crc32 = update_crc(i, inString, strlen(inString)); retCode = testBloom(crc32); if (retCode == 0) break; } if (retCode == 1) cout<<inString; } fclose(fp2); } /* Function to initialize CRC32 table */ void gen_crc_table(void) { register word32 crc_accum; register word16 i, j; // Initialize the CRC32 8-bit look-up table for (i = 0; i < 256; i++) { crc_accum = ((word32) i << 24); for (j = 0; j < 8; j++) { if (crc_accum & 0x80000000L) crc_accum = (crc_accum << 1) ^ POLYNOMIAL; else crc_accum = (crc_accum << 1); } CrcTable[i] = crc_accum; } } /* Function to generate CRC32 */ word32 update_crc(word32 crc_accum, char *data_blk_ptr, word32 data_blk_size) { register word32 i, j; for (j = 0; j < data_blk_size; j++) { i = ((int) (crc_accum >> 24) ^ *data_blk_ptr++) & 0xFF; crc_accum = (crc_accum << 8) ^ CrcTable[i]; } crc_accum = ~crc_accum; return crc_accum; } /* Function to map hash into Bloom filter */ void mapBloom(word32 hash) { int tempInt; int bitNum; int byteNum; unsigned char mapBit; tempInt = hash % M; byteNum = tempInt / 8; bitNum = tempInt % 8; mapBit = 0x80; mapBit = mapBit >> bitNum; // Map the bit into the Bloom filter BFilter[byteNum] = BFilter[byteNum] | mapBit; } /* Function to test for a Bloom filter match */ int testBloom(word32 hash) { int tempInt; int bitNum; int byteNum; unsigned char testBit; int retCode; tempInt = hash % M; byteNum = tempInt / 8; bitNum = tempInt % 8; testBit = 0x80; testBit = testBit >> bitNum; if (BFilter[byteNum] & testBit) retCode = 1; else retCode = 0; return retCode; }
Nested Loop Statement in C++
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.
Syntax for Nested Loop Statement in C++
Outer_loop { Inner_loop { // inner loop statements. } // outer loop statements. }
Outer_loop and Inner_loop are the valid loops that can be a 'for' loop, 'while' loop or 'do-while' loop.
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
/* nested loop statement in C++ language */ // C++ program that uses nested for loop to print a 2D matrix #include <bits/stdc++.h> using namespace std; #define ROW 3 #define COL 3 // Driver program int main() { int i, j; // Declare the matrix int matrix[ROW][COL] = { { 4, 8, 12 }, { 16, 20, 24 }, { 28, 32, 36 } }; cout << "Given matrix is \n"; // Print the matrix using nested loops for (i = 0; i < ROW; i++) { for (j = 0; j < COL; j++) cout << matrix[i][j]; cout << "\n"; } return 0; }
fclose() Function in C++
Close file. Closes the file associated with the stream and disassociates it. Closes the given file stream. Any unwritten buffered data are flushed to the OS. Any unread buffered data are discarded. Whether or not the operation succeeds, the stream is no longer associated with a file, and the buffer allocated by std::setbuf or std::setvbuf, if any, is also disassociated and deallocated if automatic allocation was used. All internal buffers associated with the stream are disassociated from it and flushed: the content of any unwritten output buffer is written and the content of any unread input buffer is discarded. Even if the call fails, the stream passed as parameter will no longer be associated with the file nor its buffers.
Syntax for fclose() Function in C++
#include <cstdio> int fclose ( FILE * stream );
stream
Pointer to a FILE object that specifies the stream to be closed. If the stream is successfully closed, a zero value is returned. On failure, EOF is returned.
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
/* The fclose() function takes a single argument, a file stream which is to be closed. All the data that are buffered but not written are flushed to the OS and all unread buffered data are discarded. Even if the operation fails, the stream is no longer associated with the file. If the file pointer is used after fclose() is executed, the behaviour is undefined. */ /* Close file by fclose() function code example */ #include <iostream> #include <cstdio> using namespace std; int main() { FILE *fp; fp = fopen("file.txt","w"); char str[20] = "Hello World!"; if (fp == NULL) { cout << "Error opening file"; exit(1); } fprintf(fp,"%s",str); fclose(fp); cout << "File closed successfully"; 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
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
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; }
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; }
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; }
Enumeration (or enum) in C++
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.
Syntax for enum in C++
enum enum_name{const1, const2, ....... };
enum_name
Any name given by user
const1, const2
These are values of type flag The enum keyword is also used to define the variables of enum type. There are two ways to define the variables of enum type as follows
enum colors{red, black}; enum suit{heart, diamond=8, spade=3, club};
Points to remember for C++ Enum: • enum improves type safety • enum can be easily used in switch • enum can be traversed • enum can have fields, constructors and methods • enum may implement many interfaces but cannot extend any class because it internally extends Enum class
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
/* Enum is a user defined data type where we specify a set of values for a variable and the variable can only take one out of a small set of possible values. We use enum keyword to define a Enumeration. */ #include <bits/stdc++.h> using namespace std; int main() { // Defining enum Gender enum Gender { Male, Female }; // Creating Gender type variable Gender gender = Male; switch (gender) { case Male: cout << "Gender is Male"; break; case Female: cout << "Gender is Female"; break; default: cout << "Value can be Male or Female"; } return 0; }
strlen() Function in C++
Get string length. Returns the length of the C string str. C++ strlen() is an inbuilt function that is used to calculate the length of the string. It is a beneficial method to find the length of the string. The strlen() function is defined under the string.h header file. The strlen() takes a null-terminated byte string str as its argument and returns its length. The length does not include a null character. If there is no null character in the string, the behavior of the function is undefined.
Syntax for strlen() Function in C++
#include <cstring> size_t strlen ( const char * str );
str
a string passed to this function, whose length needs to be found. Here str is the string variable of whose we have to find the length. It takes one parameter which is a pointer that points to the null-terminated byte string. The string is terminated by a null character. If a null character does not terminate it, then the behavior is undefined. It returns an integer giving the length of the passed string. Function returns the length of string. While calculating the total length of a String, the character at the first index is counted as 1 and not 0, i.e. one-based index . The function strlen returns the total number of characters actually present in the char[] and not the total number of character it can hold.
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
/* return the length of the C string str by strlen() function code example */ #include <cstring> #include <iostream> using namespace std; int main() { char str1[] = "This a string"; char str2[] = "This is another string"; // find lengths of str1 and str2 // size_t return value converted to int int len1 = strlen(str1); int len2 = strlen(str2); cout << "Length of str1 = " << len1 << endl; cout << "Length of str2 = " << len2 << endl; if (len1 > len2) cout << "str1 is longer than str2"; else if (len1 < len2) cout << "str2 is longer than str1"; else cout << "str1 and str2 are of equal length"; 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; }
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; }
#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; }
Standard Input Stream (cin) in C++
The cin object is used to accept input from the standard input device i.e. keyboard. It is defined in the iostream header file. C++ cin statement is the instance of the class istream and is used to read input from the standard input device which is usually a keyboard. The extraction operator(>>) is used along with the object cin for reading inputs. The extraction operator extracts the data from the object cin which is entered using the keyboard.
Syntax for Standard Input Stream (cin) in C++
cin >> var_name;
>>
is the extraction operator.
var_name
is usually a variable, but can also be an element of containers like arrays, vectors, lists, etc. The "c" in cin refers to "character" and "in" means "input". Hence cin means "character input". The cin object is used along with the extraction operator >> in order to receive a stream of characters. The >> operator can also be used more than once in the same statement to accept multiple inputs. The cin object can also be used with other member functions such as getline(), read(), etc. Some of the commonly used member functions are: • cin.get(char &ch): Reads an input character and stores it in ch. • cin.getline(char *buffer, int length): Reads a stream of characters into the string buffer, It stops when: it has read length-1 characters or when it finds an end-of-line character '\n' or the end of the file eof. • cin.read(char *buffer, int n): Reads n bytes (or until the end of the file) from the stream into the buffer. • cin.ignore(int n): Ignores the next n characters from the input stream. • cin.eof(): Returns a non-zero value if the end of file (eof) is reached. The prototype of cin as defined in the iostream header file is: extern istream cin; The cin object in C++ is an object of class istream. It is associated with the standard C input stream stdin. The cin object is ensured to be initialized during or before the first time an object of type ios_base::Init is constructed. After the cin object is constructed, cin.tie() returns &cout. This means that any formatted input operation on cin forces a call to cout.flush() if any characters are pending for output.
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
/* Standard Input Stream (cin) in C++ language */ // cin with Member Functions #include <iostream> using namespace std; int main() { char name[20], address[20]; cout << "Name: "; // use cin with getline() cin.getline(name, 20); cout << "Address: "; cin.getline(address, 20); cout << endl << "You entered " << endl; cout << "Name = " << name << endl; cout << "Address = " << address; return 0; }
fgets() Function in C++
Get string from stream. Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first. A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str. A terminating null character is automatically appended after the characters copied to str. Notice that fgets is quite different from gets: not only fgets accepts a stream argument, but also allows to specify the maximum size of str and includes in the string any ending newline character.
Syntax for fgets() Function in C++
#include <cstdio> char * fgets ( char * str, int num, FILE * stream );
str
Pointer to an array of chars where the string read is copied.
num
Maximum number of characters to be copied into str (including the terminating null-character).
stream
Pointer to a FILE object that identifies an input stream. stdin can be used as argument to read from the standard input. On success, the function returns str. If the end-of-file is encountered while attempting to read a character, the eof indicator is set (feof). If this happens before any characters could be read, the pointer returned is a null pointer (and the contents of str remain unchanged). If a read error occurs, the error indicator (ferror) is set and a null pointer is also returned (but the contents pointed by str may have changed).
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
/* The fgets() function in C++ reads a specified maximum number of characters from the given file stream. */ /* Get string from stream by fgets() function code example */ #include <iostream> #include <cstdio> using namespace std; int main() { int count = 10; char str[10]; FILE *fp; fp = fopen("file.txt","w+"); fputs("An example file\n", fp); fputs("Filename is file.txt\n", fp); rewind(fp); while(feof(fp) == 0) { fgets(str,count,fp); cout << str << endl; } fclose(fp); return 0; }
Break Statement in C++
Break statement in C++ is a loop control statement defined using the break keyword. It is used to stop the current execution and proceed with the next one. When a compiler calls the break statement, it immediately stops the execution of the loop and transfers the control outside the loop and executes the other statements. In the case of a nested loop, break the statement stops the execution of the inner loop and proceeds with the outer loop. The statement itself says it breaks the loop. When the break statement is called in the program, it immediately terminates the loop and transfers the flow control to the statement mentioned outside the loop.
Syntax for Break Statement in C++
// jump-statement; break;
The break statement is used in the following scenario: • When a user is not sure about the number of iterations in the program. • When a user wants to stop the program based on some condition. The break statement terminates the loop where it is defined and execute the other. If the condition is mentioned in the program, based on the condition, it executes the loop. If the condition is true, it executes the conditional statement, and if the break statement is mentioned, it will immediately break the program. otherwise, the loop will iterate until the given condition fails. if the condition is false, it stops the program.
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
/* break statement with while loop code example */ // program to find the sum of positive numbers // if the user enters a negative numbers, break ends the loop // the negative number entered is not added to sum #include <iostream> using namespace std; int main() { int number; int sum = 0; while (true) { // take input from the user cout << "Enter a number: "; cin >> number; // break condition if (number < 0) { break; } // add all positive numbers sum += number; } // display the sum cout << "The sum is " << sum << endl; return 0; }
exit() Function in C++
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.
Syntax for exit() Function in C++
void exit (int status);
status
Status code. If this is 0 or EXIT_SUCCESS, it indicates success. If it is EXIT_FAILURE, it indicates failure. 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().) Functions registered with atexit() are called in the reverse order of their registration. A function registered with atexit(), before an object obj1 of static storage duration is initialized, will not be called until obj1's destruction has completed. A function registered with atexit(), after an object obj2 of static storage duration is initialized, will be called before obj2's destruction starts. Normal program termination performs the following (in the same order): • Objects associated with the current thread with thread storage duration are destroyed (C++11 only). • Objects with static storage duration are destroyed (C++) and functions registered with atexit are called. • All C streams (open with functions in <cstdio>) are closed (and flushed, if buffered), and all files created with tmpfile are removed. • Control is returned to the host environment. Note that objects with automatic storage are not destroyed by calling exit (C++). If status is zero or EXIT_SUCCESS, a successful termination status is returned to the host environment. If status is EXIT_FAILURE, an unsuccessful termination status is returned to the host environment. Otherwise, the status returned depends on the system and library implementation. Flushes all buffers, and closes all open files. All files opened with tmpfile() are deleted. Returns control to the host environment from the program. exit() returns no values.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* terminate the process normally, performing the regular cleanup for terminating programs by exit() function code example */ #include<iostream> using namespace std; int main() { int i; cout<<"Enter a non-zero value: "; //user input cin>>i; if(i) // checks whether the user input is non-zero or not { cout<<"Valid input.\n"; } else { cout<<"ERROR!"; //the program exists if the value is 0 exit(0); } cout<<"The input was : "<<i; }
Standard Output Stream (cout) in C++
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.
Syntax for cout in C++
cout << var_name; //or cout << "Some String";
The syntax of the cout object in C++: cout << var_name; Or cout << "Some String";
<<
is the insertion operator
var_name
is usually a variable, but can also be an array element or elements of containers like vectors, lists, maps, etc. 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. The << operator can be used more than once with a combination of variables, strings, and manipulators. cout is used for displaying data on the screen. The operator << called as insertion operator or put to operator. The Insertion operator can be overloaded. Insertion operator is similar to the printf() operation in C. cout is the object of ostream class. Data flow direction is from variable to output device. Multiple outputs can be displayed using cout.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* standard output stream (cout) in C++ language */ #include <iostream> using namespace std; int main() { string str = "Do not interrupt me"; char ch = 'm'; // use cout with write() cout.write(str,6); cout << endl; // use cout with put() cout.put(ch); return 0; }
Static Keyword in C++
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. C++ Static Field: A field which is declared as static is called static field. Unlike instance field which gets memory each time whenever you create object, there is only one copy of static field created in the memory. It is shared to all the objects. It is used to refer the common property of all objects such as rateOfInterest in case of Account, companyName in case of Employee etc. Static variables inside functions: Static variables when used inside function are initialized only once, and then they hold there value even through function calls. These static variables are stored on static storage area , not in stack.
void counter() { static int count=0; cout << count++; } int main(0 { for(int i=0;i<5;i++) { counter(); } }
Static class objects: Static keyword works in the same way for class objects too. Objects declared static are allocated storage in static storage area, and have scope till the end of program. Static objects are also initialized using constructors like other normal objects. Assignment to zero, on using static keyword is only for primitive datatypes, not for user defined datatypes.
class Abc { int i; public: Abc() { i=0; cout << "constructor"; } ~Abc() { cout << "destructor"; } }; void f() { static Abc obj; } int main() { int x=0; if(x==0) { f(); } cout << "END"; }
Static data member in class: Static data members of class are those members which are shared by all the objects. Static data member has a single piece of storage, and is not available as separate copy with each object, like other non-static data members. Static member variables (data members) are not initialied using constructor, because these are not dependent on object initialization. Also, it must be initialized explicitly, always outside the class. If not initialized, Linker will give error.
class X { public: static int i; X() { // construtor }; }; int X::i=1; int main() { X obj; cout << obj.i; // prints value of i }
Static member functions: These functions work for the class as whole rather than for a particular object of a class. It can be called using an object and the direct member access . operator. But, its more typical to call a static member function by itself, using class name and scope resolution :: operator.
class X { public: static void f() { // statement } }; int main() { X::f(); // calling member function directly with class name }
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
/* static keyword has different meanings when used with different types simple code example */ // CPP program to illustrate class objects as static #include<iostream> using namespace std; class Happy { int i = 0; public: Happy() { i = 0; cout << "Inside Constructor\n"; } ~Happy() { cout << "Inside Destructor\n"; } }; int main() { int x = 0; if (x==0) { static Happy obj; } cout << "End of main\n"; }
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; }
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; }
Bitwise Operators in C++
The bitwise operators are the operators used to perform the operations on the data at the bit-level. When we perform the bitwise operations, then it is also known as bit-level programming. It consists of two digits, either 0 or 1. It is mainly used in numerical computations to make the calculations faster. We have different types of bitwise operators in the C++ programming language. The following is the list of the bitwise operators:
&
Bitwise AND operator is denoted by the single ampersand sign (&). Two integer operands are written on both sides of the (&) operator. If the corresponding bits of both the operands are 1, then the output of the bitwise AND operation is 1; otherwise, the output would be 0. This is one of the most commonly used logical bitwise operators. It is represented by a single ampersand sign (&). Two integer expressions are written on each side of the (&) operator. The result of the bitwise AND operation is 1 if both the bits have the value as 1; otherwise, the result is always 0. The bitwise AND operator is a single ampersand: &. A handy mnemonic is that the small version of the boolean AND, &&, works on smaller pieces (bits instead of bytes, chars, integers, etc). In essence, a binary AND simply takes the logical AND of the bits in each position of a number in binary form. 01001000 & 10111000 = 00001000 The most significant bit of the first number is 0, so we know the most significant bit of the result must be 0; in the second most significant bit, the bit of second number is zero, so we have the same result. The only time where both bits are 1, which is the only time the result will be 1, is the fifth bit from the left.
|
Bitwise OR operator is represented by a single vertical sign (|). Two integer operands are written on both sides of the (|) symbol. If the bit value of any of the operand is 1, then the output would be 1, otherwise 0. It is represented by a single vertical bar sign (|). Two integer expressions are written on each side of the (|) operator. The result of the bitwise OR operation is 1 if at least one of the expression has the value as 1; otherwise, the result is always 0. Bitwise OR works almost exactly the same way as bitwise AND. The only difference is that only one of the two bits needs to be a 1 for that position's bit in the result to be 1. (If both bits are a 1, the result will also have a 1 in that position.) The symbol is a pipe: |. Again, this is similar to boolean logical operator, which is ||. 01001000 | 10111000 = 11111000
^
Bitwise exclusive OR operator is denoted by (^) symbol. Two operands are written on both sides of the exclusive OR operator. If the corresponding bit of any of the operand is 1 then the output would be 1, otherwise 0. The bitwise XOR ^ operator returns 1 if and only if one of the operands is 1. However, if both the operands are 0, or if both are 1, then the result is 0. The following truth table demonstrates the working of the bitwise XOR operator. Let a and b be two operands that can only take binary values i.e. 1 or 0. There is no boolean operator counterpart to bitwise exclusive-or, but there is a simple explanation. The exclusive-or operation takes two inputs and returns a 1 if either one or the other of the inputs is a 1, but not if both are. That is, if both inputs are 1 or both inputs are 0, it returns 0. Bitwise exclusive-or, with the operator of a caret, ^, performs the exclusive-or operation on each pair of bits. Exclusive-or is commonly abbreviated XOR. 01110010 ^ 10101010 = 11011000
~
Bitwise complement operator is also known as one's complement operator (unary operator). It is represented by the symbol tilde (~). It takes only one operand or variable and performs complement operation on an operand. When we apply the complement operation on any bits, then 0 becomes 1 and 1 becomes 0. The bitwise complement operator, the tilde, ~, flips every bit. A useful way to remember this is that the tilde is sometimes called a twiddle, and the bitwise complement twiddles every bit: if you have a 1, it's a 0, and if you have a 0, it's a 1. The bitwise complement is also called as one's complement operator since it always takes only one value or an operand. It is a unary operator. When we perform complement on any bits, all the 1's become 0's and vice versa. If we have an integer expression that contains 0000 1111 then after performing bitwise complement operation the value will become 1111 0000. Bitwise complement operator is denoted by symbol tilde (~). The bitwise shift operators are used to move/shift the bit patterns either to the left or right side. Left and right are two shift operators provided by 'C' which are represented as follows: Operand << n (Left Shift), Operand >> n (Right Shift) an operand is an integer expression on which we have to perform the shift operation. 'n' is the total number of bit positions that we have to shift in the integer expression.
<<
Left-shift operator - It is an operator that shifts the number of bits to the left-side. Left shift operator shifts all bits towards left by a certain number of specified bits. The bit positions that have been vacated by the left shift operator are filled with 0. The symbol of the left shift operator is <<. The left shift operation will shift the 'n' number of bits to the left side. The leftmost bits in the expression will be popped out, and n bits with the value 0 will be filled on the right side.
>>
Right-shift operator - It is an operator that shifts the number of bits to the right side. Right shift operator shifts all bits towards right by certain number of specified bits. It is denoted by >>. The right shift operation will shift the 'n' number of bits to the right side. The rightmost 'n' bits in the expression will be popped out, and the value 0 will be filled on the left side. X Y X&Y X|Y X^Y 0 0 0 0 0 0 1 0 1 1 1 0 0 1 1 1 1 1 1 1 Shifts operators can be combined then it can be used to extract the data from the integer expression.
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
/* bitwise operators in C++ language*/ #include <iostream> using namespace std; int main() { // a = 5(00000101), b = 9(00001001) int a = 5, b = 9; // The result is 00000001 cout<<"a = " << a <<","<< " b = " << b <<endl; cout << "a & b = " << (a & b) << endl; // The result is 00001101 cout << "a | b = " << (a | b) << endl; // The result is 00001100 cout << "a ^ b = " << (a ^ b) << endl; // The result is 11111010 cout << "~(" << a << ") = " << (~a) << endl; // The result is 00010010 cout<<"b << 1" <<" = "<< (b << 1) <<endl; // The result is 00000100 cout<<"b >> 1 "<<"= " << (b >> 1 )<<endl; return 0; }
For Loop Statement in C++
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.
Syntax of For Loop Statement in C++
for (initialization; condition; update) { // body of-loop }
initialization
initializes variables and is executed only once.
condition
if true, the body of for loop is executed, if false, the for loop is terminated.
update
updates the value of initialized variables and again checks the condition. A new range-based for loop was introduced to work with collections such as arrays and vectors.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* For Loop Statement in C++ Language */ // C++ program to find the sum of first n natural numbers // positive integers such as 1,2,3,...n are known as natural numbers #include <iostream> using namespace std; int main() { int num, sum; sum = 0; cout << "Enter a positive integer: "; cin >> num; for (int i = 1; i <= num; ++i) { sum += i; } cout << "Sum = " << sum << endl; return 0; }


To copy string in C++ language, enter a string to "make copy" to another variable say str2 of same type using Function strcpy() and display the copied string on the screen as shown here
It affects the "value of the variable" from the Parameter List. There is a possibility to use the default values for the parameters in the parameters list. In this case you can assign a
To find the "Largest Element", the first two elements of array are checked and largest of these two element is placed in arr[0]. Then, the first and third elements are checked and