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++ > Beginners Lab Assignments Code Examples

Office management

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 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
/* Office management It is a simple project made in c++,it has not got ny type of graphics as simple as stick so plz try and use the software in ur office frontier to ad or modify or delete the employyers details try once.......... give me ur reply on my email */ #include<DOS.h> #include<fstream.h> #include<conio.h> #include<string.h> #include<stdio.h> int count =0; class emp { char name[40]; char jobdeg[40],phno[20]; float salary,srno; public: void getdata(void); void display(void); void mod_data(); }; void emp::getdata(void) { char ch; cin.get(ch); clrscr(); gotoxy(15,10); cout<<"Add student data "; gotoxy(17,12); cout<<"Record #"<<(++count)<<endl; gotoxy(1,14); for(int i=0;i<40;i++)name[i]=' '; salary=0.0;srno=0.0; //jobdeg=;phno='asd'; cout<<" Enter the Serial no";cin>>srno; cout<<" Enter Name"; gets(name); cout<<" Enter Job designation";gets(jobdeg); cout<<" Enter Phone number";gets(phno); cout<<" Enter the Salary";cin>>salary; cout<<" "; } void emp::display(void) { clrscr(); gotoxy(15,10); cout<<"Student Details "; gotoxy(1,12); cout<<" Sr. NO "<<srno<<" Name "<<name<<""<<" Salary "<<salary<<" Job designation "<<jobdeg<<" Phone no "<<phno; } void emp::mod_data(void) { char nm[40],jd[40],ph[20]; float sal,sr; clrscr(); gotoxy(15,8); cout<<"Modify Employee's data"; char ch=cin.get();cout<<ch; clrscr(); gotoxy(17,10); cout<<"Current details are"; gotoxy(17,12); cout<<" Sr.No. :-"<<srno<<" Name:-"<<name<<" Job designation"<<jobdeg<<" Salary"<<salary<<" Contact no"<<phno; gotoxy(17,18); cout<<" Enter the new details"; cout<<" Serial no";cin>>sr; cout<<" Name";gets(nm); cout<<" Job designation ";gets(jd); cout<<" Salary";cin>>sal; cout<<" Phone number";gets(ph); if(strlen(nm)!=0)strcpy(name,nm); if(strlen(jd)!=0)strcpy(jobdeg,jd); if(strlen(ph)!=0)strcpy(phno,ph); if(sal>salary||sal<salary)salary=sal; if(sr>srno||sr<srno)srno=sr; clrscr(); } int main() { clrscr(); emp empl; fstream finout; finout.open("empdl.dat",ios::in|ios::out|ios::binary); if(!finout) { cout<<"Cannot open the file!!!"; return 1; } int choice ,merc=0,offset=0; char ans; do { clrscr(); if(count==0) { int r,c; clrscr(); /* Introduction with Swastik*/ textcolor(YELLOW); clrscr(); for(r=5;r<20;r++) { delay(100); gotoxy(34,r); cout<<"*"; } for(c=16;c<55;c=c+2) { delay(100); gotoxy(c,12); cout<<"*"; } for(c=35;c<55;c=c+2) { delay(100); gotoxy(c,5); cout<<"*"; } for(c=34;c>15;c=c-2) { delay(100); gotoxy(c,20); cout<<"*"; } for(r=12;r<21;r++) { delay(100); gotoxy(55,r); cout<<"*"; } for(r=12;r>4;r=r-1) { delay(100); gotoxy(15,r); cout<<"*"; } for(r=8;r<=8;r++) { delay(10); gotoxy(25,r); cout<<"*"; } for(r=8;r<=8;r++) { delay(10); gotoxy(45,r); cout<<"*"; } for(r=16;r<=16;r++) { delay(10); gotoxy(25,r); cout<<"*"; } for(r=16;r<=16;r++) { delay(10); gotoxy(45,r); cout<<"*"; } delay(1400); clrscr(); /* OFFICE MANAGEMENT */ delay(300); cout<<" O "; delay(300); cout<<"F "; delay(300); cout<<"F "; delay(300); cout<<"I "; delay(300); cout<<"C "; delay(300); cout<<"E "; delay(300); cout<<" M "; delay(300); cout<<"A "; delay(300); cout<<"N "; delay(300); cout<<"A "; delay(300); cout<<"G"; delay(300); cout<<" E"; delay(300); cout<<" M"; delay(300); cout<<" E"; delay(300); cout<<" N"; delay(300); cout<<" T "; delay(300); cout<<" ****** "; delay(300); cout<<" ... "; delay(1400); cout<<"a PRESS ANY KEY ........ "; for(c=1;c<80;c++) { delay(10); gotoxy(c,1); cout<<"&"; } for(r=1;r<26;r++) { delay(10); gotoxy(1,r); cout<<"&&"; } for(c=26;c<102;c++) { delay(10); gotoxy(c,26); cout<<"&"; } for(r=1;r<26;r++) { delay(10); gotoxy(78,r); cout<<"&&"; } getch(); } clrscr(); textcolor(CYAN); cout<<" Main menu"; cout<<" ______________"; cout<<" 1.Add record"; cout<<" 2.Modify record"; cout<<" 3.Display record"; cout<<" 4.Exit....... "; cin>>choice; switch(choice) { case 1:empl.getdata(); merc=count; offset=((merc-1)*sizeof(emp)); finout.seekp(offset,ios::beg); finout.write((char*) &empl,sizeof(emp)); break; case 2:if(!count) { gotoxy(20,20); cout<<" No record has been added yet!!!! plz run option 1 first!!!!"; cout<<"Press any key to continue........."; getch(); break; } cout<<"Modify which record"; cin>>merc; if( merc>count) { cout<<" Only "<<count<<" These many records are added"; cout<<" Invalid record number!!!!"; gotoxy(20,20); cout<<"Press any key to continue!!!!!"; getch(); break; } else { offset=(merc-1)*sizeof(emp); finout.seekg(offset,ios::beg); finout.read((char*)&empl,sizeof(emp)); empl.display(); cout<<"Modify this record?(y/n)"; cin>>ans; if(ans=='y'||ans=='Y') { cout<<"Enter new details"; empl.mod_data(); finout.seekp(offset,ios::beg); finout.write((char*) &empl,sizeof(emp)); cout<<"Record modified!!!!!"; gotoxy(20,20); cout<<"Press any key to continue!!!!!!!!"; getch(); } break; } case 3: if(!count) { cout<<" No record has been added yet"; cout<<"Please run the optionm 1 first on the main screen"; gotoxy(10,20); cout<<"press any key to continue"; getch(); break; } cout<<" Display which record"; cin>>merc; cout<<endl; if( merc>count) { cout<<" Only "<<count<<" These many records are added"; cout<<" Invalid record number!!!!"; gotoxy(20,20); cout<<"Press any key to continue!!!!!"; getch(); break; } else { offset=(merc-1)*sizeof(emp); finout.seekg(offset,ios::beg); finout.read((char*)&empl,sizeof(emp)); empl.display(); gotoxy(10,20); cout<<"Press any key to continue!!!!!!!"; getch(); } break; case 4:break; default :cout<<"Wrong choice!!!! valid choice ar only 1-4"; break; } }while(choice>=1&& choice<=3); finout.close(); return 0; }
read() Function in C++
Read block of data. Extracts n characters from the stream and stores them in the array pointed to by s. This function simply copies a block of data, without checking its contents nor appending a null character at the end. If the input sequence runs out of characters to extract (i.e., the end-of-file is reached) before n characters have been successfully read, the array pointed to by s contains all the characters read until that point, and both the eofbit and failbit flags are set for the stream. Internally, the function accesses the input sequence by first constructing a sentry object (with noskipws set to true). Then (if good), it extracts characters from its associated stream buffer object as if calling its member functions sbumpc or sgetc, and finally destroys the sentry object before returning. The number of characters successfully read and stored by this function can be accessed by calling member gcount.
Syntax for read() Function in C++
#include <fstream> istream& read (char* s, streamsize n);
s
Pointer to an array where the extracted characters are stored.
n
Number of characters to extract. streamsize is a signed integral type. Function returns the istream object (*this). Errors are signaled by modifying the internal state flags: • eofbit: The function stopped extracting characters because the input sequence has no more characters available (end-of-file reached). • failbit: Either the function could not extract n characters or the construction of sentry failed. • badbit: Error on stream (such as when this function catches an exception thrown by an internal operation). When set, the integrity of the stream may have been affected. Multiple flags may be set by a single operation. If the operation sets an internal state flag that was registered with member exceptions, the function throws an exception of member type failure.
Data races
Modifies the elements in the array pointed to by s and the stream object. Concurrent access to the same stream object may cause data races, except for the standard stream object cin when this is synchronized with stdio (in this case, no data races are initiated, although no guarantees are given on the order in which extracted characters are attributed to threads).
Exception safety
Basic guarantee: if an exception is thrown, the object is in a valid state. It throws an exception of member type failure if the resulting error state flag is not goodbit and member exceptions was set to throw for that state. Any exception thrown by an internal operation is caught and handled by the function, setting badbit. If badbit was set on the last call to exceptions, the function rethrows the caught exception.
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
/* The function read() in <iostream> header file extracts n characters from the stream and stores them in the array pointed to the stream. Unlike functions put() and get() it is usually used to handle the data in binary form. */ /* extracts n characters from the stream and stores them in the array pointed by s with read() function code example. */ #include <iostream> #include <fstream> int main () { std::ifstream is ("test.txt", std::ifstream::binary); if (is) { is.seekg (0, is.end); int length = is.tellg(); is.seekg (0, is.beg); char * buffer = new char [length]; std::cout << "Reading " << length << " characters... "; is.read (buffer,length); if (is) std::cout << "all characters read successfully."; else std::cout << "error: only " << is.gcount() << " could be read"; is.close(); delete[] buffer; } 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; }
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; }
gotoxy() Function in C++
Positions cursor in text window. The gotoxy() function places the cursor at the desired location on the screen. This means it is possible to change the cursor location on the screen using the gotoxy() function. It is basically used to print text wherever the cursor is moved. If the coordinates are in any way invalid the call to gotoxy is ignored. Neither argument to gotoxy can be zero.
Syntax for gotoxy() Function in C++
void gotoxy(int x, int y);
x
X coordinate of the position where we want to place the cursor.
y
Y coordinate of the position where we want to place the cursor. This function does not return any value. Do not use this function for Win32s or Win32 GUI applications.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* The gotoxy() function places the cursor at the desired location on the screen. This means it is possible to change the cursor location on the screen using the gotoxy() function. It is basically used to print text wherever the cursor is moved. */ // Description: prints grid at given origin (xPos, yPos) // Arguments: // xPos - x coordinate of origin // yPos - y coordinate of origin void Grid::print(int xPos, int yPos){ #ifdef EN_PRINT for(int i = 0;i < GRID_LENGTH;i++){ for(int j = 0;j < GRID_LENGTH;j++){ int x = xPos + 6 * j; int y = yPos + 2 * i; gotoXY(x,y); std::cout<<" "; gotoXY(x,y); std::cout<<m_data[i*GRID_LENGTH + j]; } } #endif }
getch() Function in C++
The getch() is a predefined non-standard function that is defined in conio.h header file. It is mostly used by the Dev C/C++, MS- DOS's compilers like Turbo C to hold the screen until the user passes a single value to exit from the console screen. It can also be used to read a single byte character or string from the keyboard and then print. It does not hold any parameters. It has no buffer area to store the input character in a program.
Syntax for getch() Function in C++
#include <conio.h> int getch(void);
The getch() function does not accept any parameter from the user. It returns the ASCII value of the key pressed by the user as an input. We use a getch() function in a C/ C++ program to hold the output screen for some time until the user passes a key from the keyboard to exit the console screen. Using getch() function, we can hide the input character provided by the users in the ATM PIN, password, etc. • getch() method pauses the Output Console until a key is pressed. • It does not use any buffer to store the input character. • The entered character is immediately returned without waiting for the enter key. • The entered character does not show up on the console. • The getch() method can be used to accept hidden inputs like password, ATM pin numbers, etc.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/* wait for any character input from keyboard by getch() function code example. The getch() function is very useful if you want to read a character input from the keyboard. */ // C code to illustrate working of // getch() to accept hidden inputs #include<iostream.h> #include<conio.h> void main() { int a=10, b=20; int sum=0; clrscr(); sum=a+b; cout<<"Sum: "<<sum; getch(); // use getch() befor end of main() }
Ostream Library seekp() Function in C++
Set position in output sequence. Sets the position where the next character is to be inserted into the output stream. Internally, the function accesses the output sequence by first constructing a sentry object without evaluating it. Then, if member fail returns true, the function returns. Otherwise, it calls either pubseekpos (1) or pubseekoff (2) on its associated stream buffer object (if any). Finally, it destroys the sentry object before returning. Notice that the function will work even if the eofbit flag is set before the call, but it will not modify it.
Syntax for Ostream seekp() Function in C++
#include <fstream> //(1) ostream& seekp (streampos pos); //(2) ostream& seekp (streamoff off, ios_base::seekdir way);
pos
New absolute position within the stream (relative to the beginning). streampos is an fpos type (it can be converted to/from integral types).
off
Offset value, relative to the way parameter. streamoff is an offset type (generally, a signed integral type).
way
Object of type ios_base::seekdir. It may take any of the following constant values: • ios_base::beg - beginning of the stream • ios_base::cur - current position in the stream • ios_base::end - end of the stream Function returns the ostream object (*this). Errors are signaled by modifying the internal state flags: • eofbit: - • failbit: The internal call to either pubseekpos or pubseekoff failed (it may also be set if the construction of sentry failed). • badbit: Another error occurred on the stream (such as when the function catches an exception thrown by an internal operation). When set, the integrity of the stream may have been affected. Multiple flags may be set by a single operation. If the operation sets an internal state flag that was registered with member exceptions, the function throws an exception of member type failure.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* The seekp(pos) method of ostream in C++ is used to set the position of the pointer in the output sequence with the specified position. This method takes the new position to be set and returns this ostream instance with the position set to the specified new position. */ /* Set position in output sequence by seekp() function code example */ #include <fstream> int main () { std::ofstream outfile; outfile.open ("filename.txt"); outfile.write ("This is an apple",16); long pos = outfile.tellp(); outfile.seekp (pos-7); outfile.write (" sai",4); outfile.close(); return 0; }
String Relational Operators in C++
Relational operators for string. Performs the appropriate comparison operation between the string objects lhs and rhs. The functions use string::compare for the comparison. These operators are overloaded in header <string>. If strings are compared using relational operators then, their characters are compared lexicographically according to the current character traits, means it starts comparison character by character starting from the first character until the characters in both strings are equal or a NULL character is encountered.
Syntax for String Relational Operators in C++
#include <string> //(1) == : Equal to bool operator== (const string& lhs, const string& rhs) noexcept; bool operator== (const char* lhs, const string& rhs); bool operator== (const string& lhs, const char* rhs); //(2) != : Not equal to bool operator!= (const string& lhs, const string& rhs) noexcept; bool operator!= (const char* lhs, const string& rhs); bool operator!= (const string& lhs, const char* rhs); //(3) < : Less than bool operator< (const string& lhs, const string& rhs) noexcept; bool operator< (const char* lhs, const string& rhs); bool operator< (const string& lhs, const char* rhs); //(4) <= : Less than and equal to bool operator<= (const string& lhs, const string& rhs) noexcept; bool operator<= (const char* lhs, const string& rhs); bool operator<= (const string& lhs, const char* rhs); //(5) > : Greater than bool operator> (const string& lhs, const string& rhs) noexcept; bool operator> (const char* lhs, const string& rhs); bool operator> (const string& lhs, const char* rhs); //(6) >= : Greater than and equal to bool operator>= (const string& lhs, const string& rhs) noexcept; bool operator>= (const char* lhs, const string& rhs); bool operator>= (const string& lhs, const char* rhs);
lhs, rhs
Arguments to the left- and right-hand side of the operator, respectively. If of type char*, it shall point to a null-terminated character sequence. • lhs < rhs : A string lhs is smaller than rhs string, if either, length of lhs is shorter than rhs or first mismatched character is smaller. • lhs > rhs : A string lhs is greater than rhs string, if either, length of lhs is longer than rhs or first mismatched character is larger. • <= and >= have almost same implementation with additional feature of being equal as well. • If after comparing lexicographically, both strings are found same, then they are said to be equal. • If any of the points from 1 to 3 follows up then, strings are said to be unequal. Function returns true if the condition holds, and false otherwise.
Complexity
Unspecified, but generally up to linear in both lhs and rhs's lengths.
Iterator validity
No changes
Data races
Both objects, lhs and rhs, are accessed.
Exception safety
If an argument of type char* does not point to null-terminated character sequence, it causes undefined behavior. For operations between string objects, exceptions are never thrown (no-throw guarantee). For other cases, if an exception is thrown, there are no changes in the string (strong 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
/* If strings are compared using relational operators then, their characters are compared lexicographically according to the current character traits, means it starts comparison character by character starting from the first character until the characters in both strings are equal or a NULL character is encountered. */ // CPP code example to implement relational operators on String objects #include<iostream> using namespace std; void relational_operation(string s1, string s2) { string s3 = s1 + s2; if(s1 != s2) cout << s1 << " is not equal to " << s2 << endl; if(s1 > s2) cout << s1 << " is greater than " << s2 << endl; else if(s1 < s2) cout << s1 << " is smaller than " << s2 << endl; if(s3 == s1 + s2) cout << s3 << " is equal to " << s1 + s2 << endl; } // Main function int main() { string s1("Happy"); string s2("Happy 8) Codings"); relational_operation(s1, s2); 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; }
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++
sizeof(data_type);
data_type
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; }
Iostream Library get() Function in C++
Get characters. Extracts characters from the stream, as unformatted input. The get() function is used to read a character(at a time) from a file. The classes istream and ostream define two member functions get(), put() respectively to handle the single character input/output operations. There are two types of get() functions. Both get(char *) and get(void) prototype can be used to fetch a character including the blank space,tab and newline character. The get(char *) version assigns the input character to its argument and the get(void) version returns the input character. Since these functions are members of input/output Stream classes, these must be invoked using appropriate objects.
Syntax for get() Function in C++
#include <iostream> //single character (1) int get(); istream& get (char& c); //c-string (2) istream& get (char* s, streamsize n); istream& get (char* s, streamsize n, char delim); //stream buffer (3) istream& get (streambuf& sb); istream& get (streambuf& sb, char delim);
c
The reference to a character where the extracted value is stored.
s
Pointer to an array of characters where extracted characters are stored as a c-string. If the function does not extract any characters (or if the first character extracted is the delimiter character) and n is greater than zero, this is set to an empty c-string.
n
Maximum number of characters to write to s (including the terminating null character). If this is less than 2, the function does not extract any characters and sets failbit. streamsize is a signed integral type.
delim
Explicit delimiting character: The operation of extracting successive characters stops as soon as the next character to extract compares equal to this.
sb
A streambuf object on whose controlled output sequence the characters are copied. • (1) single character Extracts a single character from the stream. The character is either returned (first signature), or set as the value of its argument (second signature). • (2) c-string Extracts characters from the stream and stores them in s as a c-string, until either (n-1) characters have been extracted or the delimiting character is encountered: the delimiting character being either the newline character ('\n') or delim (if this argument is specified). The delimiting character is not extracted from the input sequence if found, and remains there as the next character to be extracted from the stream (see getline for an alternative that does discard the delimiting character). A null character ('\0') is automatically appended to the written sequence if n is greater than zero, even if an empty string is extracted. • (3) stream buffer Extracts characters from the stream and inserts them into the output sequence controlled by the stream buffer object sb, stopping either as soon as such an insertion fails or as soon as the delimiting character is encountered in the input sequence (the delimiting character being either the newline character, '\n', or delim, if this argument is specified). Only the characters successfully inserted into sb are extracted from the stream: Neither the delimiting character, nor eventually the character that failed to be inserted at sb, are extracted from the input sequence and remain there as the next character to be extracted from the stream. The function also stops extracting characters if the end-of-file is reached. If this is reached prematurely (before meeting the conditions described above), the function sets the eofbit flag. Internally, the function accesses the input sequence by first constructing a sentry object (with noskipws set to true). Then (if good), it extracts characters from its associated stream buffer object as if calling its member functions sbumpc or sgetc, and finally destroys the sentry object before returning. The number of characters successfully read and stored by this function can be accessed by calling member gcount. The first signature returns the character read, or the end-of-file value (EOF) if no characters are available in the stream (note that in this case, the failbit flag is also set). All other signatures always return *this. Note that this return value can be checked for the state of the stream (see casting a stream to bool for more info). Errors are signaled by modifying the internal state flags: • eofbit The function stopped extracting characters because the input sequence has no more characters available (end-of-file reached). • failbit Either no characters were written or an empty c-string was stored in s. • badbit Error on stream (such as when this function catches an exception thrown by an internal operation). When set, the integrity of the stream may have been affected. Multiple flags may be set by a single operation. If the operation sets an internal state flag that was registered with member exceptions, the function throws an exception of member type failure.
Data races
Modifies c, sb or the elements in the array pointed by s. Modifies the stream object. Concurrent access to the same stream object may cause data races, except for the standard stream object cin when this is synchronized with stdio (in this case, no data races are initiated, although no guarantees are given on the order in which extracted characters are attributed to threads).
Exception safety
Basic guarantee: if an exception is thrown, the object is in a valid state. It throws an exception of member type failure if the resulting error state flag is not goodbit and member exceptions was set to throw for that state. Any exception thrown by an internal operation is caught and handled by the function, setting badbit. If badbit was set on the last call to exceptions, the function rethrows the caught exception.
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
/* reads a single character from the associated stream by get() function code example. */ /* It is used to fetch a character from the file and continues to do so until the end-of-the file condition is reached. */ //C++ Reading the content to a file using ifstream class and file mode ios::in #include<iostream> #include<ifstream> using namespace std; int main() { //Creating an input stream to read a file ifstream ifstream_ob; //Opening a file named File1.txt to read its content ifstream_ob.open("File1.txt", ios::in); char ch; //Reading the file using get() function and displaying its content while(ifstream_ob) { ch = ifstream_ob.get(); cout<<ch; } //Closing the input strea ifstream_ob.close(); return 0; }
write() Function in C++
Write block of data. Inserts the first n characters of the array pointed by s into the stream. This function simply copies a block of data, without checking its contents: The array may contain null characters, which are also copied without stopping the copying process. Internally, the function accesses the output sequence by first constructing a sentry object. Then (if good), it inserts character into its associated stream buffer object as if calling its member function sputc until n characters have been written or until an insertion fails (in this case it sets the badbit flag). Finally, it destroys the sentry object before returning.
Syntax for write() Function in C++
#include <fstream> ostream& write (const char* s, streamsize n);
s
Pointer to an array of at least n characters.
n
Number of characters to insert. Integer value of type streamsize representing the size in characters of the block of data to write. streamsize is a signed integral type. Function returns the ostream object (*this). Errors are signaled by modifying the internal state flags: • eofbit: - • failbit: May be set if the construction of sentry failed. • badbit: Either an insertion on the stream failed, or some other error happened (such as when this function catches an exception thrown by an internal operation). When set, the integrity of the stream may have been affected. Multiple flags may be set by a single operation. If the operation sets an internal state flag that was registered with member exceptions, the function throws an exception of member type failure.
Data races
Access up to n characters pointed by s. Modifies the stream object. Concurrent access to the same stream object may cause data races, except for the standard stream objects (cout, cerr, clog) when these are synchronized with stdio (in this case, no data races are initiated, although no guarantees are given on the order in which characters from multiple threads are inserted).
Exception safety
Basic guarantee: if an exception is thrown, the object is in a valid state. It throws an exception of member type failure if the resulting error state flag is not goodbit and member exceptions was set to throw for that state. Any exception thrown by an internal operation is caught and handled by the function, setting badbit. If badbit was set on the last call to exceptions, the function rethrows the caught exception.
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
/* write block of data by ostream::write function code example */ /* in order to perform a binary input/output operation using the read() and write() functions, C++ provides us a few file stream classes */ // Copy a file #include <fstream> // std::ifstream, std::ofstream int main () { std::ifstream infile ("test.txt",std::ifstream::binary); std::ofstream outfile ("new.txt",std::ofstream::binary); // get size of file infile.seekg (0,infile.end); long size = infile.tellg(); infile.seekg (0); // allocate memory for file content char* buffer = new char[size]; // read content of infile infile.read (buffer,size); // write to outfile outfile.write (buffer,size); // release dynamically-allocated memory delete[] buffer; outfile.close(); infile.close(); return 0; }
strcpy() Function in C++
Copy string. Copies the C string pointed by source into the array pointed by destination, including the terminating null character (and stopping at that point). To avoid overflows, the size of the array pointed by destination shall be long enough to contain the same C string as source (including the terminating null character), and should not overlap in memory with source. strcpy() is a standard library function in C/C++ and is used to copy one string to another. In C it is present in string.h header file and in C++ it is present in cstring header file. It copies the whole string to the destination string. It replaces the whole string instead of appending it. It won't change the source string.
Syntax for strcpy() Function in C++
#include <cstring> char * strcpy ( char * destination, const char * source );
destination
Pointer to the destination array where the content is to be copied.
source
C string to be copied. destination is returned. After copying the source string to the destination string, the strcpy() function returns a pointer to the destination string. • This function copies the entire string to the destination string. It doesn't append the source string to the destination string. In other words, we can say that it replaces the content of destination string by the content of source string. • It does not affect the source string. The source string remains same after copying. • This function only works with C style strings and not C++ style strings i.e. it only works with strings of type char str[]; and not string s1; which are created using standard string data type available in C++ and not C.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* copy a character string from source to destination by strcpy() string function code example */ #include <cstring> #include <iostream> using namespace std; int main() { char src[20] = "I am the source."; // large enough to store content of src char dest[30] = "I am the destination."; cout << "dest[] before copy: " << dest << endl; // copy contents of src to dest strcpy(dest,src); cout << "dest[] after copy: " << dest; 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; }
seekg() Function in C++
Set position in input sequence. Sets the position of the next character to be extracted from the input stream. Sets the position of the next character to be extracted from the input stream. seekg() is a function in the iostream library (part of the standard library) that allows you to seek to an arbitrary position in a file. It is used in file handling to sets the position of the next character to be extracted from the input stream from a given file. Internally, the function accesses the input sequence by first constructing a sentry object (with noskipws set to true). Then (if good), it calls either pubseekpos (1) or pubseekoff (2) on its associated stream buffer object (if any). Finally, it destroys the sentry object before returning. Calling this function does not alter the value returned by gcount.
Syntax for seekg() Function in C++
#include <fstream> //(1) istream& seekg (streampos pos); //(2) istream& seekg (streamoff off, ios_base::seekdir way);
pos
New absolute position within the stream (relative to the beginning). streampos is an fpos type (it can be converted to/from integral types).
off
Offset value, relative to the way parameter. streamoff is an offset type (generally, a signed integral type).
way
Object of type ios_base::seekdir. It may take any of the following constant values: ios_base::beg beginning of the stream ios_base::cur current position in the stream ios_base::end end of the stream Function returns the istream object (*this). Errors are signaled by modifying the internal state flags: eofbit - failbit Either the construction of sentry failed, or the internal call to pubseekpos (1) or pubseekoff (2) failed (i.e., either function returned -1). badbit Another error occurred on the stream (such as when the function catches an exception thrown by an internal operation). When set, the integrity of the stream may have been affected. Multiple flags may be set by a single operation. If the operation sets an internal state flag that was registered with member exceptions, the function throws an exception of member type failure.
Data races
Modifies the stream object. Concurrent access to the same stream object may cause data races.
Exception safety
Basic guarantee: if an exception is thrown, the object is in a valid state. It throws an exception of member type failure if the resulting error state flag is not goodbit and member exceptions was set to throw for that state. Any exception thrown by an internal operation is caught and handled by the function, setting badbit. If badbit was set on the last call to exceptions, the function rethrows the caught exception.
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
/* sets the position of the next character to be extracted from the input stream from a given file by seekg() function code example */ // CPP Prpgram to demonstrate the seekg function in file handling #include <fstream> #include <iostream> using namespace std; // Driver Code int main(int argc, char** argv) { // Open a new file for input/output operations fstream myFile("test.txt", ios::in | ios::out | ios::trunc); // Add the characters "Hello World" to the file myFile << "Hello World"; // Seek to 6 characters from the beginning of the file myFile.seekg(6, ios::beg); // Read the next 5 characters from the file into a // buffer char A[6]; myFile.read(A, 5); // End the buffer with a null terminating character A[5] = 0; // Output the contents read from the file and close it cout << A << endl; myFile.close(); }
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; }
gets() Function in C++
Get string from stdin. Reads characters from the standard input (stdin) and stores them as a C string into str until a newline character or the end-of-file is reached. The newline character, if found, is not copied into str. A terminating null character is automatically appended after the characters copied to str. Notice that gets is quite different from fgets: not only gets uses stdin as source, but it does not include the ending newline character in the resulting string and does not allow to specify a maximum size for str (which can lead to buffer overflows).
Syntax for gets() Function in C++
#include <cstdio> char * gets ( char * str );
str
Pointer to a block of memory (array of char) where the string read is copied as a C string. 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). The most recent revision of the C standard (2011) has definitively removed this function from its specification. The function is deprecated in C++ (as of 2011 standard, which follows C99+TC3).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* The gets() function in C++ reads characters from stdin and stores them until a newline character is found or end of file occurs. */ /* Get string from stdin by gets() function code example */ //Program demonstrating the difference between gets and cin #include<iostream.h> #include<stdio.h> int main() { char str1[80],str2[80]; cout<<"\n Enter a string using gets(): "; gets(str1); cout<<"\n Enter a string using cin object: "; cin>>str2; cout<<"\n String input with gets(): "; cout<<str1; cout<<"\n String input with cin object: "; cout<<str2; 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; }
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; }
clrscr() Function in C++
It is a predefined function in "conio.h" (console input output header file) used to clear the console screen. It is a predefined function, by using this function we can clear the data from console (Monitor). Using of clrscr() is always optional but it should be place after variable or function declaration only. It is often used at the beginning of the program (mostly after variable declaration but not necessarily) so that the console is clear for our output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* clrscr() function is also a non-standard function defined in "conio.h" header. This function is used to clear the console screen. It is often used at the beginning of the program (mostly after variable declaration but not necessarily) so that the console is clear for our output.*/ #include<iostream.h> #include<conio.h> void main() { int a=10, b=20; int sum=0; clrscr(); // use clrscr() after variable declaration sum=a+b; cout<<"Sum: "<<sum; //clear the console screen clrscr(); getch(); }
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; }
textcolor() Function in C++
Use the textcolor function to define what color you want to use for text. You can use this function to vary the text colors of your output. Colors must be written in all caps, or expressed as a numeral. Now, if you want your text to blink then while calling the textcolor() function pass the color and also say BLINK. This will like this: textcolor(BLUE+BLINK).
Syntax for textcolor() Function in C++
void textcolor(int color);
color
specify the color Change the color of drawing text where color is a integer variable INT VALUES corresponding to Colors: • BLACK 0 • BLUE 1 • GREEN 2 • CYAN 3 • RED 4 • MAGENTA 5 • BROWN 6 • LIGHTGRAY 7 • DARKGRAY 8 • LIGHTBLUE 9 • LIGHTGREEN 10 • LIGHTCYAN 11 • LIGHTRED 12 • LIGHTMAGENTA 13 • YELLOW 14 • WHITE 15
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* In C++ programming, the background of the output screen is black and text color is in white color. We can color both the background and text color in the output screen. */ #include <stdio.h> #include <iostream> #include <conio.h> //this should be enough I guess using namespace std; string a; int main() { clrscr(); textcolor(2); gotoxy(3,3); textattr(4); cout << "This should be underlined?"; cout << endl; cout << "Wanna end this program? Press a key (Y) and then press enter.."; cin >> a; }
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; }
delay() Function in C++
delay() function is used to hold the program's execution for given number of milliseconds, it is declared in dos.h header file. There can be many instances when we need to create a delay in our programs. C++ provides us with an easy way to do so. We can use a delay() function for this purpose in our code. We can run the code after a specific time in C++ using delay() function.
Syntax for delay() Function in C++
void delay(unsigned int milliseconds);
milliseconds
how many milliseconds to delay The function takes one parameter which is unsigned integer. Here, void suggests that this function returns nothing. 'delay' is the function name.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/* hold the program's execution for given number of milliseconds by delay() function code example. */ #include<iostream.h> #include<dos.h> //for delay() #include<conio.h> //for getch() int main() { clrscr(); int n; cout<<"Enter the delay (in seconds) you want to make after giving input."<<endl; cin>>n; delay(n*1000); cout<<"This has been printed after "<< n <<" seconds delay"; getch(); return 0; }
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; }
Fstream Library open() Function in C++
Open file. Opens the file identified by argument filename, associating it with the stream object, so that input/output operations are performed on its content. Argument mode specifies the opening mode. If the stream is already associated with a file (i.e., it is already open), calling this function fails. The file association of a stream is kept by its internal stream buffer: Internally, the function calls rdbuf()->open(filename,mode|ios_base::out) The function clears the stream's state flags on success (setting them to goodbit). In case of failure, failbit is set.
Syntax for Fstream open() Function in C++
void open (const char* filename, ios_base::openmode mode = ios_base::in | ios_base::out); void open (const string& filename, ios_base::openmode mode = ios_base::in | ios_base::out);
filename
String with the name of the file to open. Specifics about its format and validity depend on the library implementation and running environment.
mode
Flags describing the requested input/output mode for the file. This is an object of the bitmask member type openmode that consists of a combination of the following member constants: • in input File open for reading: the internal stream buffer supports input operations. • out output File open for writing: the internal stream buffer supports output operations. • binary binary Operations are performed in binary mode rather than text. • ate at end The output position starts at the end of the file. • app append All output operations happen at the end of the file, appending to its existing contents. • trunc truncate Any contents that existed in the file before it is open are discarded. These flags can be combined with the bitwise OR operator (|). If the mode has both trunc and app set, the opening operation fails. It also fails if trunc is set but out is not. This function does not return any value. If the function fails to open a file, the failbit state flag is set for the stream (which may throw ios_base::failure if that state flag was registered using member exceptions).
Data races
Modifies the fstream object. Concurrent access to the same stream object introduce data races.
Exception safety
Basic guarantee: if an exception is thrown, the stream is in a valid state. It throws an exception of member type failure if the function fails (setting the failbit state flag) and member exceptions was set to throw for that state.
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
/* Fstream library open() function opens the file identified by argument filename, associating it with the stream object, so that input/output operations are performed on its content. */ #include <iostream> #include <fstream> using namespace std; int main() { fstream new_file; new_file.open("new_file_write.txt",ios::out); if(!new_file) { cout<<"File creation failed"; } else { cout<<"New file created"; new_file<<"Learning File handling"; //Writing to file new_file.close(); } return 0; }
Switch Case Statement in C++
Switch statement in C tests the value of a variable and compares it with multiple cases. Once the case match is found, a block of statements associated with that particular case is executed. Each case in a block of a switch has a different name/number which is referred to as an identifier. The value provided by the user is compared with all the cases inside the switch block until the match is found. If a case match is NOT found, then the default statement is executed, and the control goes out of the switch block.
Syntax for Switch Case Statement in C++
switch( expression ) { case value-1: Block-1; Break; case value-2: Block-2; Break; case value-n: Block-n; Break; default: Block-1; Break; } Statement-x;
• The expression can be integer expression or a character expression. • Value-1, 2, n are case labels which are used to identify each case individually. Remember that case labels should not be same as it may create a problem while executing a program. Suppose we have two cases with the same label as '1'. Then while executing the program, the case that appears first will be executed even though you want the program to execute a second case. This creates problems in the program and does not provide the desired output. • Case labels always end with a colon ( : ). Each of these cases is associated with a block. • A block is nothing but multiple statements which are grouped for a particular case. • Whenever the switch is executed, the value of test-expression is compared with all the cases which we have defined inside the switch. Suppose the test expression contains value 4. This value is compared with all the cases until case whose label four is found in the program. As soon as a case is found the block of statements associated with that particular case is executed and control goes out of the switch. • The break keyword in each case indicates the end of a particular case. If we do not put the break in each case then even though the specific case is executed, the switch in C will continue to execute all the cases until the end is reached. This should not happen; hence we always have to put break keyword in each case. Break will terminate the case once it is executed and the control will fall out of the switch. • The default case is an optional one. Whenever the value of test-expression is not matched with any of the cases inside the switch, then the default will be executed. Otherwise, it is not necessary to write default in the switch. • Once the switch is executed the control will go to the statement-x, and the execution of a program will continue.
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 switch statement helps in testing the equality of a variable against a set of values */ #include <iostream> using namespace std; int main () { // local variable declaration: char grade = 'D'; switch(grade) { case 'A' : cout << "Excellent!" << endl; break; case 'B' : case 'C' : cout << "Well done" << endl; break; case 'D' : cout << "You passed" << endl; break; case 'F' : cout << "Better try again" << endl; break; default : cout << "Invalid grade" << endl; } cout << "Your grade is " << grade << endl; 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; }
C++ Files and Streams
In C++ programming we are using the iostream standard library, it provides cin and cout methods for reading from input and writing to output respectively. To read and write from a file we are using the standard C++ library called fstream. Let us see the data types define in fstream library is: • ofstream: This data type represents the output file stream and is used to create files and to write information to files. • ifstream: This data type represents the input file stream and is used to read information from files. • fstream: This data type represents the file stream generally, and has the capabilities of both ofstream and ifstream which means it can create files, write information to files, and read information from files. To perform file processing in C++, header files <iostream> and <fstream> must be included in your C++ source file.
Opening a File
A file must be opened before you can read from it or write to it. Either ofstream or fstream object may be used to open a file for writing. And ifstream object is used to open a file for reading purpose only. File streams in C++ are basically the libraries that are used in the due course of programming. The programmers generally use the iostream standard library in the C++ programming as it provides the cin and cout methods that are used for reading from the input and writing to the output respectively. In order to read and write from a file, the programmers are generally using the standard C++ library that is known as the fstream. Following is the standard syntax for open() function, which is a member of fstream, ifstream, and ofstream objects.
void open(const char *filename, ios::openmode mode);
Here, the first argument specifies the name and location of the file to be opened and the second argument of the open() member function defines the mode in which the file should be opened. ios::app Append mode. All output to that file to be appended to the end. ios::ate Open a file for output and move the read/write control to the end of the file. ios::in Open a file for reading. ios::out Open a file for writing. ios::trunc If the file already exists, its contents will be truncated before opening the file.
Closing a File
When a C++ program terminates it automatically flushes all the streams, release all the allocated memory and close all the opened files. But it is always a good practice that a programmer should close all the opened files before program termination. Following is the standard syntax for close() function, which is a member of fstream, ifstream, and ofstream objects.
void close();
Writing to a File
While doing C++ programming, you write information to a file from your program using the stream insertion operator (<<) just as you use that operator to output information to the screen. The only difference is that you use an ofstream or fstream object instead of the cout object.
Reading from a File
You read information from a file into your program using the stream extraction operator (>>) just as you use that operator to input information from the keyboard. The only difference is that you use an ifstream or fstream object instead of the cin object. 'ifstream' data type of 'fstream' library is used to read the files of C++. But before reading, there are several tasks which are performed sequentially like opening the file, reading and closing it. Different data types are used for the specific purpose. We can simply read the information from the file using the operator ( >> ) with the name of the file. We need to use the fstream or ifstream object in C++ in order to read the file. Reading of the file line by line can be done by simply using the while loop along with the function of ifstream 'getline()'.
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
/* C++ files and streams */ /* writing to a file and reading from a file in C++ language */ #include <fstream> #include <iostream> using namespace std; int main () { char data[100]; // open a file in write mode. ofstream outfile; outfile.open("afile.dat"); cout << "Writing to the file" << endl; cout << "Enter your name: "; cin.getline(data, 100); // write inputted data into the file. outfile << data << endl; cout << "Enter your age: "; cin >> data; cin.ignore(); // again write inputted data into the file. outfile << data << endl; // close the opened file. outfile.close(); // open a file in read mode. ifstream infile; infile.open("afile.dat"); cout << "Reading from the file" << endl; infile >> data; // write the data at the screen. cout << data << endl; // again read the data from the file and display it. infile >> data; cout << data << endl; // close the opened file. infile.close(); 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; }


A 'stack' is a basic "data structure" and can be defined in an 'Abstract', implementation-free manner, or it can be "Generally Defined" as a Linear List of items in which all additions and