Happy Codings - Programming Code Examples

C++ Programming Code Examples

C++ > Games Code Examples

SNAKE WAR - I

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 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
/* SNAKE WAR - I */ #include <graphics.h> #include <iostream.h> #include <conio.h> #include <dos.h> #include <stdlib.h> #include <stdio.h> //#pragma warn -wrch #define MAX 50 #define UP_ARROW 72 #define DOWN_ARROW 80 #define LEFT_ARROW 75 #define RIGHT_ARROW 77 #define WinMinX 40 #define WinMaxX 600 #define WinMinY 40 #define WinMaxY 440 enum Direction {Forward,Backward,Upward,Downward}; struct Coord { int x , y; }; class Snake; class Point { int x , y , color ; public: Point ( ) { set (); } void set(); void draw( ); int getx() { return x; } int gety() { return y; } friend int point_vanished ( Point &p , Snake &s ); }; class Snake { Coord *_Snake; int _CurSize, _color,_MaxSize, _Points; char _player; Direction _Direction; public: Snake ( int size = 20, int color = RED , char player = 'M' ) { _Snake = new Coord [ size ]; _CurSize = 3; if ( player == 'C' ) { _Snake [0].x = WinMaxX - 10; _Direction = Backward; } else { _Snake [0].x = WinMinX + 10; _Direction = Forward; } //_Snake [0].x = WinMinX + 10; _Snake [0].y = WinMinY + 10; _color = color; _MaxSize = size; _player = player; _Points = 0; } void set( int size = 20, int color = RED , char player = 'M' ) { delete _Snake; _Snake = new Coord [ size ]; _CurSize = 3; if ( player == 'C' ) { _Direction = Backward; _Snake [0].x = WinMaxX - 10; } else { _Snake [0].x = WinMinX + 10; _Direction = Forward; } _Snake [0].x = WinMinX + 10; //_Snake [0].y = WinMinY + 10; _color = color; _MaxSize = size; _player = player; _Points = 0; } void change_direction ( Direction d); void increment (); void inc_disp (); void shift_all (); void display ( int color = BLACK ); void com_play ( Point p1 ); friend int point_vanished ( Point &p , Snake &s ); }; //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> void Sound ( int s ); void Message_Display ( char msg[30] , char color ); void show_Header(); void signature(); int menu (); void drawMenu ( int selected , int defCol , int selCol ); void show_About(); void show_HowTOPlay(); void show_New(); void Play(); //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> int main() { int g = DETECT , d; initgraph ( &g , &d , "d:\tc\bgi" ); int selected_option; Start: selected_option = menu(); switch ( selected_option ) { case 1: Play(); goto Start; case 2: show_HowTOPlay(); goto Start; case 3: show_New(); goto Start; case 4: show_About(); goto Start; case 5: return 1; } return 1; } void Snake :: increment ( ) { //int i; shift_all(); if ( _Direction == Forward ) { if ( _Snake[0].x >= WinMaxX ) { _Snake[0].x = WinMinX ; } else _Snake[0].x = _Snake[0].x + 10; } else if ( _Direction == Backward ) { if ( _Snake[0].x <= WinMinX ) { _Snake[0].x = WinMaxX ; } else _Snake[0].x = _Snake[0].x - 10; } else if ( _Direction == Upward ) { if ( _Snake[0].y <= WinMinY ) { _Snake[0].y = WinMaxY ; } else _Snake[0].y = _Snake[0].y - 10; } else if ( _Direction == Downward ) { if ( _Snake[0].y >= WinMaxY ) { _Snake[0].y = WinMinY ; } else _Snake[0].y = _Snake[0].y + 10; } } void Snake :: shift_all () { int i; for ( i = _CurSize -1 ; i > 0; i-- ) { _Snake[i].x = _Snake[i-1].x; _Snake[i].y = _Snake[i-1].y; } } void Snake :: inc_disp () { display ( BLACK ); increment(); display ( _color ); } void Snake :: display ( int color) { setfillstyle ( 1, color ); if ( color == 0 ) { setcolor ( 0 ); bar ( _Snake[_CurSize - 1].x - 5 , _Snake[_CurSize - 1].y - 5 , _Snake[_CurSize - 1].x + 5 , _Snake[_CurSize - 1].y + 5 ); rectangle ( _Snake[_CurSize - 1].x - 5 , _Snake[_CurSize - 1].y - 5 ,_Snake[_CurSize - 1].x + 5 , _Snake[_CurSize - 1].y + 5 ); //return ; } else { setcolor ( WHITE ); for ( int i = 0; i< _CurSize; i++ ) { bar ( _Snake[i].x - 5 , _Snake[i].y - 5 , _Snake[i].x + 5 , _Snake[i].y + 5 ); rectangle ( _Snake[i].x - 5 , _Snake[i].y - 5 , _Snake[i].x + 5 , _Snake[i].y + 5 ); } /* //int i = 0; bar ( _Snake[i].x - 5 , _Snake[i].y - 5 , _Snake[i].x + 5 , _Snake[i].y+ 5 ); rectangle ( _Snake[i].x - 5 , _Snake[i].y - 5 , _Snake[i].x + 5 ,_Snake[i].y ); */ setfillstyle ( 1 , 0 ); fillellipse ( _Snake[0].x , _Snake[0].y , 2 , 2); char msg[50]; setcolor ( WHITE ); if ( _player == 'C' ) { bar ( 250 , 12 , 630 , WinMinY - 10 ); sprintf ( msg , "Com Snake at :- ( %d , %d ) Score:- %d", _Snake[0].x, _Snake[0].y , _Points ); outtextxy ( 250 , 12 , msg ); } else { bar ( 250 , 1 , 630 , WinMinY - 10 ); sprintf ( msg , "Ur Snake at :- ( %d , %d ) Score:- %d", _Snake[0].x, _Snake[0].y , _Points ); outtextxy ( 250 , 1 , msg ); } } } void Snake :: change_direction ( Direction d) { if ( ( _Direction == Forward ) && ( d == Backward ) ) { Sound ( -1 ); } else if ( ( _Direction == Backward ) && ( d == Forward ) ) { Sound ( -1 ); } else if ( ( _Direction == Upward ) && ( d == Downward ) ) { Sound ( -1 ); } else if ( ( _Direction == Downward ) && ( d == Upward ) ) { Sound ( -1 ); } else { _Direction = d; Sound ( 1 ); } } void Point :: draw ( ) { char msg[30]; setfillstyle ( 1 , color ); setcolor ( YELLOW ); bar ( x - 4 , y - 4 , x + 4 , y + 4 ); rectangle ( x - 4 , y - 4 , x + 4 , y + 4 ); setfillstyle ( 1 , 0 ); fillellipse ( x , y , 2 , 2 ); bar ( 1 , 1 , 300 , WinMinY - 10 ); sprintf ( msg , "Point at :- ( %d , %d )", x , y ); outtextxy ( 40 , 1 , msg ); } void Point :: set ( ) { color = random ( 15 ) + 1; x = random ( ( ( WinMaxX - WinMinX ) / 10 ) ) ; y = random ( ( ( WinMaxY - WinMinY ) / 10 ) ) ; x = ( x * 10 ) + WinMinX; y = ( y * 10 ) + WinMinY; draw ( ); } int point_vanished ( Point &p , Snake &s ) { if ( ( s._Snake[0].x == p.x ) && ( s._Snake[0].y == p.y ) ) { s._CurSize++; if ( s._CurSize == s._MaxSize ) { return 2; } s.increment (); s.display ( RED ); Sound ( 2 ); delay ( 100 ); s._Points = s._Points + 20 ; p.set(); return 1; } else { return -1; } } void Sound ( int s ) { if ( s == -1 ) { sound ( 150 ); delay ( 30 ); sound ( 250 ); delay ( 30 ); nosound (); } else if ( s == 1 ) { sound ( 450 ); delay ( 20 ); nosound (); } else if ( s == 2 ) { sound ( 650 ); delay ( 20 ); nosound (); } } void Snake :: com_play ( Point p1 ) { if ( p1.getx() < _Snake[0].x ) { if ( _Direction == Forward ) _Direction = p1.gety() < _Snake[0].y ? Upward : Downward; else _Direction = Backward; } else if ( p1.getx() > _Snake[0].x ) { if ( _Direction == Backward ) _Direction = p1.gety() < _Snake[0].y ? Upward : Downward; else _Direction = Forward; } else { if ( p1.gety() < _Snake[0].y ) { _Direction = Upward; } else if ( p1.gety() > _Snake[0].y ) { _Direction = Downward; } } } void Message_Display ( char msg[30] , char color ) { settextstyle ( 1 , 0 , 5 ); setcolor ( 8 ); outtextxy ( 195 , 205 , msg); settextstyle ( 1 , 0 , 5 ); setcolor ( color ); outtextxy ( 200 , 200 , msg); delay ( 1000 ); } int menu () { int ch; int selected = 1; int TotalOptions = 5; cleardevice(); setbkcolor ( BLUE ); show_Header(); signature(); drawMenu ( selected , RED , GREEN ); do { ch = getch(); if ( ch == DOWN_ARROW ) { selected = selected >= TotalOptions ? 1 : selected + 1; drawMenu ( selected , RED , GREEN ); } else if ( ch == UP_ARROW ) { selected = selected < 2 ? TotalOptions : selected - 1; drawMenu ( selected , RED , GREEN ); } }while ( ch != ' ' ); return selected; } void drawMenu ( int selected , int defCol , int selCol ) { int x = 250; int y = 100; int width = 150; int height = 30; int i; int TotalOptions = 5; char menu_option[5][14]= { " PLAY ", " HOW TO PLAY ", " WHAT'S NEW ", " ABOUT ME ", " EXIT " }; setcolor ( WHITE ); for ( i = 1; i <= TotalOptions; i++ ) { if ( i == selected ) setfillstyle ( 1 , selCol ); else setfillstyle ( 1 , defCol ); bar ( x , y , x + width , y + height ); rectangle ( x , y , x + width , y + height ); outtextxy ( x + 20 , y + 10 , menu_option[i - 1] ); y = y + height + 30; } } void show_About() { cleardevice(); setbkcolor ( BLACK ); show_Header(); setcolor ( WHITE ); settextstyle ( 0 , 0 , 0 ); signature(); getch(); } void show_HowTOPlay() { cleardevice(); setbkcolor ( BLACK ); show_Header(); settextstyle ( 0 , 0 , 0 ); setcolor ( WHITE ); outtextxy ( 20 , 100 , "Objective:" ); outtextxy ( 20 , 150 , "Playing:" ); outtextxy ( 20 , 220 , "Tip:" ); setcolor ( LIGHTGREEN ); outtextxy ( 120 , 120 , "To collect 50 boxes before the computer Snake." ); outtextxy ( 120 , 170 , "1. Use arrow keys to control your Snake." ); outtextxy ( 120 , 180 , "2. To collect the box just come near to the BOX." ); outtextxy ( 120 , 190 , "3. Press <ESC> to QUIT any time." ); outtextxy ( 120 , 240 , "1. Use shortcuts to collect the BOX. [ Computer Snake never " ); outtextxy ( 120 , 250 , " uses shortcut]" ); outtextxy ( 120 , 260 , "2. Computer Snake can't Hurt you, so enjoy moving around." ); signature(); getch(); } void signature() { outtextxy ( 350 , 400 , "WWW " ); } void show_Header() { setcolor ( RED ); settextstyle ( 1 , 0 , 4 ); outtextxy ( 193 , 27 , " SNAKE WAR - I " ); setcolor ( YELLOW ); outtextxy ( 195 , 25 , " SNAKE WAR - I " ); } void show_New() { cleardevice(); setbkcolor ( BLACK ); show_Header(); settextstyle ( 0 , 0 , 0 ); setcolor ( WHITE ); outtextxy ( 20 , 100 , "What's new" ); outtextxy ( 20 , 150 , "What's next" ); outtextxy ( 20 , 260 , "When to expect next version" ); outtextxy ( 20 , 320 , "Comments, Bugs and Suggestions" ); setcolor ( LIGHTGREEN ); outtextxy ( 70 , 120 , "Nothing, cos it's the first version. :-)" ); outtextxy ( 70 , 170 , "In next version of this Game:- " ); outtextxy ( 90 , 180 , " > One or more player will be able to play." outtextxy ( 90 , 190 , " > You'll be able to select Zero or more computer players." ); outtextxy ( 90 , 200 , " > You'll be able to PAUSE the Game any time." ); outtextxy ( 90 , 210 , " > You'll be able to select the color of each snake." ); outtextxy ( 90 , 220 , " > Keys will be customizable." ); outtextxy ( 90 , 230 , " > Snakes will be able to Hurt each other." ); outtextxy ( 70 , 280 , "Don't worry, i'll mail the code of next version too. [ Very Soon ]" ); outtextxy ( 70 , 340 , "For any suggestion or comment or Bug report feel free to mail me." ); outtextxy ( 70 , 350 , "There may be Bugs too in this game, so please let me know them." ); signature(); getch(); } void Play() { Snake s1 ( MAX , GREEN , 'M' ); Snake s2 ( MAX , MAGENTA , 'C' ); char ch , KeyPressed = 0; cleardevice(); randomize (); rectangle ( WinMinX - 7, WinMinY - 7, WinMaxX + 7 , WinMaxY + 7 ); Point p1; setbkcolor ( BLUE ); s1.inc_disp(); s2.inc_disp(); setcolor ( YELLOW ); outtextxy ( 10 , 450 , "> Collect 50 Boxes to WIN. > Use shortcuts to WIN."); setcolor ( CYAN ); outtextxy ( 10 , 460 , "> Use <ESC> to QUIT anytime. > LEFT , RIGHT , UP , DOWN Arrow Keys to Play. "); getch(); KeyPressed = 1; ch = 'R'; while ( 1 ) { while ( !kbhit() ) { s1.inc_disp(); if ( point_vanished ( p1 , s1 ) == 2 ) { Message_Display ( "YOU WIN " , GREEN ); ch=0x1b; getch(); break; } s2.com_play ( p1 ); s2.inc_disp(); if ( point_vanished ( p1 , s2 ) == 2 ) { Message_Display ( "YOU LOSE " , GREEN ); ch=0x1b; getch(); break; } delay ( 100 ); if ( KeyPressed == 1 )KeyPressed = 0; } if ( ch == 0x1b ) break; ch = getch(); if ( KeyPressed == 1 ) { KeyPressed = 0; continue; } if ( ch == 0x1b ) break; else if ( ch == 0 ) { ch = getch (); if ( ch == UP_ARROW ) { s1.change_direction ( Upward ); KeyPressed = 1; } else if ( ch == DOWN_ARROW ) { s1.change_direction ( Downward ); KeyPressed = 1; } else if ( ch == LEFT_ARROW ) { s1.change_direction ( Backward ); KeyPressed = 1; } else if ( ch == RIGHT_ARROW ) { s1.change_direction ( Forward ); KeyPressed = 1; } } } }
bar() Function in C++
bar() function is a C graphics function that is used to draw graphics in the C programming language. The graphics.h header contains functions that work for drawing graphics. The bar() function is also defined in the header file. Bar function is used to draw a 2-dimensional, rectangular filled in bar. Coordinates of left top and right bottom corner are required to draw the bar. Left specifies the X-coordinate of top left corner, top specifies the Y-coordinate of top left corner, right specifies the X-coordinate of right bottom corner, bottom specifies the Y-coordinate of right bottom corner. Current fill pattern and fill color is used to fill the bar. To change fill pattern and fill color use setfillstyle.
Syntax for bar() Function in C++
#include <graphics.h> void bar(int left, int top, int right, int bottom);
left
X coordinate of top left corner.
top
Y coordinate of top left corner.
right
X coordinate of bottom right corner.
bottom
Y coordinate of bottom right corner. Current fill pattern and fill color is used to fill the bar. To change fill pattern and fill color use setfillstyle. This function does not return any value.
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
/* The bar() function is used to draw a bar ( of bar graph) which is a 2-dimensional figure. It is filled rectangular figure. The function takes four arguments that are the coordinates of (X, Y) coordinates of the top-left corner of the bar {left and top } and (X, Y) coordinates of the bottom-right corner of the bar {right and bottom}. */ /* draw a filled-in, rectangular, two-dimensional bar by bar() function code example. */ #include <graphics.h> // driver code int main() { // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // "graphics.h" header file int gd = DETECT, gm; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, ""); // location of sides int left, top, right, bottom; // left, top, right, bottom denotes // location of rectangular bar bar(left = 150, top = 150, right = 190, bottom = 350); bar(left = 220, top = 250, right = 260, bottom = 350); bar(left = 290, top = 200, right = 330, bottom = 350); // y axis line line(100, 50, 100, 350); // x axis line line(100, 350, 400, 350); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0; }
What is an Multi-Dimensional Array
An array is a collection of data items, all of the same type, accessed using a common name. A one-dimensional array is like a list; A two dimensional array is like a table; The C++ language places no limits on the number of dimensions in an array, though specific implementations may. Some texts refer to one-dimensional arrays as vectors, two-dimensional arrays as matrices, and use the general term arrays when the number of dimensions is unspecified or unimportant.
Declaring Two-Dimensional Arrays
An array of arrays is known as 2D array. The two dimensional (2D) array in C++ programming is also known as matrix. A matrix can be represented as a table of rows and columns. In C/C++, we can define multi dimensional arrays in simple words as array of arrays. Data in multi dimensional arrays are stored in tabular form (in row major order). General form of declaring N-dimensional arrays is:
datatype arrayname[size1][size2]....[sizeN]; example: int 2d-array[8][16]; char letters[4][9]; float numbers[10][25];
Initializing Two-Dimensional Arrays
In the 1D array, we don't need to specify the size of the array if the declaration and initialization are being done simultaneously. However, this will not work with 2D arrays. We will have to define at least the second dimension of the array. The two-dimensional array can be declared and defined in the following way. Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an array with 3 rows and each row has 4 columns.
int numbers[3][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}};
Accessing Two-Dimensional Array Elements
Just like one-dimensional arrays, two-dimensional arrays also require indices to access the required elements. A row and a column index are needed to access a particular element; for nested loops, two indices (one to traverse the rows and the other to traverse the columns in each row) are required to print a two-dimensional array.
// an array with 3 rows and 2 columns. int x[3][2] = {{0,1}, {2,3}, {4,5}}; // output each array element's value for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) { cout << "Element at x[" << i << "][" << j << "]: "; cout << x[i][j]<<endl; } }
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
/* multi-dimensional arrays in C++ language */ /* taking input for two dimensional array */ #include <iostream> using namespace std; int main() { int numbers[2][3]; cout << "Enter 6 numbers: " << endl; // Storing user input in the array for (int i = 0; i < 2; ++i) { for (int j = 0; j < 3; ++j) { cin >> numbers[i][j]; } } cout << "The numbers are: " << endl; // Printing array elements for (int i = 0; i < 2; ++i) { for (int j = 0; j < 3; ++j) { cout << "numbers[" << i << "][" << j << "]: " << numbers[i][j] << 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; }
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; }
sound() Function in C++
Our system can create various sounds on different frequencies. The sound() is very useful as it can create very nice music with the help of programming and our user can enjoy music during working in out the program. Sound function produces the sound of a specified frequency. Used for adding music to a C++ program.
Syntax for sound() Function in C++
void sound(unsigned frequency);
frequency
the frequency of the sound
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* sound() function produces the sound of a specified frequency. */ int k; //loop to increment the value of a till 100. for ( k = 1 ; a <= 100 ; a = k++ ) { //calling the function for producing //the sound of value a. sound(a); //delay the sound 10 miliseconds. delay(10); } // function to stop the system sound. nosound(); return 0;
setfillstyle() Function in C++
The header file graphics.h contains setfillstyle() function which sets the current fill pattern and fill color. Current fill pattern and fill color is used to fill the area. setfillstyle sets the current fill pattern and fill color. To set a user-defined fill pattern, do not give a pattern of 12 (USER_FILL) to setfillstyle; instead, call setfillpattern.
Syntax for setfillstyle() Function in C++
#include<graphics.h> void setfillstyle(int pattern, int color);
color
Specify the color • 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
pattern
Specify the pattern • EMPTY_FILL – 0 • SOLID_FILL – 1 • LINE_FILL – 2 • LTSLASH_FILL – 3 • SLASH_FILL – 4 • BKSLASH_FILL – 5 • LTBKSLASH_FILL – 6 • HATCH_FILL – 7 • XHATCH_FILL – 8 • INTERLEAVE_FILL – 9 • WIDE_DOT_FILL – 10 • CLOSE_DOT_FILL – 11 • USER_FILL – 12 If invalid input is passed to setfillstyle, graphresult returns -1(grError), and the current fill pattern and fill color remain unchanged. The EMPTY_FILL style is like a solid fill using the current background color (which is set by setbkcolor). This function does not return any value.
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
/* The header file graphics.h contains setfillstyle() function which sets the current fill pattern and fill color. floodfill() function is used to fill an enclosed area. Current fill pattern and fill color is used to fill the area. */ #include <graphics.h> // driver code int main() { // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // "graphics.h" header file int gd = DETECT, gm; // initgraph initializes the // graphics system by loading // a graphics driver from disk initgraph(&gd, &gm, " "); // center and radius of circle int x_circle = 250; int y_circle = 250; int radius=100; // setting border color int border_color = WHITE; // set color and pattern setfillstyle(HATCH_FILL,RED); // x and y is a position and // radius is for radius of circle circle(x_circle,y_circle,radius); // fill the color at location // (x, y) with in border color floodfill(x_circle,y_circle,border_color); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system closegraph(); return 0; }
outtextxy() Function in C++
outtextxy displays a text string in the viewport at the given position (x, y), using the current justification settings and the current font, direction, and size. To maintain code compatibility when using several fonts, use textwidth and textheight to determine the dimensions of the string. If a string is printed with the default font using outtext or outtextxy, any part of the string that extends outside the current viewport is truncated. outtextxy is for use in graphics mode; it will not work in text mode.
Syntax for outtextxy() Function in C++
#include <graphics.h> void outtextxy(int x, int y, char *string);
x
x-coordinate of the point
y
y-coordinate of the point
string
string to be displayed where, x, y are coordinates of the point and, third argument contains the address of string to be displayed. This function does not return any value.
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
/* outtextxy() function displays the text or string at a specified point (x, y) on the screen. */ // C++ Implementation for outtextxy() #include <graphics.h> int main() { textcolor(RED); cleardevice(); setcolor(RED); outtextxy(150,205,"Enter the Username:"); outtextxy(150,245,"Enter the Password:"); outtextxy(150,355,"Thank you"); outtextxy(150,445,"nice job"); outtextxy(50,105,"good day"); outtextxy(50,145,"pan"); outtextxy(50,255,"go"); outtextxy(50,245,"nice day"); return 0; }
cleardevice() Function in C++
The header file graphics.h contains cleardevice() function. cleardevice() is a function which is used to clear the screen by filling the whole screen with the current background color. It means that cleardevice() function is used to clear the whole screen with the current background color and it also sets the current position to (0,0). Both clrscr() and cleardevice() functions are used to clear the screen but clrscr() is used in text mode and cleardevice function is used in the graphics mode.
Syntax for cleardevice() Function in C++
#include <graphics.h> void cleardevice();
Clearing the screen is always an issue for developers, because now and then we want to show the user some useful or important data, which should be highlighted or at least have user's attention. It is important to note that, after clearing the device, we will lose all our drawing, shapes or images. It is useful but be little cautious. This function does not return any value.
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
/* cleardevice erases (that is, fills with the current background color) the entire graphics screen and moves the CP (current position) to home (0,0). */ #include <graphics.h> int main() { clrscr(); cleardevice(); int flag=44; setbkcolor(3); draw(); char m[20]; char a[20][20]={"2xqwer4fgi","trewq9y3ry","yuip7qtgfm","jpiuy9bph6","klkjh6decc", "etlhjklo2k","lasdfapl4z","efghjv5qy","mmjnhlmt8t","134rfvup5n"}; randomize(); int r=random(10)+1; settextstyle(SCRIPT_FONT, HORIZ_DIR, 5); outtextxy(190,0,"level 8"); line(190,60, 300, 60); settextstyle(SCRIPT_FONT, HORIZ_DIR, 3); outtextxy(0,100,"\nplease this is the last time!!!"); cout<<endl<<endl<<endl<<endl<<endl<<endl<<endl<<endl<<endl<<"\t"; for(int i=0;a[r][i]!='\0';i++) { cout<<a[r][i]; td(); cout<<" "; td(); } clrscr(); cleardevice(); return 0; }
Delete Operator in C++
Deallocate storage space. Default deallocation functions (single-object form). A delete operator is used to deallocate memory space that is dynamically created using the new operator, calloc and malloc() function, etc., at the run time of a program in C++ language. In other words, a delete operator is used to release array and non-array (pointer) objects from the heap, which the new operator dynamically allocates to put variables on heap memory. We can use either the delete operator or delete [ ] operator in our program to delete the deallocated space. A delete operator has a void return type, and hence, it does not return a value.
Syntax for Delete Operator in C++
//ordinary (1) void operator delete (void* ptr) noexcept; //nothrow (2) void operator delete (void* ptr, const std::nothrow_t& nothrow_constant) noexcept; //placement (3) void operator delete (void* ptr, void* voidptr2) noexcept;
ptr
A pointer to the memory block to be released, type-casted to a void*. If this is a null-pointer, the function does nothing. If not null, this pointer value should have been returned by a previous call to operator new, and have not yet been released by a previous call to this function. If the implementation has strict pointer safety, this pointer shall also be a safely-derived pointer.
nothrow_constant
The constant nothrow. This parameter is ignored in the default definition. nothrow_t is the type of constant nothrow.
voidptr2
A void pointer. The value is ignored in the default definition.
size
The first argument passed to the allocation function when the memory block was allocated. std::size_t is an unsigned integral type. This function does not return any value. (1) ordinary delete: Deallocates the memory block pointed by ptr (if not null), releasing the storage space previously allocated to it by a call to operator new and rendering that pointer location invalid. (2) nothrow delete: Same as above (1). The default definition calls the first version (1): ::operator delete(ptr). (3) placement delete: Does nothing. The default allocation and deallocation functions are special components of the standard library; They have the following unique properties: Global: All overloads of operator delete are declared in the global namespace, not within the std namespace. Implicit: The deallocating versions (i.e., all but (3)) are implicitly declared in every translation unit of a C++ program, no matter whether header <new> is included or not. Replaceable: The deallocating versions (i.e., all but (3)) are also replaceable: A program may provide its own definition that replaces the one provided by default or can overload it for specific types. The custom definition shall deallocate the storage referenced by ptr. operator delete is a regular function that can be called explicitly just as any other function. But in C++, delete is an operator with a very specific behavior: An expression with the delete operator, first calls the appropriate destructor (for class types), and then calls a deallocation function. The deallocation function for a class object is a member function named operator delete, if it exists. In all other cases it is a global function operator delete (i.e., this function -- or a more specific overload). If the delete expression is preceded by the scope operator (i.e., ::operator delete), only global deallocation functions are considered. delete expressions that use global deallocation functions always use the signature that takes either a pointer (such as (1)), or a pointer and a size (such as (4)). Preferring always the version with size (4), unless an overload provides a better match for the pointer type. The other signatures ((2) and (3)) are never called by a delete-expression (the delete operator always calls the ordinary version of this function, and exactly once for each of its arguments). These other signatures are only called automatically by a new-expression when their object construction fails (e.g., if the constructor of an object throws while being constructed by a new-expression with nothrow, the matching operator delete function accepting a nothrow argument is called). Non-member deallocation functions shall not be declared in a namespace scope other than the global namespace.
Data races
Modifies the storage referenced by ptr. Calls to allocation and deallocation functions that reuse the same unit of storage shall occur in a single total order where each deallocation happens before the next allocation. This shall also apply to the observable behavior of custom replacements for this function.
Exception safety
No-throw guarantee: this function never throws exceptions. Notice that either an invalid value of ptr, or a value for size that does not match the one passed to the allocation function, causes undefined behavior. Similarly, we can delete the block of allocated memory space using the delete [] operator. delete [ ] pointer_variable; // delete [] ptr; It deallocate for an array.
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
/* deallocate storage space by delete operator */ #include <iostream> using namespace std; int main () { // declaration of variables int *ptr1, *ptr2, sum; // allocated memory space using new operator ptr1 = new int; ptr2 = new int; cout << " Enter first number: "; cin >> *ptr1; cout << " Enter second number: "; cin >> *ptr2; sum = *ptr1 + *ptr2; cout << " Sum of pointer variables = " << sum; // delete pointer variables delete ptr1; delete ptr2; return 0; }
initgraph() Function in C++
To create a program in Graphics Mode, the first step would be to include the header file graphics.h. This file is required for Graphics programming. After this, the graphics have to be initialized. C Language supports 16 Bit's MS-DOS environment. Initializing the Graphics mode is to call various functions, one such is called initgraph. initgraph initializes the graphics system by loading a graphics driver from disk (or validating a registered driver), and putting the system into graphics mode. To start the graphics system, first call the initgraph function. initgraph loads the graphics driver and puts the system into graphics mode. You can tell initgraph to use a particular graphics driver and mode, or to autodetect the attached video adapter at run time and pick the corresponding driver. If you tell initgraph to autodetect, it calls detectgraph to select a graphics driver and mode. initgraph also resets all graphics settings to their defaults (current position, palette, color, viewport, and so on) and resets graphresult to 0.
Syntax for initgraph() Function in C++
void initgraph (int *graphdriver, int *graphmode, char *pathtodriver);
graphdriver
This is an integer that indicates that the graphics driver has been used.
graphmode
It is also an integer value that detects the available graphics driver and initializes the graphics mode according to its highest resolution.
pathtodriver
This is the path of the directory that first searches the initgraph function graphics driver. If the graphics driver is not available then the system searches it in the current directory. It is necessary to pass the correct value of the three parameters in the initgraph function or else an unpredictable output is obtained.
intgd = DETECT, gm; initgraph (&gd, &gm, " ");
To initialize Graphics mode, you only have to write two lines. Here, we have taken two integer variables 'd' and 'm'. Here, DETECT is an enumeration type that identifies and identifies the proper graphics driver. The initgraph function has to pass the address of both the variables. You can see in the example that we have given a space at the position of the third variable. This means that if you do not know the driver's path then you can leave it blank. The compiler will auto-detect the path. initgraph always sets the internal error code; on success, it sets the code to 0. If an error occurred, *graphdriver is set to -2, -3, -4, or -5, and graphresult returns the same value as listed below: • grNotDetected -2 Cannot detect a graphics card • grFileNotFound -3 Cannot find driver file • grInvalidDriver -4 Invalid driver • grNoLoadMem -5 Insufficient memory to load driver
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
/* initgraph initializes the graphics system by loading a graphics driver from disk (or validating a registered driver), and putting the system into graphics mode. To start the graphics system, first call the initgraph function. initgraph loads the graphics driver and puts the system into graphics mode. You can tell initgraph to use a particular graphics driver and mode, or to autodetect the attached video adapter at run time and pick the corresponding driver. */ int DGraphics::Init( int gmode ) { int gdriver = VGA, errorcode; gdriver=installuserdriver("SVGA256",NULL); initgraph(&gdriver, &gmode, ""); if ( (errorcode = graphresult()) != grOk ) { cout << "Error: Graphics - %s\n" << grapherrormsg(errorcode); return FALSE; } ActiveMode=gmode; return TRUE; }
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; }
setbkcolor() Function in C++
setbkcolor() function is used to set the background color in graphics mode. The default background color is black and default drawing color as we know is white. setbkcolor() function takes only one argument it would be either the name of color defined in graphics.h header file or number associated with those colors. If we write setbkcolor(yellow) it changes the background color in Green. The possible color values are from 0 - 15 black, blue, green, cyan, red, magenta, brown, lightgray, darkgray, lightblue, lightgreen, lightcyan, lightred, lightmagenta, yellow, white and blink (128).
Syntax for setbkcolor() Function in C++
#include<graphics> void setbkcolor(int color);
color
specify the color setbkcolor sets the background to the color specified by color. The argument color can be a name or a number as listed below. (These symbolic names are defined in graphics.h.) This function does not return any value. 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 24 25 26
/* change the background to the color specified by color in graphics mode. */ /* Program to make digital clock in C++ graphics */ #include<graphics> #include<conio.h> #include<time.h> int main() { initwindow(700,500,"CLOCK",300,100);//displays graphics window char t[15],date[10]; while(1) { setbkcolor(5);//set background color _strtime(t);//pick system time and saves in char array setcolor(11);//color of time settextstyle(4, HORIZ_DIR, 8);//font of time outtextxy(100, 100, t);//prints time delay(1000); } getch(); closegraph(); }
Continue Statement in C++
Continue statement is used inside loops. Whenever a continue statement is encountered inside a loop, control directly jumps to the beginning of the loop for next iteration, skipping the execution of statements inside loop's body for the current iteration. The continue statement works somewhat like the break statement. Instead of forcing termination, however, continue forces the next iteration of the loop to take place, skipping any code in between. For the for loop, continue causes the conditional test and increment portions of the loop to execute. For the while and do...while loops, program control passes to the conditional tests.
Syntax for Continue Statement in C++
loop-statement{ continue; }
As the name suggest the continue statement forces the loop to continue or execute the next iteration. When the continue statement is executed in the loop, the code inside the loop following the continue statement will be skipped and next iteration of the loop will begin.
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
/* continue statement skips the execution of further statements in the block and continues with the next iteration. */ // program to calculate positive numbers till 50 only // if the user enters a negative number, // that number is skipped from the calculation // negative number -> loop terminate // numbers above 50 -> skip iteration #include <iostream> using namespace std; int main() { int sum = 0; int number = 0; while (number >= 0) { // add all positive numbers sum += number; // take input from the user cout << "Enter a number: "; cin >> number; // continue condition if (number > 50) { cout << "The number is greater than 50 and won't be calculated." << endl; number = 0; // the value of number is made 0 again continue; } } // display the sum cout << "The sum is " << sum << endl; return 0; }
sprintf() Function in C++
Write formatted data to string. Composes a string with the same text that would be printed if format was used on printf, but instead of being printed, the content is stored as a C string in the buffer pointed by str. The size of the buffer should be large enough to contain the entire resulting string (see snprintf for a safer version). A terminating null character is automatically appended after the content. After the format parameter, the function expects at least as many additional arguments as needed for format.
Syntax for sprintf() Function in C++
#include <cstdio> int sprintf ( char * str, const char * format, ... );
str
Pointer to a buffer where the resulting C-string is stored. The buffer should be large enough to contain the resulting string.
format
C string that contains a format string that follows the same specifications as format in printf (see printf for details).
... (additional arguments)
Depending on the format string, the function may expect a sequence of additional arguments, each containing a value to be used to replace a format specifier in the format string (or a pointer to a storage location, for n). There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function. On success, the total number of characters written is returned. This count does not include the additional null-character automatically appended at the end of the string. On failure, a negative number is returned. The format parameter of printf() can contain format specifiers that begin with %. These specifiers are replaced by the values of respective variables that follow the format string.
flags
one or more flags that modifies the conversion behavior (optional)
-
Left-justify within the given field width; Right justification is the default (see width sub-specifier).
+
Forces to preceed the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a - sign.
(space)
If no sign is going to be written, a blank space is inserted before the value.
#
Used with o, x or X specifiers the value is preceeded with 0, 0x or 0X respectively for values different than zero. Used with a, A, e, E, f, F, g or G it forces the written output to contain a decimal point even if no more digits follow. By default, if no digits follow, no decimal point is written.
0
Left-pads the number with zeroes (0) instead of spaces when padding is specified (see width sub-specifier).
width
an optional * or integer value used to specify minimum width field.
(number)
Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.
*
The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
.precision
an optional field consisting of a . followed by * or integer or nothing to specify the precision.
.number
For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0. For a, A, e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6). For g and G specifiers: This is the maximum number of significant digits to be printed. For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered. If the period is specified without an explicit value for precision, 0 is assumed.
.*
The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
length
an optional length modifier that specifies the size of the argument.
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
/* The sprintf() function in C++ is used to write a formatted string to character string buffer. It is defined in the cstdio header file. */ /* Write formatted data to string by sprintf() function code example */ #include <cstdio> #include <iostream> using namespace std; int main() { char buffer[100]; int count; char name[] = "Max"; int age = 23; // write combination of strings and variables to buffer variable // store the number of characters written in count count = sprintf(buffer, "Hi, I am %s and I am %d years old", name, age); // print the string buffer cout << buffer << endl; // print the number of characters written cout << "Number of characters written = " << count; 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; }
nosound() Function in C++
The nosound() function in C language is used to stop the sound played by sound() function. The nosound() function is simply silent the system. The sound() and nosound() functions are very useful as they can create very nice music with the help of programming and our user can enjoy music during working in out the program.
Syntax for nosound() Function in C++
void nosound();
You can use the function nosound to turn off the PC speaker.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/* you can simply silent the system by nosound() function code example. */ #include <stdio.h> //to use 'sound()', 'delay()' functions #include <dos.h> int main() { //calling the function for producing //the sound of frequency 400. sound(400); //function to delay the sound for //half of second. delay(500); //calling the function to stop the //system sound. nosound(); 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; }
#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; }
Memory Management new Operator in C++
Allocate storage space. Default allocation functions (single-object form). A new operator is used to create the object while a delete operator is used to delete the object. When the object is created by using the new operator, then the object will exist until we explicitly use the delete operator to delete the object. Therefore, we can say that the lifetime of the object is not related to the block structure of the program.
Syntax for new Operator in C++
#include <new> //throwing (1) void* operator new (std::size_t size); //nothrow (2) void* operator new (std::size_t size, const std::nothrow_t& nothrow_value) noexcept; //placement (3) void* operator new (std::size_t size, void* ptr) noexcept;
size
Size in bytes of the requested memory block. This is the size of the type specifier in the new-expression when called automatically by such an expression. If this argument is zero, the function still returns a distinct non-null pointer on success (although dereferencing this pointer leads to undefined behavior). size_t is an integral type.
nothrow_value
The constant nothrow. This parameter is only used to distinguish it from the first version with an overloaded version. When the nothrow constant is passed as second parameter to operator new, operator new returns a null-pointer on failure instead of throwing a bad_alloc exception. nothrow_t is the type of constant nothrow.
ptr
A pointer to an already-allocated memory block of the proper size. If called by a new-expression, the object is initialized (or constructed) at this location. For the first and second versions, function returns a pointer to the newly allocated storage space. For the third version, ptr is returned. • (1) throwing allocation: Allocates size bytes of storage, suitably aligned to represent any object of that size, and returns a non-null pointer to the first byte of this block. On failure, it throws a bad_alloc exception. • (2) nothrow allocation: Same as above (1), except that on failure it returns a null pointer instead of throwing an exception. The default definition allocates memory by calling the the first version: ::operator new (size). If replaced, both the first and second versions shall return pointers with identical properties. • (3) placement: Simply returns ptr (no storage is allocated). Notice though that, if the function is called by a new-expression, the proper initialization will be performed (for class objects, this includes calling its default constructor). The default allocation and deallocation functions are special components of the standard library; They have the following unique properties: • Global: All three versions of operator new are declared in the global namespace, not within the std namespace. • Implicit: The allocating versions ((1) and (2)) are implicitly declared in every translation unit of a C++ program, no matter whether header <new> is included or not. • Replaceable: The allocating versions ((1) and (2)) are also replaceable: A program may provide its own definition that replaces the one provided by default to produce the result described above, or can overload it for specific types. If set_new_handler has been used to define a new_handler function, this new-handler function is called by the default definitions of the allocating versions ((1) and (2)) if they fail to allocate the requested storage. operator new can be called explicitly as a regular function, but in C++, new is an operator with a very specific behavior: An expression with the new operator, first calls function operator new (i.e., this function) with the size of its type specifier as first argument, and if this is successful, it then automatically initializes or constructs the object (if needed). Finally, the expression evaluates as a pointer to the appropriate type.
Data races
Modifies the storage referenced by the returned value. Calls to allocation and deallocation functions that reuse the same unit of storage shall occur in a single total order where each deallocation happens entirely before the next allocation. This shall also apply to the observable behavior of custom replacements for this function.
Exception safety
The first version (1) throws bad_alloc if it fails to allocate storage. Otherwise, it throws no exceptions (no-throw guarantee).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
/* C++ allows us to allocate the memory of a variable or an array in run time. This is known as dynamic memory allocation. The new operator denotes a request for memory allocation on the Free Store. If sufficient memory is available, new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable. */ /* Allocate storage space by operator new */ // C++ program code example to illustrate dynamic allocation and deallocation of memory using new and delete #include <iostream> using namespace std; int main () { // Pointer initialization to null int* p = NULL; // Request memory for the variable // using new operator p = new(nothrow) int; if (!p) cout << "allocation of memory failed\n"; else { // Store value at allocated address *p = 29; cout << "Value of p: " << *p << endl; } // Request block of memory // using new operator float *r = new float(75.25); cout << "Value of r: " << *r << endl; // Request block of memory of size n int n = 5; int *q = new(nothrow) int[n]; if (!q) cout << "allocation of memory failed\n"; else { for (int i = 0; i < n; i++) q[i] = i+1; cout << "Value store in block of memory: "; for (int i = 0; i < n; i++) cout << q[i] << " "; } // freed the allocated memory delete p; delete r; // freed the block of allocated memory delete[] q; return 0; }
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; }
Structures in C++ Language
In C++, classes and structs are blueprints that are used to create the instance of a class. Structs are used for lightweight objects such as Rectangle, color, Point, etc. Unlike class, structs in C++ are value type than reference type. It is useful if you have data that is not intended to be modified after creation of struct. C++ Structure is a collection of different data types. It is similar to the class that holds different types of data.
Syntax for Structures in C++
struct structureName{ member1; member2; member3; . . . memberN; };
A structure is declared by preceding the struct keyword followed by the identifier(structure name). Inside the curly braces, we can declare the member variables of different types. Consider the following situation:
struct Teacher { char name[20]; int id; int age; }
In the above case, Teacher is a structure contains three variables name, id, and age. When the structure is declared, no memory is allocated. When the variable of a structure is created, then the memory is allocated. Let's understand this scenario. Structures in C++ can contain two types of members: • Data Member: These members are normal C++ variables. We can create a structure with variables of different data types in C++. • Member Functions: These members are normal C++ functions. Along with variables, we can also include functions inside a structure declaration. Structure variable can be defined as: Teacher s; Here, s is a structure variable of type Teacher. When the structure variable is created, the memory will be allocated. Teacher structure contains one char variable and two integer variable. Therefore, the memory for one char variable is 1 byte and two ints will be 2*4 = 8. The total memory occupied by the s variable is 9 byte. The variable of the structure can be accessed by simply using the instance of the structure followed by the dot (.) operator and then the field of the structure.
s.id = 4;
We are accessing the id field of the structure Teacher by using the dot(.) operator and assigns the value 4 to the id field. In C++, the struct keyword is optional before in declaration of a variable. In C, it is mandatory.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
/* Structure is a collection of variables of different data types under a single name. It is similar to a class in that, both holds a collecion of data of different data types. */ #include <iostream> using namespace std; struct Person { char name[50]; int age; float salary; }; int main() { Person p1; cout << "Enter Full name: "; cin.get(p1.name, 50); cout << "Enter age: "; cin >> p1.age; cout << "Enter salary: "; cin >> p1.salary; cout << "\nDisplaying Information." << endl; cout << "Name: " << p1.name << endl; cout <<"Age: " << p1.age << endl; cout << "Salary: " << p1.salary; return 0; }
setcolor() Function in C++
setcolor() function is used to set the foreground color in graphics mode. After resetting the foreground color you will get the text or any other shape which you want to draw in that color. setcolor sets the current drawing color to color, which can range from 0 to getmaxcolor. The current drawing color is the value to which pixels are set when lines, and so on are drawn. The drawing colors shown below are available for the CGA and EGA, respectively.
Syntax for setcolor() Function in C++
void setcolor(int color);
color
specify the color setcolor() functions contains only one argument that is color. It may be the color name enumerated in graphics.h header file or number assigned with that color. This function does not return any value. 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 24 25 26 27 28 29 30 31 32
/* setcolor() function change the current drawing color in graphic mode. */ #include<stdio.h> #include<conio.h> #include<graphics.h> void main() { int gd=DETECT,gm; initgraph(&gd,&gm," "); setbkcolor(5);//set background color setcolor(11);//color of time settextstyle(4, HORIZ_DIR, 8);//font of time setcolor(GREEN); circle(320,240,100); setcolor(RED); outtextxy(320,80."It is circle"); getch(); closegraph(); }
Friend Functions in C++
A friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class. Even though the prototypes for friend functions appear in the class definition, friends are not member functions. A friend can be a function, function template, or member function, or a class or class template, in which case the entire class and all of its members are friends. If a function is defined as a friend function in C++ programming language, then the protected and private data of a class can be accessed using the function. By using the keyword friend compiler knows the given function is a friend function. For accessing the data, the declaration of a friend function should be done inside the body of a class starting with the keyword friend.
Syntax for Friend Functions in C++
class class_name { friend data_type function_name(argument/s); // syntax of friend function. };
In the above declaration, the friend function is preceded by the keyword friend. The function can be defined anywhere in the program like a normal C++ function. The function definition does not use either the keyword friend or scope resolution operator. • The function is not in the scope of the class to which it has been declared as a friend. • It cannot be called using the object as it is not in the scope of that class. • It can be invoked like a normal function without using the object. • It cannot access the member names directly and has to use an object name and dot membership operator with the member name. • It can be declared either in the private or the public part. A friend class can access both private and protected members of the class in which it has been declared as friend.
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
/* a friend function can access the private and protected data of a class. */ // C++ program to demonstrate the working of friend function #include <iostream> using namespace std; class Distance { private: int meter; // friend function friend int addFive(Distance); public: Distance() : meter(0) {} }; // friend function definition int addFive(Distance d) { //accessing private members from the friend function d.meter += 5; return d.meter; } int main() { Distance D; cout << "Distance: " << addFive(D); return 0; }
kbhit() Function in C++
The kbhit is basically the Keyboard Hit. This function is present at conio.h header file. So for using this, we have to include this header file into our code. The functionality of kbhit() is that, when a key is pressed it returns nonzero value, otherwise returns zero. kbhit() is used to determine if a key has been pressed or not. If a key has been pressed then it returns a non zero value otherwise returns zero.
Syntax for kbhit() Function in C++
#include <conio.h> int kbhit();
Function returns true (non-zero) if there is a character in the input buffer, otherwise false. Note : kbhit() is not a standard library function and should be avoided.
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
/* kbhit() function is not defined as part of the ANSI C/C++ standard. It is generally used by Borland's family of compilers. It returns a non-zero integer if a key is in the keyboard buffer. It will not wait for a key to be pressed. */ // C++ program code example to fetch key pressed using kbhit() #include <conio.h> #include <iostream> int main() { char ch; while (1) { if (kbhit) { // Stores the pressed key in ch ch = getch(); // Terminates the loop // when escape is pressed if (int(ch) == 27) break; cout << "Key pressed= " << ch; } } 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; }
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; }
settextstyle() Function in C++
Settextstyle function is used to change the way in which text appears, using it we can modify the size of text, change direction of text and change the font of text. settextstyle sets the text font, the direction in which text is displayed, and the size of the characters. A call to settextstyle affects all text output by outtext and outtextxy.
Syntax for settextstyle() Function in C++
#include <graphics.h> void settextstyle(int font, int direction, int charsize);
font
One 8x8 bit-mapped font and several "stroked" fonts are available. The 8x8 bit-mapped font is the default. The enumeration font_names, which is defined in graphics.h, provides names for these different font settings: • DEFAULT_FONT – 0 8x8 bit-mapped font • TRIPLEX_FONT – 1 Stroked triplex font • SMALL_FONT – 2 Stroked small font • SANS_SERIF_FONT – 3 Stroked sans-serif font • GOTHIC_FONT – 4 Stroked gothic font • SCRIPT_FONT – 5 Stroked script font • SIMPLEX_FONT – 6 Stroked triplex script font • TRIPLEX_SCR_FONT – 7 Stroked triplex script font • COMPLEX_FONT – 8 Stroked complex font • EUROPEAN_FONT – 9 Stroked European font • BOLD_FONT – 10 Stroked bold font The default bit-mapped font is built into the graphics system. Stroked fonts are stored in *.CHR disk files, and only one at a time is kept in memory. Therefore, when you select a stroked font (different from the last selected stroked font), the corresponding *.CHR file must be loaded from disk. To avoid this loading when several stroked fonts are used, you can link font files into your program. Do this by converting them into object files with the BGIOBJ utility, then registering them through registerbgifont.
direction
Font directions supported are horizontal text (left to right) and vertical text (rotated 90 degrees counterclockwise). The default direction is HORIZ_DIR. The size of each character can be magnified using the charsize factor. If charsize is nonzero, it can affect bit-mapped or stroked characters. A charsize value of 0 can be used only with stroked fonts.
charsize
• If charsize equals 1, outtext and outtextxy displays characters from the 8x8 bit-mapped font in an 8x8 pixel rectangle onscreen. • If charsize equals 2, these output functions display characters from the 8x8 bit-mapped font in a 16*16 pixel rectangle, and so on (up to a limit of ten times the normal size). • When charsize equals 0, the output functions outtext and outtextxy magnify the stroked font text using either the default character magnification factor (4) or the user-defined character size given by setusercharsize. Always use textheight and textwidth to determine the actual dimensions of the text. This function needs to be called before the outtextxy() function, otherwise there will be no effect on text and output will be the same.
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
/* settextstyle() function sets the current text font, direction and character size. All calls to outtext() and outtextxy() are affected by the new settings. */ int main() { int gm, gd; gd = VGA; gm = VGAHI; initgraph(&gd, &gm, ""); settextstyle(SANS_SERIF_FONT, HORIZ_DIR, 4); outtextxy(32, 8, "SANS_SERIF_FONT"); settextstyle(DEFAULT_FONT, HORIZ_DIR, 4); outtextxy(32, 58, "DEFAULT_FONT"); settextstyle(GOTHIC_FONT, HORIZ_DIR, 4); outtextxy(32, 108, "GOTHIC_FONT"); settextstyle(SCRIPT_FONT, HORIZ_DIR, 4); outtextxy(32, 158, "SCRIPT_FONT"); getch(); closegraph(); }
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() }
rectangle() Function in C++
rectangle() is used to draw a rectangle. Coordinates of left top and right bottom corner are required to draw the rectangle. left specifies the X-coordinate of top left corner, top specifies the Y-coordinate of top left corner, right specifies the X-coordinate of right bottom corner, bottom specifies the Y-coordinate of right bottom corner.
Syntax for rectangle() Function in C++
rectangle(int left, int top, int right, int bottom);
left
X coordinate of top left corner.
top
Y coordinate of top left corner.
right
X coordinate of bottom right corner.
bottom
Y coordinate of bottom right corner. To create a rectangle, you have to pass the four parameters in this function. The two parameters represent the left and top upper left corner. Similarly, the right bottom parameter represents the lower right corner of the rectangle. This function does not return any value.
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
/* function rectangle() draws a rectangle in graphic mode. */ int main() { // location of left, top, right, bottom int left = 150, top = 150; int right = 450, bottom = 450; // initgraph initializes the graphics system // by loading a graphics driver from disk initgraph(&gd, &gm, ""); // rectangle function rectangle(left, top, right, bottom); left = 200, = 250; right = 150, = 300; rectangle(left, top, right, bottom); left = 100, = 200; right = 450, = 100; rectangle(left, top, right, bottom); getch(); 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; }
fillellipse() Function in C++
Draws an ellipse using (x,y) as a center point and xradius and yradius as the horizontal and vertical axes, and fills it with the current fill color and fill pattern. The header file graphics.h contains fillellipse() function which draws and fills an ellipse with center at (x, y) and (xradius, yradius) as x and y radius of ellipse. Where, (x, y) is center of the ellipse. (xradius, yradius) are x and y radius of ellipse.
Syntax for fillellipse() Function in C++
#include <graphics.h> void fillellipse(int x, int y, int xradius, int yradius);
x
x coordinate of center of the ellipse
y
y coordinate of center of the ellipse
xradius
horizontal axes of the ellipse
yradius
vertical axes of the ellipse This function does not return any value.
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
/* fillellipse() function draws an ellipse and fill it with current drawing color and pattern. */ /* draws an ellipse and fill it by fillellipse() function code example */ #include <graphics.h> // driver code int main() { // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // "graphics.h" header file int gd = DETECT, gm; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, ""); // fillellipse fuction fillellipse(200, 200, 50, 90); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0; }


'C++ program' in which user enter a number, program reverse it and display the reversed number on the console. If the 'input number' is 12345 Then reversed number will be 54321
Randomly select pivot value from the subpart of the array. Partition that subpart so that the values left of the 'pivot' are smaller and to the right are greater from the pivot. And consider
#include: This statements tells the compiler to include iostream file. This file contains pre defined "input/output functions" that we can use in our program. Comments as the names