Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes


C++ Programming Code Examples

C++ > Games Code Examples

Brainvita - Game in C++ (Project)

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 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
/* Brainvita - Game in C++ (Project) */ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> #include <dos.h> #include <time.h> #include <bios.h> #define UP 72 #define DOWN 80 #define LEFT 75 #define RIGHT 77 #define ENTER 13 #define ESC 27 #define YES 1 #define NO 0 int x=320,y=100,marble=32,marble_color=12; void *p; size_t area; // Matrix of board int board[7][7]= { {-1,-1,1,1,1,-1,-1}, {-1,-1,1,1,1,-1,-1}, { 1, 1,1,1,1, 1, 1}, { 1, 1,1,1,1, 1, 1}, { 1, 1,1,1,1, 1, 1}, {-1,-1,1,1,1,-1,-1}, {-1,-1,1,1,1,-1,-1} }; //------------------------------------------------------------------------ // Function Prototypes //------------------------------------------------------------------------ void Marble(int x,int y,int c); void G(); int check(); int GetXY(int X,int Y); int GetBoard(int X,int Y); void SetBoard(int X,int Y,int element); void Blink(int x,int y,int c); void DrawBoard(); int MakeMove(int X,int Y); void Init(); int finish(); void win(char *text,int sx,int sy,int ex,int ey,int ck); void winp(int sx,int sy,int ex,int ey,int state); void Menu(); void LCD(int left,int top,int NUM); void Lcd(int x,int y,int n); void Intro(); void Drawborder(int x,int y); void Background(); int load_game (); int save_game(); //------------------------------------------------------------------------ // Main Function //------------------------------------------------------------------------ void main() { int i; G(); Intro(); Background(); DrawBoard(); Marble(320,220,0); board[3][3]=0; Init(); setcolor(0); for(i=0;i<=220;i++) { rectangle(0+i,0+i,640-i,480-i); delay(10); } for(i=0;i<=220;i++) { rectangle(100+i,100,540-i,380); delay(8); } closegraph(); getch(); } void Marble(int x,int y,int c) { setfillstyle(1,c); setcolor(c); fillellipse(x,y,8,8); if(c!=0) { if(c==15){setcolor(7);setfillstyle(1,7);} else {setfillstyle(1,15);setcolor(15);} fillellipse(x+3,y-2,1,2); } } void mydelay(float secs) { clock_t start, end; start = clock(); do { end = clock(); if(kbhit()) break; }while(((end - start)/CLK_TCK)<secs); } void Intro() { int i; char pattern[8] ={0xfe,0xbc,0xda,0xe4,0xe2,0xc0,0x88,0x00}; setfillpattern(pattern,1); bar(0,0,640,480); settextstyle(1,0,5); setcolor(10); getch(); setcolor(0); for(i=0;i<=320;i++) { rectangle(0+i,0,640-i,480); delay(5); } // win("BRAINVITA",1,1,638,478,1); } void Drawborder(int x,int y) { setwritemode(COPY_PUT); setcolor(0); line(x+60,y-20,x+180,y-20);// __ line(x+60,y+60,x+60,y-20);// | line(x-40,y+60,x+60,y+60);// __ line(x-40,y+60,x-40,y+180);// | setcolor(15); line(x-40,y+180,x+60,y+180);// __ setcolor(0); line(x+60,y+180,x+60,y+280);// | setcolor(15); line(x+180,y-20,x+180,y+60);// | setcolor(0); line(x+180,y+60,x+290,y+60);// __ setcolor(15); line(x+290,y+60,x+290,y+180);// | line(x+180,y+180,x+290,y+180);// __ line(x+180,y+180,x+180,y+280);// | line(x+180,y+280,x+60,y+280);// __ setwritemode(XOR_PUT); } void Background() { int i; setfillstyle(1,3); bar(0,0,640,480); for(i=0;i<=15;i++) { setcolor(i); rectangle(0+i,0+i,640-i,480-i); } win("BRAINVITA",145,45,505,400,1); // winp(159,79,491,381,1); win("Keys",24,45,135,290,1); win("Help !",510,45,625,250,1); setfillstyle(1,0); bar(35,75,125,280); bar(520,75,618,240); winp(35,75,125,280,1); winp(520,75,618,240,1); setcolor(14); settextstyle(2,0,4); outtextxy(42,80,"Keys used"); setcolor(15); outtextxy(42,100,"+ or- : color"); outtextxy(47,120,"³ : Up"); outtextxy(47,140,"³ : Down"); outtextxy(42,160,"<- : Left"); outtextxy(42,180,"-> : Right"); outtextxy(42,200,"Enter : Pick"); outtextxy(42,220,"S : save game"); outtextxy(42,240,"L : load game"); outtextxy(42,260,"Esc : Exit"); line(47,120,50,123); line(47,120,43,123); line(47,140,50,143); line(47,140,43,143); outtextxy(523,80,"Use Arrow Keys"); outtextxy(523,100,"to move around"); outtextxy(523,120,"then press enter"); outtextxy(523,140,"to select any"); outtextxy(523,160,"marble,then jump"); outtextxy(523,180,"over another to"); outtextxy(523,200,"remove it."); win("",190,410,480,460,0); setfillstyle(1,0); bar(200,420,470,450); settextstyle(1,0,3); setcolor(10); outtextxy(220,420,"Marbles :"); } //------------------------------------------------------------------------ // Draw The Whole Board on Screen //------------------------------------------------------------------------ void DrawBoard() { int i,j,x=200,y=100; x=200;y=100; setfillstyle(1,1); bar(x-40,y-20,x+290,y+280); setfillstyle(1,7); bar(x-41,y-21,x+60,y+60); bar(x+180,y-21,x+290,y+60); bar(x-41,y+180,x+60,y+290); bar(x+180,y+180,x+290,y+290); Drawborder(x,y); Drawborder(x+1,y+1); setfillstyle(1,12); setcolor(11); for(i=0;i<7;i++) { for(j=0;j<7;j++) { if(board[j][i]!=-1) { if(board[j][i]==1) Marble(x,y,marble_color); if(board[j][i]==0) Marble(x,y,0); } x+=40; } x=200; y+=40; } settextstyle(1,0,3); } //------------------------------------------------------------------------ // Switch Into Graphics mode //------------------------------------------------------------------------ void G() { int gdriver = DETECT, gmode, errorcode; /* // for stand alone registerfarbgidriver(EGAVGA_driver_far); registerfarbgifont(sansserif_font_far); registerfarbgifont(small_font_far); registerfarbgifont(gothic_font_far); registerfarbgifont(triplex_font_far); */ initgraph(&gdriver, &gmode, ""); errorcode = graphresult(); if (errorcode != grOk) { printf("Graphics error: %s ", grapherrormsg(errorcode)); exit(1); } area=imagesize(150,70,240,180); p=malloc(area); if(p==NULL) {closegraph();exit(1);} } //------------------------------------------------------------------------ // Check the board if any move is possible //------------------------------------------------------------------------ int check() // a know bug is there { int i,j,flag; flag=0; for(i=0;i<7;i++) { for(j=0;j<7;j++) if(board[j][i]!=-1) { if(board[j][i]==1) { if(board[j+1][i]==1) { if(board[j+2][i]==0) flag++; } if(board[j-1][i]==1) { if(board[j-2][i]==0) flag++; } if(board[j][i+1]==1) { if(board[j][i+2]==0) flag++; } if(board[j][i-1]==1) { if(board[j][i-2]==0) flag++; } } } } //count marble marble=0; for(i=0;i<7;i++) { for(j=0;j<7;j++) if(board[j][i]==1) marble++; } return flag; } //------------------------------------------------------------------------ // Give the current x,y position on board & find is it valid or not //------------------------------------------------------------------------ int GetXY(int X,int Y) { int i,j,x=200,y=100,flag=0; for(i=0;i<7;i++) { for(j=0;j<7;j++) { if(board[j][i]!=-1) { if(x==X && y==Y) flag=1; } x+=40; } x=200; y+=40; } return flag; } //------------------------------------------------------------------------ // check current position is filled or not //------------------------------------------------------------------------ int GetBoard(int X,int Y) { int i,j,x=200,y=100,f=-1; for(i=0;i<7;i++) { for(j=0;j<7;j++) { if(board[j][i]!=-1) { if(x==X && y==Y) f=board[j][i]; } x+=40; } x=200; y+=40; } return f; } //------------------------------------------------------------------------ // Sets the board to 1 or 0 ,represents filled & empty respectively //------------------------------------------------------------------------ void SetBoard(int X,int Y,int element) { int i,j,x=200,y=100; for(i=0;i<7;i++) { for(j=0;j<7;j++) { if(board[j][i]!=-1) { if(x==X && y==Y) board[j][i]=element; } x+=40; } x=200; y+=40; } } //------------------------------------------------------------------------ // Blinks the cursor or square //------------------------------------------------------------------------ void Blink(int x,int y,int c) { int i; setcolor(c); do { rectangle(x-10,y-10,x+10,y+10); rectangle(x-11,y-11,x+11,y+11); mydelay(0.5); rectangle(x-10,y-10,x+10,y+10); rectangle(x-11,y-11,x+11,y+11); mydelay(0.5); }while(!kbhit()); } //------------------------------------------------------------------------ // When ENTER pressed check for conditions & perform task //------------------------------------------------------------------------ int MakeMove(int X,int Y) { int flag,key; flag=NO; if(marble_color==11) Marble(X,Y,9); else Marble(X,Y,11); key = bioskey(0); if(key==0x4800)//up { if(GetBoard(X,Y-80)==0 && GetBoard(X,Y-40)==1) { Marble(X,Y,0); SetBoard(X,Y,0); Y-=40; Marble(X,Y,0); SetBoard(X,Y,0); Y-=40; SetBoard(X,Y,1); y=Y; flag=YES; } } if(key==0x5000)//down { if(GetBoard(X,Y+80)==0 && GetBoard(X,Y+40)==1) { Marble(X,Y,0); SetBoard(X,Y,0); Y+=40; Marble(X,Y,0); SetBoard(X,Y,0); Y+=40; SetBoard(X,Y,1); y=Y; flag=YES; } } if(key==0x4b00)//left { if(GetBoard(X-80,Y)==0 && GetBoard(X-40,Y)==1) { Marble(X,Y,0); SetBoard(X,Y,0); X-=40; Marble(X,Y,0); SetBoard(X,Y,0); X-=40; SetBoard(X,Y,1); x=X; flag=YES; } } if(key==0x4d00)//right { if(GetBoard(X+80,Y)==0 && GetBoard(X+40,Y)==1) { Marble(X,Y,0); SetBoard(X,Y,0); X+=40; Marble(X,Y,0); SetBoard(X,Y,0); X+=40; SetBoard(X,Y,1); x=X; flag=YES; } } if(kbhit()) getch(); setcolor(11); if(flag==YES) { Marble(X,Y,marble_color); } else//invalid key { Marble(X,Y,marble_color); sound(800); delay(100); nosound(); } return flag; } //------------------------------------------------------------------------ // Handles All the funtions & Perform desired move //------------------------------------------------------------------------ void Init() { int i,j,e=1; char ch; setwritemode(XOR_PUT); setcolor(15); while(e) { setfillstyle(1,11); Lcd(360,425,marble); Blink(x,y,11); ch=getch(); Lcd(360,425,marble); if(ch==ESC) e=0; if(GetXY(x,y)==1) { switch(ch) { case UP :if(GetXY(x,y-40)==1) if(y>100) y-=40;break; case DOWN :if(GetXY(x,y+40)==1) if(y<340) y+=40;break; case LEFT :if(GetXY(x-40,y)==1) if(x>200) x-=40;break; case RIGHT :if(GetXY(x+40,y)==1) if(x<440) x+=40;break; case ENTER :if(GetBoard(x,y)==1) { MakeMove(x,y); } break; case ESC :e=0;break; case '+': marble_color++; if(marble_color>15) marble_color=2; DrawBoard(); break; case '-':marble_color--; if(marble_color<2) marble_color=15; DrawBoard(); break; case 's':case 'S':save_game();break; case 'l':case 'L':load_game();break; }//switch }//if if(check()==0) e=finish(); }//while setwritemode(COPY_PUT); } //------------------------------------------------------------------------ // Display Final Screen //------------------------------------------------------------------------ int finish() { int i,j,f; char opt=0; setwritemode(COPY_PUT); f=0; for(i=0;i<7;i++) { for(j=0;j<7;j++) if(board[j][i]==1) f++; } Lcd(360,425,marble); // f-=1; win("Done !",220,155,425,240,1); setcolor(0); settextstyle(1,0,1); switch(f) { case 1:outtextxy(230,180,"You Are Intelligent !");break; case 2:outtextxy(255,180," Wonderful !");break; case 3:outtextxy(255,180," Good Job !");break; case 4:outtextxy(255,180," Can be better !");break; case 5:outtextxy(230,180," You Need Practice !");break; case 6:outtextxy(230,180," Very Poor !");break; case 7:outtextxy(230,180," Very Very Poor !");break; default:outtextxy(255,180," Try Again !");break; } // gotoxy(1,1);printf("%d",f); getch(); win("Exit ?",220,155,425,240,1); settextstyle(1,0,1); setcolor(1); outtextxy(240,180,"Play Again [y/n] :"); opt=getch(); setfillstyle(1,3); bar(17,402,624,464); if(opt=='y' || opt=='Y') { for(i=0;i<7;i++) { for(j=0;j<7;j++) if(board[j][i]!=-1) board[j][i]=1; } Marble(320,220,0); board[3][3]=0; marble=32; Background(); DrawBoard(); f=1; } else f=0; setwritemode(XOR_PUT); return f; } void win(char *text,int sx,int sy,int ex,int ey,int ck) { setfillstyle(1,7); bar(sx,sy,ex,ey); setfillstyle(1,7); setcolor(15); line(sx,sy,sx,ey); line(sx,sy,ex,sy); line(sx,sy,sx,ey); line(sx,sy,ex,sy); setcolor(0); line(ex,sy,ex,ey); line(ex,sy,ex,ey); line(sx,ey,ex,ey); line(sx,ey,ex,ey); if(ck==1) { settextstyle(0,0,0); setfillstyle(1,1); bar(sx+2,sy+2,ex-2,sy+17); setcolor(15); outtextxy(sx+4,sy+4,text); //for x setfillstyle(1,7); bar(ex-15,sy+4,ex-4,sy+15); setcolor(15); line(ex-15,sy+4,ex-4,sy+4); line(ex-15,sy+4,ex-15,sy+15); setcolor(0); line(ex-15,sy+15,ex-4,sy+15); line(ex-4,sy+4,ex-4,sy+15); setcolor(1); outtextxy(ex-13,sy+5,"x"); setfillstyle(1,7); } } void winp(int sx,int sy,int ex,int ey,int state) { if(state==1) { setcolor(0); line(sx,sy,sx,ey); line(sx,sy,ex,sy); line(sx,sy,sx,ey); line(sx,sy,ex,sy); setcolor(15); line(ex,sy,ex,ey); line(ex,sy,ex,ey); line(sx,ey,ex,ey); line(sx,ey,ex,ey); } else { setcolor(15); line(sx,sy,sx,ey); line(sx,sy,ex,sy); line(sx,sy,sx,ey); line(sx,sy,ex,sy); setcolor(0); line(ex,sy,ex,ey); line(ex,sy,ex,ey); line(sx,ey,ex,ey); line(sx,ey,ex,ey); } } void mybar(int sx,int sy,int ex,int ey) { int i; // setcolor(14); for(i=sy;i<=ey;i++) line(sx,i,ex,i); } void Menu() { setcolor(0); settextstyle(2,0,4); getimage(161,80,240,180,p); win(" ",161,80,240,180,0); outtextxy(170,88,"New Game"); outtextxy(170,105,"Exit"); setwritemode(XOR_PUT); mybar(170,88,220,100); getch(); mybar(170,88,220,100); mybar(170,105,220,117); getch(); mybar(170,105,220,117); setwritemode(COPY_PUT); getch(); putimage(161,80,p,COPY_PUT); } void Lcd(int x,int y,int n) { int a,b; if(n<10) { LCD(x,y,0); LCD(x+15,y,n); } else if(n<100) { a=n/10;b=n%10; LCD(x,y,a); LCD(x+15,y,b); } } void LCD(int left,int top,int NUM) { int i; // int right=100, bottom=100; setcolor(10); switch(NUM) { case 1: line(left+11,top+2,left+11,top+9); // | line(left+11,top+11,left+11,top+18); // | break; case 2: line(left,top,left+10,top); //-- line(left+11,top+2,left+11,top+9); // | line(left+1,top+10,left+9,top+10); //-- line(left-1,top+11,left-1,top+18); //| line(left,top+20,left+10,top+20); //-- break; case 3: line(left,top,left+10,top); //-- line(left+11,top+2,left+11,top+9); // | line(left+1,top+10,left+9,top+10); //-- line(left+11,top+11,left+11,top+18); // | line(left,top+20,left+10,top+20); //-- break; case 4: line(left-1,top+2,left-1,top+9); //| line(left+11,top+2,left+11,top+9); // | line(left+1,top+10,left+9,top+10); //-- line(left+11,top+11,left+11,top+18); // | break; case 5: line(left,top,left+10,top); //-- line(left-1,top+2,left-1,top+9); //| line(left+1,top+10,left+9,top+10); //-- line(left+11,top+11,left+11,top+18); // | line(left,top+20,left+10,top+20); //-- break; case 6: line(left,top,left+10,top); //-- line(left-1,top+2,left-1,top+9); //| line(left+1,top+10,left+9,top+10); //-- line(left-1,top+11,left-1,top+18); //| line(left+11,top+11,left+11,top+18); // | line(left,top+20,left+10,top+20); //-- break; case 7: line(left,top,left+10,top); //-- line(left-1,top+2,left-1,top+9); //| line(left+11,top+2,left+11,top+9); // | line(left+11,top+11,left+11,top+18); // | break; case 8: line(left,top,left+10,top); //-- line(left-1,top+2,left-1,top+9); //| line(left+11,top+2,left+11,top+9); // | line(left+1,top+10,left+9,top+10); //-- line(left-1,top+11,left-1,top+18); //| line(left+11,top+11,left+11,top+18); // | line(left,top+20,left+10,top+20); //-- break; case 9: line(left,top,left+10,top); //-- line(left-1,top+2,left-1,top+9); //| line(left+11,top+2,left+11,top+9); // | line(left+1,top+10,left+9,top+10); //-- line(left+11,top+11,left+11,top+18); // | line(left,top+20,left+10,top+20); //-- break; case 0: line(left,top,left+10,top); //-- line(left-1,top+2,left-1,top+9); //| line(left+11,top+2,left+11,top+9); // | line(left-1,top+11,left-1,top+18); //| line(left+11,top+11,left+11,top+18); // | line(left,top+20,left+10,top+20); //-- break; } } int load_game() { FILE *fp ; char *name; gotoxy(20,2);printf("File name: "); scanf("%s",name); if ( ( fp = fopen ( name, "rb" ) ) == NULL ) { setfillstyle(1,3); bar(20,17,400,40); gotoxy(20,2); printf(" Unable to Load Game"); getch(); setfillstyle(1,3); bar(20,17,400,40); return 0; } fread(board,sizeof(board),1,fp); fclose ( fp ) ; setfillstyle(1,3); bar(20,17,400,40); DrawBoard(); return 1; } int save_game() { char *fname; FILE *fp ; gotoxy(20,2);printf("File name: "); scanf("%s",fname); if ( ( fp = fopen ( fname, "wb" ) ) == NULL ) return 0; fwrite(board, sizeof ( board ), 1, fp); fclose(fp) ; setfillstyle(1,3); bar(20,17,400,40); return 1; }
fclose() Function in C++
Close file. Closes the file associated with the stream and disassociates it. Closes the given file stream. Any unwritten buffered data are flushed to the OS. Any unread buffered data are discarded. Whether or not the operation succeeds, the stream is no longer associated with a file, and the buffer allocated by std::setbuf or std::setvbuf, if any, is also disassociated and deallocated if automatic allocation was used. All internal buffers associated with the stream are disassociated from it and flushed: the content of any unwritten output buffer is written and the content of any unread input buffer is discarded. Even if the call fails, the stream passed as parameter will no longer be associated with the file nor its buffers.
Syntax for fclose() Function in C++
#include <cstdio> int fclose ( FILE * stream );
stream
Pointer to a FILE object that specifies the stream to be closed. If the stream is successfully closed, a zero value is returned. On failure, EOF is returned.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
/* The fclose() function takes a single argument, a file stream which is to be closed. All the data that are buffered but not written are flushed to the OS and all unread buffered data are discarded. Even if the operation fails, the stream is no longer associated with the file. If the file pointer is used after fclose() is executed, the behaviour is undefined. */ /* Close file by fclose() function code example */ #include <iostream> #include <cstdio> using namespace std; int main() { FILE *fp; fp = fopen("file.txt","w"); char str[20] = "Hello World!"; if (fp == NULL) { cout << "Error opening file"; exit(1); } fprintf(fp,"%s",str); fclose(fp); cout << "File closed successfully"; return 0; }
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; }
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; }
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;
getimage() Function in C++
getimage() function copy a specific portion into memory. This specific image would be any bit image like rectangle, circle or anything else. getimage() copies an image from the screen to memory. Left, top, right, and bottom define the screen area to which the rectangle is copied. Bitmap points to the area in memory where the bit image is stored. The first two words of this area are used for the width and height of the rectangle; the remainder holds the image itself.
Syntax for getimage() Function in C++
#include <graphics.h> void getimage(int left, int top, int right, int bottom, void *bitmap);
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
bitmap
points to the area in memory where the bit image is stored getimage() function saves a bit image of specified region into memory, region can be any 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 29 30 31 32
/* getimage() function code example copies an image from the screen to memory. */ /* save a bit image of the specified region displayed on the screen into memory by getimage() function code example. */ #include<stdio.h> #include<conio.h> #include<graphics.h> void main() { int gd=DETECT, gm,size; char *buff; initgraph(&gd,&gm," "); outtextxy(100,80,"Original image:"); rectangle(100,200,200,275); size=http://www.web.com/imagesize(100,200,200,275); buf=malloc(size); getimage(100,200,200,275,buf); outtextxy(100,320,"Captured image:"); putimage(100,340,buf,COPY_PUT); getch(); closegraph(); }
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; }
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; }
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; }
exit() Function in C++
The exit function terminates the program normally. Automatic objects are not destroyed, but static objects are. Then, all functions registered with atexit are called in the opposite order of registration. The code is returned to the operating system. An exit code of 0 or EXIT_SUCCESS means successful completion. If code is EXIT_FAILURE, an indication of program failure is returned to the operating system. Other values of code are implementation-defined.
Syntax for exit() Function in C++
void exit (int status);
status
Status code. If this is 0 or EXIT_SUCCESS, it indicates success. If it is EXIT_FAILURE, it indicates failure. Calls all functions registered with the atexit() function, and destroys C++ objects with static storage duration, all in last-in-first-out (LIFO) order. C++ objects with static storage duration are destroyed in the reverse order of the completion of their constructor. (Automatic objects are not destroyed as a result of calling exit().) Functions registered with atexit() are called in the reverse order of their registration. A function registered with atexit(), before an object obj1 of static storage duration is initialized, will not be called until obj1's destruction has completed. A function registered with atexit(), after an object obj2 of static storage duration is initialized, will be called before obj2's destruction starts. Normal program termination performs the following (in the same order): • Objects associated with the current thread with thread storage duration are destroyed (C++11 only). • Objects with static storage duration are destroyed (C++) and functions registered with atexit are called. • All C streams (open with functions in <cstdio>) are closed (and flushed, if buffered), and all files created with tmpfile are removed. • Control is returned to the host environment. Note that objects with automatic storage are not destroyed by calling exit (C++). If status is zero or EXIT_SUCCESS, a successful termination status is returned to the host environment. If status is EXIT_FAILURE, an unsuccessful termination status is returned to the host environment. Otherwise, the status returned depends on the system and library implementation. Flushes all buffers, and closes all open files. All files opened with tmpfile() are deleted. Returns control to the host environment from the program. exit() returns no values.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* terminate the process normally, performing the regular cleanup for terminating programs by exit() function code example */ #include<iostream> using namespace std; int main() { int i; cout<<"Enter a non-zero value: "; //user input cin>>i; if(i) // checks whether the user input is non-zero or not { cout<<"Valid input.\n"; } else { cout<<"ERROR!"; //the program exists if the value is 0 exit(0); } cout<<"The input was : "<<i; }
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; }
closegraph() Function in C++
The header file graphics.h contains closegraph() function which closes the graphics mode, deallocates all memory allocated by graphics system and restores the screen to the mode it was in before you called initgraph. closegraph() function is used to re-enter in the text mode and exit from the graphics mode. If you want to use both text mode and graphics mode in the program then you have to use both initgraph() and closegraph() function in the program. This function deallocates all memory allocated by graphics system and restores the screen to that mode in which it was presented before you called the initgraph() function.
Syntax for closegraph() Function in C++
#include <graphics.h> void closegraph();
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
/* closes the graphics mode, deallocates all memory allocated by graphics system and restores the screen to the mode it was in before you called initgraph by closegraph function code example. */ #include <graphics.h> int main() { int gdrive, gmode; char *drvpath = "c:\\bc\\bgi"; detectgraph(&gdrive, &gmode); initgraph(&gdrive, &gmode, drvpath); setbkcolor(0); setcolor(2); cleardevice(); MyOwnFan(320, 230, 0); getch(); closegraph(); return 0; }
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; }
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; }
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 }
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; }
imagesize() Function in C++
The header file graphics.h contains imagesize() function which returns the number of bytes required to store a bit-image. This function is used when we are using getimage. imagesize() function returns the required memory area to store an image in bytes. imagesize() function returns the number of bytes needed to store the top-left corner of the screen at left, top and the bottom-right corner at right, bottom. This function is usually used in conjunction with the getimage() function. The imagesize() function only works in graphics mode.
Syntax for imagesize() Function in C++
unsigned int imagesize(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 left, top, right, and bottom define the area of the screen in which image is stored.
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
/* imagesize() function returns the number of bytes required to store a bitimage. */ /* get the number of bytes required to store a bit-image by imagesize() function code example. */ #include <graphics.h> #include <stdio.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, color, bytes; char arr[100]; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, ""); // Draws a circle with center at // (200, 200) and radius as 50. circle(200, 200, 50); // draws a line with 2 points line(150, 200, 250, 200); // draws a line with 2 points line(200, 150, 200, 250); // imagesize function bytes = imagesize(150, 150, 250, 250); // sprintf stands for "String print". // Instead of printing on console, // it store output on char buffer // which are specified in sprintf sprintf(arr, "Number of bytes required " "to store required area = %d", bytes); // outtext function displays text // at current position. outtextxy(20, 280, arr); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); 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; }
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; }
Standard Library malloc() Function in C++
Allocate memory block. Allocates a block of size bytes of memory, returning a pointer to the beginning of the block. The content of the newly allocated block of memory is not initialized, remaining with indeterminate values. If size is zero, the return value depends on the particular library implementation (it may or may not be a null pointer), but the returned pointer shall not be dereferenced. Malloc function in C++ is used to allocate a specified size of the block of memory dynamically uninitialized. It allocates the memory to the variable on the heap and returns the void pointer pointing to the beginning address of the memory block. The values in the memory block allocated remain uninitialized and indeterminate. In case the size specified in the function is zero then pointer returned must not be dereferenced as it can be a null pointer, and in this case, behavior depends on particular library implementation. When a memory block is allocated dynamically memory is allocated on the heap but the pointer is allocated to the stack.
Syntax for malloc() Function in C++
#include <cstdlib> void* malloc (size_t size);
size
Size of the memory block, in bytes. size_t is an unsigned integral type. On success, a pointer to the memory block allocated by the function. The type of this pointer is always void*, which can be cast to the desired type of data pointer in order to be dereferenceable. If the function failed to allocate the requested block of memory, a null pointer is returned.
Advantages of malloc() in C++
There are a lot of advantages to using the malloc method in one's application: • Dynamic Memory allocation: Usually we create arrays at compile time in C++, the size of such arrays is fixed. In the case at run time we do not use all the space or extra space is required for more elements to be inserted in the array, then this leads to improper memory management or segmentation fault error. • Heap memory: Local arrays that are defined at compile time are allocated on the stack, which has lagged in memory management in case the number of data increases. Thus one needs to allocate memory out of the stack, thus malloc comes into the picture as it allocates the memory location on the heap and returns a pointer on the stack pointing to the starting address of the array type memory being allocated. • Variable-length array: This function helps to allocate memory for an array whose size can be defined at the runtime. Thus one can create the number of blocks as much as required at run time. • Better lifetime: Variable created using malloc method is proved to have a better life than the local arrays as a lifetime of local arrays depends on the scope they are being defined and cannot access out of their scope. But variables or arrays created using malloc exist till they are freed. This is of great importance for various data structures such as linked list, binary heap, etc.
Differences between the malloc() and new
• The new operator constructs an object, i.e., it calls the constructor to initialize an object while malloc() function does not call the constructor. The new operator invokes the constructor, and the delete operator invokes the destructor to destroy the object. This is the biggest difference between the malloc() and new. • The new is an operator, while malloc() is a predefined function in the stdlib header file. • The operator new can be overloaded while the malloc() function cannot be overloaded. • If the sufficient memory is not available in a heap, then the new operator will throw an exception while the malloc() function returns a NULL pointer. • In the new operator, we need to specify the number of objects to be allocated while in malloc() function, we need to specify the number of bytes to be allocated. • In the case of a new operator, we have to use the delete operator to deallocate the memory. But in the case of malloc() function, we have to use the free() function to deallocate the memory.
Data races
Only the storage referenced by the returned pointer is modified. No other storage locations are accessed by the call. If the function reuses the same unit of storage released by a deallocation function (such as free or realloc), the functions are synchronized in such a way that the deallocation happens entirely before the next allocation.
Exceptions
No-throw guarantee: this function never throws exceptions.
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
/* allocate the requested size of bytes and it returns a pointer to the first byte of allocated memory by malloc() function code example. */ #include <iostream> #include <cstdlib> using namespace std; int main() { // allocate 5 int memory blocks int* ptr = (int*) malloc(5 * sizeof(int)); // check if memory has been allocated successfully if (!ptr) { cout << "Memory Allocation Failed"; exit(1); } cout << "Initializing values..." << endl << endl; for (int i = 0; i < 5; i++) { ptr[i] = i * 2 + 1; } cout << "Initialized values" << endl; // print the values in allocated memories for (int i = 0; i < 5; i++) { // ptr[i] and *(ptr+i) can be used interchangeably cout << *(ptr + i) << endl; } // deallocate memory free(ptr); return 0; }
Math round() Function in C++
Round to nearest. Returns the integral value that is nearest to x, with halfway cases rounded away from zero. Rounds a floating-point number to an integer value. The round() functions round a floating-point number to the nearest integer value, regardless of the current rounding direction setting in the floating-point environment. If the argument is exactly halfway between two integers, round() rounds it away from 0. The return value is the rounded integer value.
Syntax for round() Function in C++
#include <cmath> double round (double x); float round (float x); long double round (long double x); double round (T x); // additional overloads for integral types
x
Value to round Function returns the value of x rounded to the nearest integral (as a floating-point value). Additional overloads are provided in this header (<cmath>) for the integral types: These overloads effectively cast x to a double before calculations (defined for T being any integral type).
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
/* round() is used to round off the given digit which can be in float or double. It returns the nearest integral value to provided parameter in round function, with halfway cases rounded away from zero. Instead of round(), std::round() can also be used. */ /* Round to nearest by round() function code example */ #include <cmath> #include <iostream> using namespace std; // Driver program int main() { // initializing value double x = 12.5, y = 13.3, z = 14.8; // Displaying the nearest values // of x, y and z cout << "Nearest value of x :" << round(x) << "\n"; cout << "Nearest value of y :" << round(y) << "\n"; cout << "Nearest value of z :" << round(z) << "\n"; // For lround cout << "lround(-0.0) = " << lround(-0.0) << "\n"; cout << "lround(2.3) = " << lround(2.3) << "\n"; cout << "lround(2.5) = " << lround(2.5) << "\n"; 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; }
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; }
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; }
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(); }
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; }
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; }
putimage() Function in C++
putimage puts the bit image previously saved with getimage back onto the screen, with the upper left corner of the image placed at (left,top). bitmap points to the area in memory where the source image is stored. The op parameter to putimage specifies a combination operator that controls how the color for each destination pixel onscreen is computed, based on the pixel already onscreen and the corresponding source pixel in memory.
Syntax for putimage() Function in C++
#include <graphics.h> void putimage(int left, int top, void *bitmap, int op);
left
X coordinate of top left corner of the specified rectangular area
top
Y coordinate of top left corner of the specified rectangular area
bitmap
pointer to the bitmap image in memory
op
operator for putimage. The enumeration putimage_ops, as defined in graphics.h, gives names to these operators. • COPY_PUT 0 Copy • XOR_PUT 1 Exclusive or • OR_PUT 2 Inclusive or • AND_PUT 3 And • NOT_PUT 4 Copy the inverse of the source In other words, COPY_PUT copies the source bitmap image onto the screen, XOR_PUT XORs the source image with the image already onscreen, OR_PUT ORs the source image with that onscreen, and so on. 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 56 57
/* In C++, the putimage() function is used to put the bit image that is saved with getimage() function back to screen. */ /* put the bit image to screen by putimage() function code example */ #include<graphics.h> #include<conio.h> #include<stdlib.h> main() { int gd = DETECT, gm, area, temp1, temp2, left = 25, top = 75; void *p; initgraph(&gd,&gm,"C:\\TC\\BGI"); setcolor(YELLOW); circle(50,100,25); setfillstyle(SOLID_FILL,YELLOW); floodfill(50,100,YELLOW); setcolor(BLACK); setfillstyle(SOLID_FILL,BLACK); fillellipse(44,85,2,6); fillellipse(56,85,2,6); ellipse(50,100,205,335,20,9); ellipse(50,100,205,335,20,10); ellipse(50,100,205,335,20,11); area = imagesize(left, top, left + 50, top + 50); p = malloc(area); setcolor(WHITE); settextstyle(SANS_SERIF_FONT,HORIZ_DIR,2); outtextxy(155,451,"Smiling Face Animation"); setcolor(BLUE); rectangle(0,0,639,449); while(!kbhit()) { temp1 = 1 + random ( 588 ); temp2 = 1 + random ( 380 ); getimage(left, top, left + 50, top + 50, p); putimage(left, top, p, XOR_PUT); putimage(temp1 , temp2, p, XOR_PUT); delay(100); left = temp1; top = temp2; } getch(); closegraph(); 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; }
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; }
Assignment Operators in C++
As the name already suggests, these operators help in assigning values to variables. These operators help us in allocating a particular value to the operands. The main simple assignment operator is '='. We have to be sure that both the left and right sides of the operator must have the same data type. We have different levels of operators. Assignment operators are used to assign the value, variable and function to another variable. Assignment operators in C are some of the C Programming Operator, which are useful to assign the values to the declared variables. Let's discuss the various types of the assignment operators such as =, +=, -=, /=, *= and %=. The following table lists the assignment operators supported by the C language:
=
Simple assignment operator. Assigns values from right side operands to left side operand
+=
Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand.
-=
Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand.
*=
Multiply AND assignment operator. It multiplies the right operand with the left operand and assigns the result to the left operand.
/=
Divide AND assignment operator. It divides the left operand with the right operand and assigns the result to the left operand.
%=
Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand.
<<=
Left shift AND assignment operator.
>>=
Right shift AND assignment operator.
&=
Bitwise AND assignment operator.
^=
Bitwise exclusive OR and assignment operator.
|=
Bitwise inclusive OR and assignment operator.
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
/* Assignment operators are used to assigning value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error. */ // C++ program to demonstrate working of Assignment operators #include <iostream> using namespace std; int main() { // Assigning value 10 to a // using "=" operator int a = 10; cout << "Value of a is "<<a<<"\n"; // Assigning value by adding 10 to a // using "+=" operator a += 10; cout << "Value of a is "<<a<<"\n"; // Assigning value by subtracting 10 from a // using "-=" operator a -= 10; cout << "Value of a is "<<a<<"\n"; // Assigning value by multiplying 10 to a // using "*=" operator a *= 10; cout << "Value of a is "<<a<<"\n"; // Assigning value by dividing 10 from a // using "/=" operator a /= 10; cout << "Value of a is "<<a<<"\n"; 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; }
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; }
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(); }
line() Function in C++
The header file graphics.h contains line() function which is used to draw a line from a point(x1, y1) to point(x2, y2) i.e. (x1, y1) and (x2, y2) are end points of the line. The function line() draws a line on the graphics screen between two specified points. So this function requires four parameters namely x1, y1, x2, and y2 to represent two points. This function draws a line from (x1, y1) coordinates to (x2, y2) coordinates on the graphics screen.
Syntax for line() Function in C++
void line(int x1, int y1, int x2, int y2);
x1
X coordinate of first point
y1
Y coordinate of first point.
x2
X coordinate of second point.
y2
Y coordinate of second point. You can change "linestyle", "pattern", "thickness" of the line by setlinestyle() function.
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
/* draw a line in C++ graphic code example */ #include<iostream.h> #include<conio.h> #include<graphics.h> void main() { int gd=DETECT,gm,x,y; clrscr(); initgraph(&gd,&gm,"c:\\TC\\bgi"); //INITIALISING GRAPHICS MODE setlinestyle(0,0,3); outtextxy(300,150,"LINE()"); line(350,60,200,200); outtextxy(300,300," CURRENT POSITION"); linerel(320,350); outtextxy(335,315,"LINEREL()"); outtextxy(30,30," CURRENT POSITION"); lineto(30,200); outtextxy(70,45,"LINETO()"); getch(); closegraph(); }
setfillpattern() Function in C++
This function is used to create a user-defined fill pattern. setfillpattern() is like setfillstyle, except that you use it to set a user-defined 8x8 pattern rather than a predefined pattern. upattern is a pointer to a sequence of 8 bytes, with each byte corresponding to 8 pixels in the pattern. Whenever a bit in a pattern byte is set to 1, the corresponding pixel is plotted.
Syntax for setfillpattern() Function in C++
#include <graphics.h> void setfillpattern(char *upattern, int color);
upattern
specifier 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
color
specifier 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 This function does not return any value. The winbgim version allows the color argument to be an ordinary BGI color (from 0 to 15) or an RGB color.
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
/* The setfillpattern() function sets the fill pattern to the pattern pointed to by the pattern parameter. The array must be at least 8 bytes long. The pattern is organized by beat. When the bit is set, the color specified by the color parameter is output, otherwise the background color is used. */ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; int maxx, maxy; /* a user-defined fill pattern */ char pattern[8] = {0x00, 0x70, 0x20, 0x27, 0x24, 0x24, 0x07, 0x00}; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } maxx = getmaxx(); maxy = getmaxy(); setcolor(getmaxcolor()); /* select a user-defined fill pattern */ setfillpattern(pattern, getmaxcolor()); /* fill the screen with the pattern */ bar(0, 0, maxx, maxy); /* clean up */ getch(); closegraph(); return 0; }
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() }
#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; }
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; }


In C++, a namespace ("the name scope") is an abstract container or environment created to hold a logical grouping of "unique identifiers" or symbols (i.e., names). An identifier defined