Happy Codings - Programming Code Examples

C Programming Code Examples

C > Games and Graphics Code Examples

Bricks game in C

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 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 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
/* Bricks game in C */ #include <iostream.h> #include <conio.h> #include <ctype.h> # include <process.h> # include <dos.h> # include <stdlib.h> # include <graphics.h> # include <stdio.h> # define NULL 0 # define YES 1 # define NO 0 #define ESC 0x1b /* Define the escape key */ int MaxX, MaxY, MidX, MidY ; int bri[5][20] ; int GraphDriver; /* The Graphics device driver */ int GraphMode; /* The Graphics mode value */ double AspectRatio; /* Aspect ratio of a pixel on the screen*/ int MaxXX, MaxYY; /* The maximum resolution of the screen */ int MaxColors; /* The maximum # of colors available */ int ErrorCode; /* Reports any graphics errors */ struct palettetype palette; /* Used to read palette info*/ // Initialize the graphics mode void Initialize(void); // Display the last screen of bricks void SayGoodbye(void); // Establish the main window for the demo void MainWindow(char *header); // Display the message Press any key to continue at last screen void StatusLine(char *msg); // Draws a boarder line at last screen void DrawBorder(void); // Changes the text style void changetextstyle(int font, int direction, int charsize); // Welcome screen of bricks game mainscreen(); // Instruction messages of bricks game screen(); // To display the bricks (in square box) and paddles in rectangle form and bulbs rounded form bricks(); // Delete a bricks when bulb hit it delbrick(int,int); // Echoes different musics bell(int); int graphmode = CGAHI, graphdriver = CGA, level; main () { union REGS ii, oo ; int BallX, BallY, Base1, Base2, dx = 1, dy = -1, OldX, OldY ; int totallayer[5] = { 10, 20, 30, 40, 50 }, max = 50, layer = 4 ; int i, flag = 0, speed = 25, score = 0, chance = 4, areareq ; char *m1, *m2 ; /* Function to initialise the graphics mode */ initgraph ( &graphdriver, &graphmode, "c:\tc\bgi " ) ; mainscreen(); initgraph ( &graphdriver, &graphmode, "c:\tc\bgi " ) ; /* get the maximum value of x and y coordinates of the screen */ MaxX = getmaxx() ; MaxY = getmaxy() ; /* finding the center of the screen */ MidX = MaxX / 2 ; MidY = MaxY / 2 ; /* create opening screen and accept the level of the player's */ level = screen() ; /* assign the speed to ball as per the level chosen */ switch ( level ) { case 'M' : case 'm' : speed = 15 ; break ; case 'F' : case 'f' : speed = 10 ; } /* draw the four layer of bricks, the paddle and the ball */ rectangle ( 0, 0, MaxX, MaxY - 12 ) ; bricks() ; rectangle ( MidX - 25, MaxY - 7 - 12, MidX + 25, MaxY - 12 ) ; floodfill ( MidX, MaxY - 1 - 12, 12 ) ; circle ( MidX, MaxY - 13 - 12, 12 ) ; floodfill ( MidX, MaxY - 10 - 12, 12 ) ; /* memory allocation for storing the image of the paddle */ areareq = imagesize ( MidX - 12, MaxY - 18, MidX + 12, MaxY - 8 ) ; m1 =((char*) malloc ( areareq )) ; /* memory allocation for storing the image of the ball */ areareq = imagesize ( MidX - 25, MaxY - 7, MidX + 25, MaxY - 1 ) ; m2 =((char *) malloc ( areareq ) ); /* if unable to alloacte the memory */ if ( m1 == NULL || m2 == NULL ) { puts ( "Not Enough memory!!" ) ; exit ( 1 ) ; } /* image of the paddle and the ball is stored into allocated memory */ getimage ( MidX - 12, MaxY - 7 - 12 - 12 + 1, MidX + 12, MaxY - 8 - 12, m1 ) ; getimage ( MidX - 25, MaxY - 7 - 12, MidX + 25, MaxY - 1 - 12, m2 ) ; /* store current position of the paddle and ball */ Base1 = MidX - 25 ; Base2 = MaxY - 7 - 12 ; BallX = MidX - 12 ; BallY = MaxY - 7 - 12 + 1 - 12 ; /* display balls remaining ( initially 3 ) */ gotoxy ( 45, 25 ) ; cout<< "Balls :" ; for ( i = 0 ; i < 3 ; i++ ) { circle ( 515 + i * 35, MaxY - 5, 12 ) ; floodfill ( 515 + i * 35, MaxY - 5, 12 ) ; } /* display starting score */ gotoxy ( 1, 25 ) ; cout<< "Score: "; gotoxy(16,25); cout<<score; /* select font and alignment for displaying text */ settextjustify ( CENTER_TEXT, CENTER_TEXT ) ; changetextstyle ( GOTHIC_FONT, HORIZ_DIR, 4 ) ; while ( 1 ) { flag = 0 ; /* saving current x and y coordinates of the ball */ OldX = BallX ; OldY = BallY ; /* update ballx and bally to move the ball in correct direction */ BallX = BallX + dx ; BallY = BallY + dy ; /* according to the position of ball the layer of bricks is determined */ if ( BallY > 40 ) { max = 50 ; layer = 4 ; } else { if ( BallY > 30 ) { max = 40 ; layer = 3 ; } else { if ( BallY > 20 ) { max = 30 ; layer = 2 ; } else { if ( BallY > 10 ) { max = 20 ; layer = 1 ; } else { max = 10 ; layer = 0 ; } } } } /* if the ball hits the right boundary, move it to the left */ if ( BallX > ( MaxX - 24 - 1 ) ) { bell ( 5 ) ; BallX = MaxX - 24 - 1 ; dx = -dx ; } /* if the ball hits the left boundary, move it to the right */ if ( BallX < 1 ) { bell ( 5 ) ; BallX = 1 ; dx = -dx ; } /* if the ball hits the top boundary, move it down */ if ( BallY < 1 ) { bell ( 5 ) ; BallY = 1 ; dy = -dy ; } /* if the ball is in the area of the bricks */ if ( BallY < max ) { /* if there is no brick at the top of the ball */ if ( bri[layer][ ( BallX + 10 ) / 32 ] == 1 ) { /* if the ball touches a brick */ for ( i = 1 ; i <= 6 ; i++ ) { /* check whether there is a brick to the right of the ball */ if ( bri[layer][ ( BallX + i + 10 ) / 32 ] == 0 ) { /* if there is a brick */ BallX = BallX + i ; flag = 1 ; break ; } /* check whether there is a brick to the left of the ball */ if ( bri[layer][ ( BallX - i + 10 ) / 32 ] == 0 ) { BallX = BallX - i ; flag = 1 ; break ; } } /* if the ball does not touch a brick at the top, left or right */ if ( !flag ) { /* check if the ball has moved above the current layer */ if ( BallY < totallayer[layer - 1] ) { /* if so, change current layer appropriately */ layer-- ; max = totallayer[layer] ; } /* restore the image of the ball at the old coordinates */ putimage ( OldX, OldY, m1, OR_PUT ) ; /* erase the image at the old coordinates */ putimage ( OldX, OldY, m1, XOR_PUT ) ; /* place the image of the ball at the new coordinates */ putimage ( BallX, BallY, m1, XOR_PUT ) ; /* delay for fewseconds*/ delay ( speed ) ; /* carry on moving the ball */ continue ; } } /* when ball touch the brick control comes to this point */ bell ( 5 ) ; /* play music */ /* erase the touched brick */ delbrick ( ( BallX + 10 ) / 32, layer ) ; /* if the brick hit is on the extreme right */ if ( ( BallX + 10 ) / 32 == 19 ) line ( MaxX, 0, MaxX, 50 ) ; /* redraw right boundary */ /* if the brick hit is on the extreme left */ if ( ( BallX + 10 ) / 32 == 0 ) line ( 0, 0, 0, 50 ) ; /* redraw left boundary */ /* if the brick hit is in the topmost layer */ if ( layer == 0 ) line ( 0, 0, MaxX, 0 ) ; /* redraw top boundary */ /* set appropriate array element to 1 to indicate absence of brick */ bri[layer][ ( BallX + 10 ) / 32 ] = 1 ; BallY = BallY + 1 ; /* update the y coordinate */ dy = -dy ; /* change the current direction of the ball */ score += 10 ; /* increment the score by 10 */ gotoxy ( 16, 25 ) ; cout<< score; /* display latest score */ /* if the first brick is hit during a throw*/ } /* if ball reached the bottom */ if ( BallY > 180 - 12 ) { /* if paddle missed the ball */ if ( BallX < Base1 - 20 || BallX > Base1 + 50 ) { /* continue the decrement of the ball */ while ( BallY < 177 ) { /* erase the image of the ball at the old coordinates */ putimage ( OldX, OldY, m1, XOR_PUT ) ; /* put the image of the ball at the new coordinates */ putimage ( BallX, BallY, m1, XOR_PUT ) ; /* introduce delay for fewseconds */ delay ( speed ) ; /* saveing current x and y coordinates of the ball */ OldX = BallX ; OldY = BallY ; /* update ballx and bally to move the ball in correct direction */ BallX = BallX + dx ; BallY = BallY + dy ; } chance-- ; /* decrement the total number of chances */ score -= 10 ; /* decrement 10 points for each ball lost */ gotoxy ( 16, 25 ) ; cout<< score; /* display latest score */ bell ( 1 ) ; /* erase one of the available balls */ if ( chance ) putimage ( 515 + ( chance - 1 ) * 35 - 12 , MaxY - 10, m1, XOR_PUT ) ; /* if the last ball is being played */ if ( chance == 1 ) { gotoxy ( 45, 25 ) ; cout<< "Last ball... careful!"; } /* if all the balls are lost */ if ( !chance ) { gotoxy ( 45, 25 ) ; cout<<"Press any key to continue ... " ; outtextxy ( MidX, MidY, "Better luck next time" ) ; bell ( 2 ) ; closegraph() ; restorecrtmode() ; closegraph(); /* Close the graphics mode */ Initialize(); /* Intialize the graphics mode */ setbkcolor(4); SayGoodbye(); /* Display the That's all Folks message */ closegraph(); /* Return the system to text mode */ exit ( 0 ) ; } } /* if ball is collected on paddle */ bell ( 4 ) ; BallY = 180 - 12 ; /* restore the y coordinate of ball */ dy = -dy ; /* move the ball upwards */ } /* put the image of the ball at the old coordinates */ putimage ( OldX, OldY, m1, OR_PUT ) ; /* erase the image of the ball at the old coordinates */ putimage ( OldX, OldY, m1, XOR_PUT ) ; /* put the image of the ball at the upadted coordinates */ putimage ( BallX, BallY, m1, XOR_PUT ) ; /* if all the bricks have been knockout */ if ( score == 500 - ( ( 4 - chance ) * 20 ) ) { outtextxy ( MidX, MidY, "Winner !!" ) ; if ( score < 600 ) outtextxy ( MidX, MidY + 30, "Try to score 600" ) ; else outtextxy ( MidX, MidY + 30, " GREAT!" ) ; bell ( 2 ) ; closegraph() ; restorecrtmode() ; exit ( 0 ) ; } /* introduce delay for few seconds */ delay ( speed ) ; /* if the key is pressed to move the paddle */ if ( kbhit() ) { /* interrupt issue to obtain the ascii and scan codes of key hit */ ii.h.ah = 0 ; int86 ( 22, &ii, &oo ) ; /* put the image of the paddle at the old coordinates */ putimage ( Base1, Base2, m2, OR_PUT ) ; /* erase the image of the paddle at the old coordinates */ putimage ( Base1, Base2, m2, XOR_PUT ) ; /* if Esc key has been pressed */ if ( oo.h.ah == 1 ) exit ( 0 ) ; /* right arrow key */ if ( oo.h.ah == 75 ) Base1 = Base1 - 25 ; /* left arrow key */ if ( oo.h.ah == 77 ) Base1= Base1 + 25 ; /* if paddle goes beyond left boundary */ if ( Base1 < 0 ) Base1 = 0 ; /* if paddle goes beyond right boundary */ if ( Base1 > 589 ) Base1 = 589 ; /* put the image of the paddle at the proper position */ putimage ( Base1, Base2, m2, XOR_PUT ) ; } } closegraph(); Initialize(); SayGoodbye(); /* Give user the closing screen */ closegraph(); /* Return the system to text mode */ return(0); } /* This function creates the opening screen and displyed instruction related to the game */ screen() { int i, j, lx = 0, ly = 0, ch ; rectangle(1,1,600,195); setbkcolor(4); /* set the textstyle for displaying instruction */ changetextstyle ( DEFAULT_FONT, HORIZ_DIR, 0 ) ; outtextxy ( 150, 55, " Instructions " ) ; changetextstyle (4, HORIZ_DIR, 5 ); outtextxy ( 130, 0, " B R I C K S" ) ; changetextstyle ( DEFAULT_FONT, HORIZ_DIR, 0 ) ; outtextxy ( 30, 68, "Use left and right arrow keys to move paddle." ) ; outtextxy ( 30, 88, "If you don't collect the ball on the paddle, you lose the ball." ) ; outtextxy ( 30, 108, "On loosing a ball you loose 20 points." ) ; outtextxy ( 30, 128, "On taking a brick you gain 5 points." ) ; changetextstyle(7, HORIZ_DIR, 3); outtextxy ( 100, 148, "Press any key to continue ..." ) ; bell ( 3 ) ; /* ring music */ fflush ( stdin ) ; if ( getch() == 0 ) getch() ; closegraph(); initgraph ( &graphdriver, &graphmode, "c:\tc\bgi " ) ; rectangle(2,2,620,195); setbkcolor(4); /* display the main menu */ while ( 1 ) { changetextstyle(4,HORIZ_DIR,5); outtextxy ( 60, 8, "Options Available:" ) ; outtextxy ( 150, 55, "Play ( P )" ) ; outtextxy ( 150, 125, "Exit ( E )" ) ; ch = 0 ; /* continue untill you select the correct choice */ while ( ! ( ch == 'E' || ch == 'P' ) ) { fflush ( stdin ) ; /* if a special key is hit, flush the keyboard buffer */ if ( ( ch = getch() ) == 0 ) getch() ; else ch = toupper ( ch ) ; /* store the uppercase of the choice made*/ } if ( ch == 'P' ) break ; if (ch == 'E') exit ( 0 ) ; } setviewport ( 1, 125 - 12, MaxX - 1, MaxY - 1, 1 ) ; clearviewport() ; closegraph(); initgraph ( &graphdriver, &graphmode, "c:\tc\bgi " ) ; rectangle(2,2,620,195); setbkcolor(4); /* display menu for the diffrent levels */ changetextstyle(7,HORIZ_DIR,3); outtextxy ( 60, 8, "Select the level for play:" ) ; outtextxy ( 150,50, "Slow ( S )" ) ; outtextxy ( 150, 100, "Medium ( M )" ) ; outtextxy ( 150, 150, "Fast ( F )" ) ; /* accept user's choice */ fflush ( stdin ) ; if ( ( ch = getch() ) == 0 ) getch() ; clearviewport() ; /* return the choice selected by the user */ return ( ch ) ; } /* This function draws bricks at the start of the game.There are four layers of the bricks */ bricks() { int i, j, lx = 0, ly = 0 ; for ( i = 0 ; i < 5 ; i++ ) /* 5 rows */ { for ( j = 0 ; j < 30 ; j++ ) /* 20 columns */ { /* draw a brick at appropriate coordinates */ rectangle ( lx, ly, lx + 20, ly + 7 ) ; floodfill ( lx + 1, ly + 1, 2 ) ; lx = lx + 32 ; } lx = 0 ; ly = ly + 10 ; } } /* This function erases the brick which is knock by the ball */ delbrick ( int b, int l ) { /* b - brick number, l - layer */ setcolor ( BLACK ) ; rectangle ( b * 32, l * 10, ( b * 32 ) + 20 , ( l * 10 ) + 7 ) ; rectangle ( b * 32 + 1, l * 10, ( b * 32 ) + 20 - 1, ( l * 10 ) + 7 - 1 ) ; rectangle ( b * 32 + 2, l * 10, ( b * 32 ) + 20 - 2, ( l * 10 ) + 7 - 2 ) ; rectangle ( b * 32 + 3, l * 10, ( b * 32 ) + 20 - 3, ( l * 10 ) + 7 - 3 ) ; rectangle ( b * 32 + 4, l * 10, ( b * 32 ) + 20 - 4, ( l * 10 ) + 7 - 4 ) ; rectangle ( b * 32 + 5, l * 10, ( b * 32 ) + 20 - 5, ( l * 10 ) + 7 - 5 ) ; rectangle ( b * 32 + 6, l * 10, ( b * 32 ) + 20 - 6, ( l * 10 ) + 7 - 6 ) ; setcolor ( CGA_YELLOW ) ; } /* plays different types of music */ bell ( int m_no ) { /* natural frequencies of 7 notes */ float wave[6] = { 120.81, 136.83, 144.81, 154.61, 216, 240 } ; int n, i ; switch ( m_no ) { case 1 : for ( i = 0 ; i < 6 ; i++ ) { sound ( wave[i] * 1 ) ; delay ( 30 ) ; } nosound() ; break ; case 2 : for ( i = 0 ; i < 15 ; i++ ) { n = random ( 6 ) ; sound ( wave[n] * 2 ) ; delay ( 100 ) ; } nosound() ; break ; case 3 : while ( !kbhit() ) { n = random ( 6 ) ; sound ( wave[n] * 2 ) ; delay ( 100 ) ; } nosound() ; /* flush the keyboard buffer */ if ( getch() == 0 ) getch() ; break ; case 4 : for ( i = 5 ; i >= 0 ; i-- ) { sound ( wave[i] * 4 ) ; delay ( 15 ) ; } nosound() ; break ; case 5 : sound ( wave[2] * 5 ) ; delay ( 50 ) ; nosound() ; } } /* */ /* INITIALIZE: Initializes the graphics system and reports */ /* any errors which occured. */ /* */ void Initialize(void) { int xasp, yasp; /* Used to read the aspect ratio*/ GraphDriver = DETECT; /* Request auto-detection */ initgraph( &GraphDriver, &GraphMode, "c:\tc\bgi" ); ErrorCode = graphresult(); /* Read result of initialization*/ if( ErrorCode != grOk ){ /* Error occured during init */ printf(" Graphics System Error: %s ", grapherrormsg( ErrorCode ) ); exit( 1 ); } getpalette( &palette ); /* Read the palette from board */ MaxColors = getmaxcolor() + 1; /* Read maximum number of colors*/ MaxXX = getmaxx(); MaxYY = getmaxy(); /* Read size of screen */ getaspectratio( &xasp, &yasp ); /* read the hardware aspect */ AspectRatio = (double)xasp / (double)yasp; /* Get correction factor */ } /* */ /* SAYGOODBYE: Give a closing screen to the user before leaving. */ /* */ void SayGoodbye(void) { struct viewporttype viewinfo; /* Structure to read viewport */ int h, w; MainWindow( "== Finale ==" ); getviewsettings( &viewinfo ); /* Read viewport settings */ changetextstyle( TRIPLEX_FONT, HORIZ_DIR, 4 ); settextjustify( CENTER_TEXT, CENTER_TEXT ); h = viewinfo.bottom - viewinfo.top; w = viewinfo.right - viewinfo.left; outtextxy( w/2, h/2, "That's all, folks!" ); StatusLine( "Press any key to EXIT" ); getch(); cleardevice(); /* Clear the graphics screen */ } /* */ /* MAINWINDOW: Establish the main window for the demo and set */ /* a viewport for the demo code. */ /* */ void MainWindow( char *header ) { int height; cleardevice(); /* Clear graphics screen */ setcolor( MaxColors - 1 ); /* Set current color to white */ setviewport( 0, 0, MaxXX, MaxYY, 1 ); /* Open port to full screen */ height = textheight( "H" ); /* Get basic text height */ changetextstyle( DEFAULT_FONT, HORIZ_DIR, 1 ); settextjustify( CENTER_TEXT, TOP_TEXT ); outtextxy( MaxXX/2, 2, header ); setviewport( 0, height+4, MaxXX, MaxYY-(height+4), 1 ); DrawBorder(); setviewport( 1, height+5, MaxXX-1, MaxYY-(height+5), 1 ); } /* */ /* STATUSLINE: Display a status line at the bottom of the screen. */ /* */ void StatusLine( char *msg ) { int height; setviewport( 0, 0, MaxXX, MaxYY, 1 ); /* Open port to full screen */ setcolor( MaxColors - 1 ); /* Set current color to white */ changetextstyle( DEFAULT_FONT, HORIZ_DIR, 1 ); settextjustify( CENTER_TEXT, TOP_TEXT ); setlinestyle( SOLID_LINE, 0, NORM_WIDTH ); setfillstyle( EMPTY_FILL, 0 ); height = textheight( "H" ); /* Detemine current height */ bar( 0, MaxYY-(height+4), MaxXX, MaxYY ); rectangle( 0, MaxYY-(height+4), MaxXX, MaxYY ); outtextxy( MaxXX/2, MaxYY-(height+2), msg ); setviewport( 1, height+5, MaxXX-1, MaxYY-(height+5), 1 ); } /* */ /* DRAWBORDER: Draw a solid single line around the current */ /* viewport. */ /* */ void DrawBorder(void) { struct viewporttype vp; setcolor( MaxColors - 1 ); /* Set current color to white */ setlinestyle( SOLID_LINE, 0, NORM_WIDTH ); getviewsettings( &vp ); rectangle( 0, 0, vp.right-vp.left, vp.bottom-vp.top ); } /* */ /* CHANGETEXTSTYLE: similar to settextstyle, but checks for */ /* errors that might occur whil loading the font file. */ /* */ void changetextstyle(int font, int direction, int charsize) { int ErrorCode; graphresult(); /* clear error code */ settextstyle(font, direction, charsize); ErrorCode = graphresult(); /* check result */ if( ErrorCode != grOk ){ /* if error occured */ closegraph(); printf(" Graphics System Error: %s ", grapherrormsg( ErrorCode ) ); exit( 1 ); } } /* The main function body of main screen which displays the main screen creating the opening screen display */ mainscreen() { int maxx, maxy, in, area; // get maximum x, y coordinates of the screen maxx = getmaxx(); maxy = getmaxy(); // setbkcolor sets the current background color using the palette setbkcolor(RED); // Draws a rectangle (graphics mode) rectangle(0, 0, maxx, maxy); // sets the line style and text justification in screen changetextstyle(1, HORIZ_DIR, 0); // displaying the output text on main screen outtextxy(220, 20, "WELCOME"); outtextxy(240,60," TO "); outtextxy(220,100," BRICKS"); changetextstyle(7, HORIZ_DIR, 3); bell(3); outtextxy(110, 150, "Press any key to continue..."); // Flushes the standard input device fflush(stdin); getch(); closegraph(); }
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 *textstring);
x
x-coordinate of the point
y
y-coordinate of the point
textstring
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 28 29 30 31 32 33 34
/* display the text or string at a specified point (x, y) on the screen by outtextxy() function example */ // C Implementation for outtextxy() #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, ""); // outtextxy function outtextxy(200, 150, "Hello, Have a good day !"); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); 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.
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 23 24 25 26 27 28 29 30 31 32 33 34 35 36
/* deallocate all memory allocated by the graphics system by closegraph() function example */ // C Implementation for closegraph() #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, ""); // outtext function displays // text at current position. outtext("Press any key to close" " the graphics mode !!"); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0; }
If Else If Ladder in C/C++
The if...else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities. The if...else ladder allows you to check between multiple test expressions and execute different 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 of if...else Ladder in C
if (Condition1) { Statement1; } else if(Condition2) { Statement2; } . . . else if(ConditionN) { StatementN; } else { Default_Statement; }
In the above syntax of if-else-if, if the Condition1 is TRUE then the Statement1 will be executed and control goes to next statement in the program following if-else-if ladder. If Condition1 is FALSE then Condition2 will be checked, if Condition2 is TRUE then Statement2 will be executed and control goes to next statement in the program following if-else-if ladder. Similarly, if Condition2 is FALSE then next condition will be checked and the process continues. If all the conditions in the if-else-if ladder are evaluated to FALSE, then Default_Statement will be executed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* write a C program which demonstrate use of if-else-if ladder statement */ #include<stdio.h> #include<conio.h> void main() { int a; printf("Enter a Number: "); scanf("%d",&a); if(a > 0) { printf("Given Number is Positive"); } else if(a == 0) { printf("Given Number is Zero"); } else if(a < 0) { printf("Given Number is Negative"); } getch(); }
setviewport() Function in C
setviewport() establishes a new viewport for graphics output. The viewport corners are given in absolute screen coordinates by (left,top) and (right,bottom). The current position (CP) is moved to (0,0) in the new window. The parameter clip determines whether drawings are clipped (truncated) at the current viewport boundaries. If clip is nonzero, all drawings will be clipped to the current viewport.
Syntax for setviewport() Function in C
#include <graphics.h> void setviewport(int left, int top, int right, int bottom, int clip);
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.
clip
The clip argument determines whether drawings are clipped (truncated) at the current viewport boundaries. If clip is non-zero, all drawings will be clipped to the current viewport. setviewport function is used to restrict drawing to a particular portion on the screen. For example, setviewport(80 , 80, 160, 160, 1); will restrict our drawing activity inside the rectangle(80, 80, 160, 160). left, top, right, bottom are the coordinates of main diagonal of rectangle in which we wish to restrict our drawing. Also note that the point (left, top) becomes the new origin.
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
/* establishes a new viewport for graphics output by setviewport() function code example */ #include <graphics.h> #include <conio.h> int main() { //initilizing graphic driver and //graphic mode variable int graphicdriver=DETECT,graphicmode; //calling initgraph with parameters initgraph(&graphicdriver,&graphicmode,"c:\\turboc3\\bgi"); //Printing message for user outtextxy(50, 50 + 50, "Program to try setviewport in C graphics"); //declaring variable; int middleofx, middleofy; //getting middle of x and y middleofx = getmaxx()/2; middleofy = getmaxy()/2; //setting viewport setviewport(middleofx - 50, middleofy - 50, middleofx + 50, middleofy + 50, 1); //creating circle circle(50, 50, 55); getch(); return 0; }
#define Directive in C
In the C Programming Language, the #define directive allows the definition of macros within your source code. These macro definitions allow constant values to be declared for use throughout your code. Macro definitions are not variables and cannot be changed by your program code like variables. You generally use this syntax when creating constants that represent numbers, strings or expressions.
Syntax for #define Directive in C
#define NAME value /* this syntax creates a constant using define*/ // Or #define NAME (expression) /* this syntax creates a constant using define*/
NAME
is the name of a particular constant. It can either be defined in smaller case or upper case or both. Most of the developers prefer the constant names to be in the upper case to find the differences.
value
defines the value of the constant.
Expression
is the value that is assigned to that constant which is defined. The expression should always be enclosed within the brackets if it has any operators. In the C programming language, the preprocessor directive acts an important role within which the #define directive is present that is used to define the constant or the micro substitution. The #define directive can use any of the basic data types present in the C standard. The #define preprocessor directive lets a programmer or a developer define the macros within the source code. This macro definition will allow the constant value that should be declared for the usage. Macro definitions cannot be changed within the program's code as one does with other variables, as macros are not variables. The #define is usually used in syntax that created a constant that is used to represent numbers, strings, or other expressions. The #define directive should not be enclosed with the semicolon(;). It is a common mistake done, and one should always treat this directive as any other header file. Enclosing it with a semicolon will generate an error. The #define creates a macro, which is in association with an identifier or is parameterized identifier along with a token string. After the macro is defined, then the compiler can substitute the token string for each occurrence of the identifier within the source file.
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 allows the definition of macros within your source code. These macro definitions allow constant values to be declared for use throughout your code. */ #include <stdio.h> #include <string.h> typedef struct Books { char title[50]; char author[50]; char subject[100]; int book_id; } Book; int main( ) { Book book; strcpy( book.title, "C Programming"); strcpy( book.author, "XCoder"); strcpy( book.subject, "C Programming Tutorial"); book.book_id = 6495407; printf( "Book title : %s\n", book.title); printf( "Book author : %s\n", book.author); printf( "Book subject : %s\n", book.subject); printf( "Book book_id : %d\n", book.book_id); return 0; }
Continue Statement in C
The continue statement in C programming works somewhat like the break statement. Instead of forcing termination, it forces the next iteration of the loop to take place, skipping any code in between. For the for loop, continue statement causes the conditional test and increment portions of the loop to execute. For the while and do...while loops, continue statement causes the program control to pass to the conditional tests.
Syntax for Continue Statement in C
//loop statements continue; //some lines of the code which is to be skipped
The continue statement in C language is used to bring the program control to the beginning of the loop. The continue statement skips some lines of code inside the loop and continues with the next iteration. It is mainly used for a condition so that we can skip some code for a particular condition.
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 continue statement skips the current iteration of the loop and continues with the next iteration. */ // Program to calculate the sum of numbers (10 numbers max) // If the user enters a negative number, it's not added to the result #include <stdio.h> int main() { int i; double number, sum = 0.0; for (i = 1; i <= 10; ++i) { printf("Enter a n%d: ", i); scanf("%lf", &number); if (number < 0.0) { continue; } sum += number; // sum = sum + number; } printf("Sum = %.2lf", sum); return 0; }
Break Statement in C
The break is a keyword in C which is used to bring the program control out of the loop. The break statement is used inside loops or switch statement. The break statement breaks the loop one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to outer loops.
Syntax for Break Statement in C
//loop statement... break;
When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. It can be used to terminate a case in the switch statement (covered in the next chapter). If you are using nested loops, the break statement will stop the execution of the innermost loop and start executing the next line of code after the block.
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
/* bring the program control out of the loop by break keyword */ // Program to calculate the sum of numbers (10 numbers max) // If the user enters a negative number, the loop terminates #include <stdio.h> int main() { int i; double number, sum = 0.0; for (i = 1; i <= 10; ++i) { printf("Enter n%d: ", i); scanf("%lf", &number); // if the user enters a negative number, break the loop if (number < 0.0) { break; } sum += number; // sum = sum + number; } printf("Sum = %.2lf", sum); 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. Here are the two types of file that can be included using #include: • 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.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* #include directive tells the preprocessor to insert the contents of another file into the source code at the point where the #include directive is found. */ // C program to illustrate file inclusion // <> used to import system header file #include <stdio.h> // " " used to import user-defined file #include "process.h" // main function int main() { // add function defined in process.h add(10, 20); // mult function defined in process.h multiply(10, 20); // printf defined in stdio.h printf("Process completed"); 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
#include<graphics.h> 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.
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
/* draw a rectangle by rectangle() function example */ // C program to draw a rectangle #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; // 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); getch(); // closegraph function closes the graphics // mode and deallocates all memory allocated // by graphics system . closegraph(); return 0; }
Logical Operators in C
An expression containing logical operator returns either 0 or 1 depending upon whether expression results true or false. Logical operators are commonly used in decision making in C programming. These operators are used to perform logical operations and used with conditional statements like C if-else statements.
&&
Called Logical AND operator. If both the operands are non-zero, then the condition becomes true.
||
Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true.
!
Called Logical NOT Operator. It is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false.
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
/* logical operators in C language */ #include <stdio.h> main() { int a = 4; int b = 23; int c ; if ( a && b ) { printf("Line 1 - Condition is true\n" ); } if ( a || b ) { printf("Line 2 - Condition is true\n" ); } /* lets change the value of a and b */ a = 2; b = 8; if ( a && b ) { printf("Line 3 - Condition is true\n" ); } else { printf("Line 3 - Condition is not true\n" ); } if ( !(a && b) ) { printf("Line 4 - Condition is true\n" ); } }
gotoxy() Function in C
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.
Syntax for gotoxy() Function in C
#include <stdio.h> void gotoxy(int x, int y);
x
x-coordinate of the point
y
y-coordinate of the point where (x, y) is the position where we want to place the cursor. If you want to take your cursor on a particular coordinate on the window, then this function is made for you. What it takes from you are two parameters. The Integers should be the x and y coordinate of the console. This is pretty helpful for games and animations. The Integers should be passed when you call the function in your 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
/* place cursor at a desired location on screen by gotoxy() function example */ #include <stdio.h> //to use 'gotoxy()' and 'getch()' #include <conio.h> int main() { // define the type of variables int a, b; // define the value of variables a = 50; b = 30; // change cursor position on further co-ordinates. gotoxy(a, b); // message printf("The position of cursor is changed"); // for killing the execution getch(); return 0; }
kbhit() in Function in C
The kbhit is basically the Keyboard Hit. Function kbhit in C is used to determine if a key has been pressed or not. 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();
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
/* check whether a key is pressed or not by kbhit() function example */ #include <stdio.h> #include <conio.h> main() { char ch; printf("Enter keys (ESC to exit)\n"); while (1) { //define infinite loop for taking keys if (kbhit) { ch = getch(); // Get typed character into ch if ((int)ch == 27) //when esc button is pressed, then it will comeout from loop break; printf("You have entered : %c\n", ch); } } }
getmaxy() Function in C
The header file graphics.h contains getmaxy() function which returns the maximum Y coordinate for current graphics mode and driver. getmaxy returns the maximum (screen-relative) y value for the current graphics driver and mode. For example, on a CGA in 320*200 mode, getmaxy returns 199. getmaxy is invaluable for centering, determining the boundaries of a region onscreen, and so on.
Syntax for getmaxy() Function in C
#include <graphics.h> int getmaxy(void);
getmaxy() returns the maximum y screen coordinate. getmaxy() function is used to fetch the maximum Y coordinate for the current graphics mode or 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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
/* get the maximum Y coordinate for current graphics mode and driver by getmaxy() 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; char arr[100]; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, ""); // sprintf stands for "String print". // Instead of printing on console, it // store output on char buffer which // are specified in sprintf sprintf(arr, "Maximum Y coordinate for current " "graphics mode And driver = %d", getmaxy()); // outtext function displays text at // current position. outtext(arr); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0; }
For Loop Statement in C
The for loop is used in the case where we need to execute some part of the code until the given condition is satisfied. The for loop is also called as a per-tested loop. It is better to use for loop if the number of iteration is known in advance. The for-loop statement is a very specialized while loop, which increases the readability of a program. It is frequently used to traverse the data structures like the array and linked list.
Syntax of For Loop Statement in C
for (initialization; condition test; increment or decrement) { //Statements to be executed repeatedly }
Step 1
First initialization happens and the counter variable gets initialized.
Step 2
In the second step the condition is checked, where the counter variable is tested for the given condition, if the condition returns true then the C statements inside the body of for loop gets executed, if the condition returns false then the for loop gets terminated and the control comes out of the loop.
Step 3
After successful execution of statements inside the body of loop, the counter variable is incremented or decremented, depending on the operation (++ or --).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* for loop statement in C language */ // Program to calculate the sum of first n natural numbers // Positive integers 1,2,3...n are known as natural numbers #include <stdio.h> int main() { int num, count, sum = 0; printf("Enter a positive integer: "); scanf("%d", &num); // for loop terminates when num is less than count for(count = 1; count <= num; ++count) { sum += count; } printf("Sum = %d", sum); 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
/* determine the size of memory required to store an 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; }
textheight() Function in C
The graphics function textheight takes the current font size and multiplication factor, and determines the height of textstring in pixels. This function is useful for adjusting the spacing between lines, computing viewport heights, sizing a title to make it fit on a graph or in a box, and so on. For example, with the 8x8 bit-mapped font and a multiplication factor of 1 (set by settextstyle), the string is 8 pixels high. settextstyle is used to change font size, family and direction. Based on the recent settings on settextstyle, textwidth function returns the width and textheight returns the height of the specfied string. Use textheight to compute the height of strings, instead of doing the computations manually. By using this function, no source code modifications have to be made when different fonts are selected.
Syntax for textheight() Function in C
#include <graphics.h> int textheight(char *textstring);
textstring
text whose height should be measured textheight() function returns the height of the specified string. textheight() function gives the height of string which is based on the current setting of the settextstyle() function which is used to change font style family and direction of the text.
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
/* compute the height of strings by textheight() 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, height; char arr[100]; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, ""); // textheight function height = textheight("I love Clementine"); //sprintf stands for "String print". //Instead of printing on console, //it store output on char buffer //which are specified in sprintf sprintf(arr, "Textheight is = %d", height); //outtext function displays text //at current position. outtext(arr); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0; }
settextjustify() Function in C
Text output after a call to settextjustify is justified around the current position horizontally and vertically, as specified. The default justification settings are LEFT_TEXT (for horizontal) and TOP_TEXT (for vertical). The enumeration text_just in graphics.h provides names for the horiz and vert settings passed to settextjustify.
Syntax for settextjustify() Function in C
#include <graphics.h> void settextjustify(int horiz, int vert);
horiz
• LEFT_TEXT – 0 left-justify text • CENTER_TEXT – 1 center text • RIGHT_TEXT – 2 right-justify text
vert
• BOTTOM_TEXT – 0 bottom-justify text • CENTER_TEXT – 1 center text • TOP_TEXT – 2 top-justify text If horiz is equal to LEFT_TEXT and direction equals HORIZ_DIR, the CP's x component is advanced after a call to outtext(string) by textwidth(string). settextjustify affects text written with outtext and cannot be used with text mode and stream functions. If invalid input is passed to settextjustify, graphresult returns -11, and the current text justification remains unchanged.
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
/* justify text output around the current position (CP) horizontally and vertically, as specified by settextjustify() function example */ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> /* function prototype */ void xat(int x, int y); /* horizontal text justification settings */ char *hjust[] = { "LEFT_TEXT", "CENTER_TEXT", "RIGHT_TEXT" }; /* vertical text justification settings */ char *vjust[] = { "BOTTOM_TEXT", "CENTER_TEXT", "TOP_TEXT" }; int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; int midx, midy, hj, vj; char msg[80]; /* 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 */ } midx = getmaxx() / 2; midy = getmaxy() / 2; /* loop through text justifications */ for (hj=LEFT_TEXT; hj<=RIGHT_TEXT; hj++) for (vj=LEFT_TEXT; vj<=RIGHT_TEXT; vj++) { cleardevice(); /* set the text justification */ settextjustify(hj, vj); /* create a message string */ sprintf(msg, "%s %s", hjust[hj], vjust[vj]); /* create crosshairs on the screen */ xat(midx, midy); /* output the message */ outtextxy(midx, midy, msg); getch(); } /* clean up */ closegraph(); return 0; } void xat(int x, int y) /* draw an x at (x,y) */ { line(x-4, y, x+4, y); line(x, y-4, x, y+4); }
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 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
/* wait for any character input from keyboard by getch() function example. */ // C code to illustrate working of // getch() to accept hidden inputs #include <conio.h> #include <dos.h> // delay() #include <stdio.h> #include <string.h> void main() { // Taking the password of 8 characters char pwd[9]; int i; // To clear the screen clrscr(); printf("Enter Password: "); for (i = 0; i < 8; i++) { // Get the hidden input // using getch() method pwd[i] = getch(); // Print * to show that // a character is entered printf("*"); } pwd[i] = '\0'; printf("\n"); // Now the hidden input is stored in pwd[] // So any operation can be done on it // Here we are just printing printf("Entered password: "); for (i = 0; pwd[i] != '\0'; i++) printf("%c", pwd[i]); // Now the console will wait // for a key to be pressed getch(); }
printf() Function in C
Writes the C string pointed by format to the standard output (stdout). If format includes format specifiers (subsequences beginning with %), the additional arguments following format are formatted and inserted in the resulting string replacing their respective specifiers. printf format string refers to a control parameter used by a class of functions in the input/output libraries of C programming language. The string is written in a simple template language: characters are usually copied literally into the function's output, but format specifiers, which start with a % character, indicate the location and method to translate a piece of data (such as a number) to characters. "printf" is the name of one of the main C output functions, and stands for "print formatted". printf format strings are complementary to scanf format strings, which provide formatted input (parsing). In both cases these provide simple functionality and fixed format compared to more sophisticated and flexible template engines or parsers, but are sufficient for many purposes.
Syntax for printf() function in C
#include <stdio.h> int printf ( const char * format, ... );
format
C string that contains the text to be written to stdout. It can optionally contain embedded format specifiers that are replaced by the values specified in subsequent additional arguments and formatted as requested. A format specifier follows this prototype: [see compatibility note below] %[flags][width][.precision][length]specifier Where the specifier character at the end is the most significant component, since it defines the type and the interpretation of its corresponding argument:
specifier
a conversion format specifier.
d or i
Signed decimal integer
u
Unsigned decimal integer
o
Unsigned octal
x
Unsigned hexadecimal integer
X
Unsigned hexadecimal integer (uppercase)
f
Decimal floating point, lowercase
F
Decimal floating point, uppercase
e
Scientific notation (mantissa/exponent), lowercase
E
Scientific notation (mantissa/exponent), uppercase
g
Use the shortest representation: %e or %f
G
Use the shortest representation: %E or %F
a
Hexadecimal floating point, lowercase
A
Hexadecimal floating point, uppercase
c
Character
s
String of characters
p
Pointer address
n
Nothing printed. The corresponding argument must be a pointer to a signed int. The number of characters written so far is stored in the pointed location.
%
A % followed by another % character will write a single % to the stream. The format specifier can also contain sub-specifiers: flags, width, .precision and modifiers (in that order), which are optional and follow these specifications:
flags
one or more flags that modifies the conversion behavior (optional)
-
Left-justify within the given field width; Right justification is the default (see width sub-specifier).
+
Forces to preceed the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a - sign.
(space)
If no sign is going to be written, a blank space is inserted before the value.
#
Used with o, x or X specifiers the value is preceeded with 0, 0x or 0X respectively for values different than zero. Used with a, A, e, E, f, F, g or G it forces the written output to contain a decimal point even if no more digits follow. By default, if no digits follow, no decimal point is written.
0
Left-pads the number with zeroes (0) instead of spaces when padding is specified (see width sub-specifier).
width
an optional * or integer value used to specify minimum width field.
(number)
Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.
*
The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
.precision
an optional field consisting of a . followed by * or integer or nothing to specify the precision.
.number
For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0. For a, A, e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6). For g and G specifiers: This is the maximum number of significant digits to be printed. For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered. If the period is specified without an explicit value for precision, 0 is assumed.
.*
The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
length
an optional length modifier that specifies the size of the argument.
... (additional arguments)
Depending on the format string, the function may expect a sequence of additional arguments, each containing a value to be used to replace a format specifier in the format string (or a pointer to a storage location, for n). There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function. If a writing error occurs, the error indicator (ferror) is set and a negative number is returned. If a multibyte character encoding error occurs while writing wide characters, errno is set to EILSEQ and a negative number 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
/* print formatted data to stdout by printf() function example */ #include <stdio.h> int main() { char ch; char str[100]; int a; float b; printf("Enter any character \n"); scanf("%c", &ch); printf("Entered character is %c \n", ch); printf("Enter any string ( upto 100 character ) \n"); scanf("%s", &str); printf("Entered string is %s \n", str); printf("Enter integer and then a float: "); // Taking multiple inputs scanf("%d%f", &a, &b); printf("You entered %d and %f", a, b); return 0; }
setcolor() Function in C
setcolor() function is used to set the foreground color in graphics mode. After resetting the foreground color you will get the text or any other shape which you want to draw in that color. setcolor sets the current drawing color to color, which can range from 0 to getmaxcolor. The current drawing color is the value to which pixels are set when lines, and so on are drawn. The drawing colors shown below are available for the CGA and EGA, respectively.
Syntax for setcolor() Function in C
#include <graphics.h> void setcolor(int color);
Each color is assigned a number. The possible color values are from 0 - 15: • 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 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.
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
/* set the current drawing color to color, which can range from 0 to getmaxcolor by setcolor() function example */ // C Implementation for setcolor() #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; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, ""); // Draws circle in white color // center at (100, 100) and radius // as 50 circle(100, 100, 50); // setcolor function setcolor(GREEN); // Draws circle in green color // center at (200, 200) and radius // as 50 circle(200, 200, 50); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0; }
getmaxx() Function in C
The header file graphics.h contains getmaxx() function which returns the maximum X coordinate for current graphics mode and driver. getmaxx() returns the maximum (screen-relative) x value for the current graphics driver and mode. For example, on a CGA in 320*200 mode, getmaxx returns 319. getmaxx is invaluable for centering, determining the boundaries of a region onscreen, and so on.
Syntax for getmaxx() Function in C
#include <graphics.h> int getmaxx(void);
getmaxx returns the maximum x screen coordinate. getmaxx() function is used to fetch the maximum X coordinate for the current graphics mode or 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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
/* get the maximum X coordinate for current graphics mode and driver by getmaxx() 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; char arr[100]; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, ""); // sprintf stands for "String print". // Instead of printing on console, it // store output on char buffer which // are specified in sprintf sprintf(arr, "Maximum X coordinate for current " "graphics mode And driver = %d", getmaxx()); // outtext function displays text at // current position. outtext(arr); 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 suspend execution of a program for a particular time. delay() function requires a parameter which should be a number, defining the milliseconds for the delay. To use delay function in your program you should include the "dos.h" header file which is not a part of standard C library. Here unsigned int is the number of milliseconds (remember 1 second = 1000 milliseconds).
Syntax for delay() Function in C
#include<stdio.h> void delay(unsigned int);
sleep() function requires a parameter which should be a number, defining the seconds to sleep. These functions are pretty useful when you want to show the user multiple outputs, for a given period of time. The nice thing about this is that we can also make alarm and reminder for the user in our program. Hence, these two functions are pretty handy, if you are planning to make a real-world application.
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
/* suspend execution of a program for a particular time by delay() function example */ #include <stdio.h> //to use 'delay()' #include <dos.h> int main() { // message for user printf("After printing this message the program will get end in next 5 seconds \n"); // delay the process for 5 seconds as it takes integer value in milliseconds. delay(5000); // message for user. printf("After printing this message the program will get delay for next 15 seconds\n"); // to terminate the process for next 15 seconds. sleep(15); // message for user printf("After printing this message the program will get end in next 2 seconds \n"); // delay the process for 2 seconds as it takes integer value in milliseconds. delay(2000); 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, try to use some random values in loop, vary delay and enjoy.
Syntax for sound() Function in C
#include <dos.h> void sound(unsigned frequency);
The delay() function has been used in this function to delay for the next sound. The Second thing is the nosound() function, which simply silent the system. These two functions are from file dos.h, which should be included in 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
/* produce the sound of a specified frequency by sound() function 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); //the sound of frequency 200. sound(200); //the sound of frequency 500. sound(500); //calling the function to stop the //system sound. nosound(); return 0; }
If Else Statement in C
The if-else statement is used to perform two operations for a single condition. The if-else statement is an extension to the if statement using which, we can perform two different operations, i.e., one is for the correctness of that condition, and the other is for the incorrectness of the condition. Here, we must notice that if and else block cannot be executed simiulteneously. Using if-else statement is always preferable since it always invokes an otherwise case with every if condition.
Syntax for if-else Statement in C
if (test expression) { // run code if test expression is true } else { // run code if test expression is false }
If the test expression is evaluated to true, • statements inside the body of if are executed. • statements inside the body of else are skipped from execution. If the test expression is evaluated to false, • statements inside the body of else are executed • statements inside the body of if are skipped from execution.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/* if else statement in C language */ // Check whether an integer is odd or even #include <stdio.h> int main() { int number; printf("Enter an integer: "); scanf("%d", &number); // True if the remainder is 0 if (number%2 == 0) { printf("%d is an even integer.",number); } else { printf("%d is an odd integer.",number); } return 0; }
floodfill() Function in C
floodfill function is used to fill an enclosed area. Current fill pattern and fill color is used to fill the area.(x, y) is any point on the screen if (x,y) lies inside the area then inside will be filled otherwise outside will be filled,border specifies the color of boundary of area. To change fill pattern and fill color use setfillstyle. floodfill fills an enclosed area on bitmap devices. (x,y) is a "seed point" within the enclosed area to be filled. The area bounded by the color border is flooded with the current fill pattern and fill color. If the seed point is within an enclosed area, the inside will be filled. If the seed is outside the enclosed area, the exterior will be filled. Use fillpoly instead of floodfill whenever possible so that you can maintain code compatibility with future versions.
Syntax for floodfill() Function in C
#include <graphics.h> void floodfill(int x, int y, int border);
x
X coordinate of point on the screen
y
Y coordinate of point on the screen
border
specifies the color of border of the enclosed area. 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 If an error occurs while flooding a region, graphresult returns a value of -7.
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
/* fill an enclosed area on bitmap devices by floodfill() 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, " "); // 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; }
cleardevice() Function in C
The header file graphics.h contains cleardevice() function. cleardevice() is a function which is used to clear the screen by filling the whole screen with the current background color. It means that cleardevice() function is used to clear the whole screen with the current background color and it also sets the current position to (0,0). . Both clrscr() and cleardevice() functions are used to clear the screen but clrscr() is used in text mode and cleardevice function is used in the graphics mode.
Syntax for cleardevice() Function in C
#include <graphics.h> void cleardevice();
Clearing the screen is always an issue for developers, because now and then we want to show the user some useful or important data, which should be highlighted or at least have user's attention. It is important to note that, after clearing the device, we will lose all our drawing, shapes or images. It is useful but be little cautious.
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
/* clear the screen in graphics mode and set the current position to (0,0) by cleardevice() function example.*/ #include <graphics.h> #include <conio.h> int main() { //initilizing graphic driver and //graphic mode variable int graphicdriver=DETECT,graphicmode; //calling initgraph initgraph(&graphicdriver,&graphicmode,"c:\\turboc3\\bgi"); //Printing message for user outtextxy(20, 20 + 20, "Program to use graph default in C graphics"); //message to clear screen outtextxy(20, 50 + 30, "Press any key to clear screen"); //getting character and clear the device screen getch(); cleardevice(); //message to press key to get exit from program outtextxy(20, 20 + 20, "Press any key to exit..."); getch(); return 0; }
restorecrtmode() Function in C
restorecrtmode restores the original video mode detected by initgraph. This function can be used in conjunction with setgraphmode to switch back and forth between text and graphics modes. Textmode should not be used for this purpose; use it only when the screen is in text mode, to change to a different text mode.
Syntax for restorecrtmode() Function in C
#include <graphics.h> void restorecrtmode(void);
restorecrtmode() restores the original screen mode that existed prior to calling initgraph(). Most often, this represents the text mode. restorecrtmode() and setgraphmode() can be alternately called to switch between text and graphics mode. Function returns nothing.
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
/* restore the original video mode detected by initgraph by restorecrtmode() function example. */ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> int main(void) { /* request auto detection */ int gd = DETECT, gmode, err; int midx, midy; /* initialize graphics and local variables */ initgraph(&gd, &gmode, "C:/TURBOC3/BGI"); /* read result of initialization */ err = graphresult(); if (err != grOk) { /* an error occurred */ printf("Graphics error: %s\n", grapherrormsg(err)); getch(); return 0; } /* mid position in x and y-axis */ midx = getmaxx() / 2; midy = getmaxy() / 2; /* output a message */ settextjustify(CENTER_TEXT, CENTER_TEXT); outtextxy(midx, midy - 100, "GRAPHICS MODE"); /* draw a rectange at the given position */ rectangle(midx - 50, midy - 50, midx + 50, midy + 50); getch(); /* restore system to text mode */ restorecrtmode(); printf("Restored system to text mode"); getch(); /* return to graphics mode */ setgraphmode(getgraphmode()); /* output a message */ settextjustify(CENTER_TEXT, CENTER_TEXT); outtextxy(midx, midy - 100, "BACK TO GRAPHIC MODE!!"); /* draws a rectangle at the given postion */ rectangle(midx - 50, midy - 50, midx + 50, midy + 50); /* clean up */ getch(); closegraph(); return 0; }
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. The "malloc" or "memory allocation" method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. It doesn't Iniatialize memory at execution time so that it has initializes each block with the default garbage value initially.
Syntax for malloc() Function in C
#include <stdlib.h> void* malloc (size_t size);
size
Size of the memory block, in bytes. size_t is an unsigned integral type. On success, function returns 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.
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
/* allocate memory block by malloc() function example */ // Program to calculate the sum of n numbers entered by the user #include <stdio.h> #include <stdlib.h> int main() { int n, i, *ptr, sum = 0; printf("Enter number of elements: "); scanf("%d", &n); ptr = (int*) malloc(n * sizeof(int)); // if memory cannot be allocated if(ptr == NULL) { printf("Error! memory not allocated."); exit(0); } printf("Enter elements: "); for(i = 0; i < n; ++i) { scanf("%d", ptr + i); sum += *(ptr + i); } printf("Sum = %d", sum); // deallocating the memory free(ptr); return 0; }
initgraph() Function in C
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. Normally, initgraph loads a graphics driver by allocating memory for the driver (through _graphgetmem), then loading the appropriate .BGI file from disk. As an alternative to this dynamic loading scheme, you can link a graphics driver file (or several of them) directly into your executable program file.
Syntax for initgraph() Function in C
#include <graphics.h> void initgraph(int *graphdriver, int *graphmode, char *pathtodriver);
pathtodriver
pathtodriver specifies the directory path where initgraph looks for graphics drivers. initgraph first looks in the path specified in pathtodriver, then (if they are not there) in the current directory. Accordingly, if pathtodriver is null, the driver files (*.BGI) must be in the current directory. This is also the path settextstyle searches for the stroked character font files (*.CHR).
graphdriver
graphdriver is an integer that specifies the graphics driver to be used. You can give it a value using a constant of the graphics_drivers enumeration type, which is defined in graphics.h and listed below. • DETECT – 0 (requests autodetect) • CGA – 1 • MCGA – 2 • EGA – 3 • EGA64 – 4 • EGAMONO – 5 • IBM8514 – 6 • HERCMONO – 7 • ATT400 – 8 • VGA – 9 • PC3270 – 10
graphmode
graphmode is an integer that specifies the initial graphics mode (unless *graphdriver equals DETECT; in which case, *graphmode is set by initgraph to the highest resolution available for the detected driver). You can give *graphmode a value using a constant of the graphics_modes enumeration type, which is defined in graphics.h and listed below. 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 27 28 29 30 31 32 33 34 35
/* initgraph initializes the graphics system by loading a graphics driver by initgraph() function example*/ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; /* initialize graphics mode */ 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); /* return with error code */ } /* draw a line */ line(0, 0, getmaxx(), getmaxy()); /* clean up */ getch(); closegraph(); return 0; }
fflush() Function in C
Flush stream. If the given stream was open for writing (or if it was open for updating and the last i/o operation was an output operation) any unwritten data in its output buffer is written to the file. If stream is a null pointer, all such streams are flushed. In all other cases, the behavior depends on the specific library implementation. In some implementations, flushing a stream open for reading causes its input buffer to be cleared (but this is not portable expected behavior). The stream remains open after this call. When a file is closed, either because of a call to fclose or because the program terminates, all the buffers associated with it are automatically flushed.
Syntax for fflush() Function in C
#include <stdio.h> int fflush ( FILE * stream );
stream
Pointer to a FILE object that specifies a buffered stream. This function returns a zero value on success. If an error occurs, EOF is returned and the error indicator is set (i.e. feof).
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
/* clean (or flush) the output buffer and transfer the buffered data into the terminal (in the case of stdout) or disk (throughout the case of file output) by fflush() function example. */ #include <stdio.h> #include <string.h> int main () { char buff[1024]; memset( buff, '\0', sizeof( buff )); fprintf(stdout, "Going to set full buffering on\n"); setvbuf(stdout, buff, _IOFBF, 1024); fprintf(stdout, "HappyCodings.com\n"); fprintf(stdout, "This output will go into buff\n"); fflush( stdout ); fprintf(stdout, "and this will appear when programm\n"); fprintf(stdout, "will come after sleeping 5 seconds\n"); sleep(5); return(0); }
exit() Function in C
The exit() function is used to terminate a process or function calling immediately in the program. It means any open file or function belonging to the process is closed immediately as the exit() function occurred in the program. The exit() function is the standard library function of the C, which is defined in the stdlib.h header file. So, we can say it is the function that forcefully terminates the current program and transfers the control to the operating system to exit the program. The exit(0) function determines the program terminates without any error message, and then the exit(1) function determines the program forcefully terminates the execution process.
Syntax for exit() Function in C
#include <stdlib.h> 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. The exit function does not return anything. • We must include the stdlib.h header file while using the exit () function. • It is used to terminate the normal execution of the program while encountered the exit () function. • The exit () function calls the registered atexit() function in the reverse order of their registration. • We can use the exit() function to flush or clean all open stream data like read or write with unwritten buffered data. • It closed all opened files linked with a parent or another function or file and can remove all files created by the tmpfile function. • The program's behaviour is undefined if the user calls the exit function more than one time or calls the exit and quick_exit function. • The exit function is categorized into two parts: exit(0) and exit(1).
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
/* call all functions registered with atexit and terminates the program by exit() function example */ #include <stdio.h> #include <stdlib.h> int main () { // declaration of the variables int i, num; printf ( " Enter the last number: "); scanf ( " %d", &num); for ( i = 1; i<num; i++) { // use if statement to check the condition if ( i == 6 ) /* use exit () statement with passing 0 argument to show termination of the program without any error message. */ exit(0); else printf (" \n Number is %d", i); } return 0; }
puts() Function in C
Write string to stdout. Writes the C string pointed by str to the standard output (stdout) and appends a newline character ('\n'). The function begins copying from the address specified (str) until it reaches the terminating null character ('\0'). This terminating null-character is not copied to the stream. Notice that puts not only differs from fputs in that it uses stdout as destination, but it also appends a newline character at the end automatically (which fputs does not). The puts() function is very much similar to printf() function. The puts() function is used to print the string on the console which is previously read by using gets() or scanf() function. The puts() function returns an integer value representing the number of characters being printed on the console. Since, it prints an additional newline character with the string, which moves the cursor to the new line on the console, the integer value returned by puts() will always be equal to the number of characters present in the string plus 1.
Syntax for puts() Function in C
#include <stdio.h> int puts(const char *str)
str
C string to be printed. On success, a non-negative value is returned. On error, the function returns EOF and sets the error indicator (ferror).
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
/* write string to stdout by puts() function example */ #include <stdio.h> #include <string.h> int main() { char name[50]; printf("Enter your name "); gets(name); int age[50]; printf("Enter your age "); gets(age); char address[50]; printf("Enter your address "); gets(address); int pincode[50]; printf("Enter your pincode "); gets(pincode); printf("Entered Name is: "); puts(name); printf("Entered age is: "); puts(age); printf("Entered address is: "); puts(address); printf("Entered pincode is: "); puts(pincode); getch(); return 0; }
While Loop Statement in C
While loop is also known as a pre-tested loop. In general, a while loop allows a part of the code to be executed multiple times depending upon a given boolean condition. It can be viewed as a repeating if statement. The while loop is mostly used in the case where the number of iterations is not known in advance. The while loop evaluates the test expression inside the parentheses (). If test expression is true, statements inside the body of while loop are executed. Then, test expression is evaluated again. The process goes on until test expression is evaluated to false. If test expression is false, the loop terminates.
Syntax of While Loop Statement in C
while (testExpression) { // the body of the loop }
• The while loop evaluates the testExpression inside the parentheses (). • If testExpression is true, statements inside the body of while loop are executed. Then, testExpression is evaluated again. • The process goes on until testExpression is evaluated to false. • If testExpression is false, the loop terminates (ends).
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
/* while loop statement in C language */ #include<stdio.h> int main() { int n, num, sum = 0, remainder; printf("Enter a number: "); scanf("%d", &n); num = n; // keep looping while n > 0 while( n > 0 ) { remainder = n % 10; // get the last digit of n sum += remainder; // add the remainder to the sum n /= 10; // remove the last digit from n } printf("Sum of digits of %d is %d", num, sum); // signal to operating system everything works fine return 0; }
Unions in C Language
A union is a special data type available in C that allows to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple-purpose.
Defining a Union
To define a union, you must use the union statement in the same way as you did while defining a structure. The union statement defines a new data type with more than one member for your program. The format of the union statement is as follows:
union [union tag] { member definition; member definition; ... member definition; } [one or more union variables];
The union tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the union's definition, before the final semicolon, you can specify one or more union variables but it is optional. Here is the way you would define a union type named Data having three members i, f, and str:
union Data { int i; float f; char str[20]; } data;
Now, a variable of Data type can store an integer, a floating-point number, or a string of characters. It means a single variable, i.e., same memory location, can be used to store multiple types of data. You can use any built-in or user defined data types inside a union based on your requirement.
Accessing Union Members
To access any member of a union, we use the member access operator (.). The member access operator is coded as a period between the union variable name and the union member that we wish to access. You would use the keyword union to define variables of union 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 30 31 32 33 34 35 36 37 38 39
/* unions in C language */ #include <stdio.h> #include <string.h> union student { char name[20]; char subject[20]; float percentage; }; int main() { union student record1; union student record2; // assigning values to record1 union variable strcpy(record1.name, "Jack"); strcpy(record1.subject, "Red"); record1.percentage = 96.23; printf("Union record1 values example\n"); printf(" Name : %s \n", record1.name); printf(" Subject : %s \n", record1.subject); printf(" Percentage : %f \n\n", record1.percentage); // assigning values to record2 union variable printf("Union record2 values example\n"); strcpy(record2.name, "Mani"); printf(" Name : %s \n", record2.name); strcpy(record2.subject, "Physics"); printf(" Subject : %s \n", record2.subject); record2.percentage = 99.50; printf(" Percentage : %f \n", record2.percentage); return 0; }
getmaxcolor() Function in C
getmaxcolor() returns highest possible color value. The header file graphics.h contains getmaxcolor() function, which returns maximum color value for current graphics mode and driver. As color numbering starts from zero, total number of colors available for current graphics mode and driver are ( getmaxcolor() + 1 ) .
Syntax for getmaxcolor() Function in C
#include<graphics.h> int getmaxcolor();
getmaxcolor returns the maximum color value. There are various colors that are also mentioned in graphics.h header file and the possible color values are from 0 - 15: • 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 33 34 35 36 37 38 39 40 41 42 43 44
/* return the maximum color value by getmaxcolor() graphic function code example */ // C Implementation for getmaxcolor() #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; char arr[100]; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, ""); // sprintf stands for "String print". // Instead of printing on console, it // store output on char buffer which // are specified in sprintf sprintf(arr, "Maximum number of colors for " "current graphics mode and " "driver = %d", getmaxcolor() + 1); // outtext function displays text // at current position. outtextxy(20, 100, arr); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0; }
toupper() Function in C
Convert lowercase letter to uppercase. Converts c to its uppercase equivalent if c is a lowercase letter and has an uppercase equivalent. If no such conversion is possible, the value returned is c unchanged. Notice that what is considered a letter may depend on the locale being used; In the default "C" locale, a lowercase letter is any of: a b c d e f g h i j k l m n o p q r s t u v w x y z, which translate respectively to: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z. In other locales, if a lowercase character has more than one correspondent uppercase character, this function always returns the same character for the same value of c. In C++, a locale-specific template version of this function (toupper) exists in header <locale>.
Syntax for toupper() Function in C
#include <ctype.h> int toupper ( int c );
c
Character to be converted, casted to an int, or EOF Function returns the uppercase equivalent to c, if such value exists, or c (unchanged) otherwise. The value is returned as an int value that can be implicitly casted to char. If the character passed is a lowercase alphabet then the toupper() function converts a lowercase alphabet to an uppercase alphabet. It is defined in the ctype.h header file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/* convert lowercase letter to uppercase by toupper() function example */ //Example for toupper in C Programming #include <stdio.h> #include <ctype.h> int main() { char ch; printf("Please Enter Any Valid Character: \n"); scanf("%c", &ch); if(isalpha(ch)) { printf("\n We Converted Your character to Upper Case = %c", toupper(ch)); } else { printf("\n Please Enter a Valid character"); } }
setbkcolor() Function in C
setbkcolor() function is used to set the background color in graphics mode. The default background color is black and default drawing color as we know is white. setbkcolor() function takes only one argument it would be either the name of color defined in graphics.h header file or number associated with those colors. If we write setbkcolor(yellow) it changes the background color in Green.
Syntax for setbkcolor() Function in C
#include <graphics.h> void setbkcolor(int color);
possible color values
• 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 On CGA and EGA systems, setbkcolor changes the background color by changing the first entry in the palette. If you use an EGA or a VGA, and you change the palette colors with setpalette or setallpalette, the defined symbolic constants might not give you the correct color. This is because the parameter to setbkcolor indicates the entry number in the current palette rather than a specific color (unless the parameter passed is 0, which always sets the background color to black).
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
/* set the background to the color specified by color by setbkcolor() function example */ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> int main(void) { /* _select driver and mode that supports multiple background colors*/ int gdriver = EGA, gmode = EGAHI, errorcode; int bkcol, maxcolor, x, y; char msg[80]; /* 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 */ } /* maximum color index supported */ maxcolor = getmaxcolor(); /* for centering text messages */ settextjustify(CENTER_TEXT, CENTER_TEXT); x = getmaxx() / 2; y = getmaxy() / 2; /* loop through the available colors */ for (bkcol=0; bkcol<=maxcolor; bkcol++) { /* clear the screen */ cleardevice(); /* select a new background color */ setbkcolor(bkcol); /* output a messsage */ if (bkcol == WHITE) setcolor(EGA_BLUE); sprintf(msg, "Background color: %d", bkcol); outtextxy(x, y, msg); getch(); } /* clean up */ closegraph(); return 0; }
Assignment Operators in C
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 41 42 43
/* assignment operators in C language */ #include <stdio.h> main() { int a = 23; int c ; c = a; printf("Line 1 - = Operator Example, Value of c = %d\n", c ); c += a; printf("Line 2 - += Operator Example, Value of c = %d\n", c ); c -= a; printf("Line 3 - -= Operator Example, Value of c = %d\n", c ); c *= a; printf("Line 4 - *= Operator Example, Value of c = %d\n", c ); c /= a; printf("Line 5 - /= Operator Example, Value of c = %d\n", c ); c = 120; c %= a; printf("Line 6 - %= Operator Example, Value of c = %d\n", c ); c <<= 2; printf("Line 7 - <<= Operator Example, Value of c = %d\n", c ); c >>= 2; printf("Line 8 - >>= Operator Example, Value of c = %d\n", c ); c &= 2; printf("Line 9 - &= Operator Example, Value of c = %d\n", c ); c ^= 2; printf("Line 10 - ^= Operator Example, Value of c = %d\n", c ); c |= 2; printf("Line 11 - |= Operator Example, Value of c = %d\n", c ); }
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. 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}.
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.
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
/* draw a 2-dimensional, rectangular filled in bar by bar() function example */ // C implementation of bar() function #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; }
clearviewport() Function in C
Clears the current viewport. clearviewport() function will erase the drawing done on the view port only and not the whole screen. Cleardevice is the function used to clear the whole screen with the background color. clearviewport() clears the current view port and resets the current position to (0, 0), relative to the current view port.
Syntax for clearviewport() Function in C
#include <graphics.h> void clearviewport(void);
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
/* clear the current viewport by clearviewport() function code example */ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> #define CLIP_ON 1 /* activates clipping in viewport */ int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode, ht; /* 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 */ } setcolor(getmaxcolor()); ht = textheight("W"); /* message in default full-screen viewport */ outtextxy(0, 0, "* <-- (0, 0) in default viewport"); /* create a smaller viewport */ setviewport(50, 50, getmaxx()-50, getmaxy()-50, CLIP_ON); /* display some messages */ outtextxy(0, 0, "* <-- (0, 0) in smaller viewport"); outtextxy(0, 2*ht, "Press any key to clear viewport:"); getch(); /* wait for a key */ clearviewport(); /* clear the viewport */ /* output another message */ outtextxy(0, 0, "Press any key to quit:"); /* clean up */ getch(); closegraph(); return 0; }
line() Function in C
line() is a library function of graphics.c in c programming language which is used to draw a line from two coordinates. line() function 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.
Syntax for line() Function in C
#include <graphics.h> 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. This is a predefined function named line which is used to draw a line on the output screen. It takes 4 arguments, first two parameters represent an initial point and the last two arguments are for the final points of the line.
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
/* draw a line from a point(x1,y1) to point(x2,y2) by line() function example */ /*C graphics program to draw a line.*/ #include <graphics.h> #include <conio.h> main() { int gd = DETECT, gm; //init graphics initgraph(&gd, &gm, "C:/TURBOC3/BGI"); /* if you are using turboc2 use below line to init graphics: initgraph(&gd, &gm, "C:/TC/BGI"); */ //draw a line /* line() function description parameter left to right x1: 100 y1: 100 x2: 200 y2: 100 */ line(100,100,200,100); //will draw a horizontal line line(10,10,200,10); //will draw another horizonatl line getch(); 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 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
/* set the text font, the direction in which text is displayed, and the size of the characters by settextstyle() function example. */ // C++ implementation for // settextstyle() function #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 text int x = 150; int y = 150; // font style int font = 8; // font direction int direction = 0; // font size int font_size = 5; // for setting text style settextstyle(font, direction, font_size); // for printing text in graphics window outtextxy(x, y, "Happy Codings"); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by graphics // system . closegraph(); return 0; }
setlinestyle() Function in C
setlinestyle() is a function which is used to draw the line of different- different styles. Turbo C compiler provides five line styles that are solid, dotted, center, dashed and user defined. These all five line styles are already enumerated in graphics.h header file as given below: setlinestyle() function contains three parameters type, pattern and thickness.
Syntax for setlinestyle() Function in C
#include <graphics.h> void setlinestyle(int linestyle, unsigned upattern, int thickness);
linestyle
First parameter contains the type of line like solid, dashed or dotted etc. • SOLID_LINE 0 Solid line • DOTTED_LINE 1 Dotted line • CENTER_LINE 2 Centered line • DASHED_LINE 3 Dashed line • USERBIT_LINE 4 User-defined line style
upattern
Second parameter is applicable only when type of line is user defined.
thickness
Third parameter specifies the thickness of the line it takes values 1 (line thickness of one pixel (normal)) or 3 (line thickness of three pixels (thick). • NORM_WIDTH 1 1 pixel wide • THICK_WIDTH 3 3 pixels wide Note: The linestyle parameter does not affect arcs, circles, ellipses, or pie slices. Only the thickness parameter is used. If invalid input is passed to setlinestyle, graphresult returns -11, and the current line style remains unchanged.
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
/* set the style for all lines drawn by line, lineto, rectangle, drawpoly by setlinestyle() function example */ // C Implementation for setlinestyle() #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; // variable to change the // line styles int c; // initial coordinate to // draw line int x = 200, y = 100; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, ""); // To keep track of lines for ( c = 0 ; c < 5 ; c++ ) { // setlinestyle function setlinestyle(c, 0, 1); // Drawing line line(x, y, x+200, y); y = y + 25; } getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); 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
/* put the bit image onto the screen by putimage() 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.website.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(); }
circle() Function in C
This library function is declared in graphics.h and used to draw a circle; it takes centre point coordinates and radius. Circle function is used to draw a circle with center (x,y) and third parameter specifies the radius of the circle. The code given below draws a circle. Where, (x, y) is center of the circle. 'radius' is the Radius of the circle.
Syntax for circle() Function in C
#include <graphics.h> circle(x, y, radius);
x
X-coordinate of the circle
y
Y-coordinate of the circle
radius
radius of the circle 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
/* draw a circle with center at (x, y) and given radius by circle() function example. */ // C Implementation for drawing circle #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, ""); // circle function circle(250, 200, 50); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0; }
Goto Statement in C
A goto statement in C programming language provides an unconditional jump from the 'goto' to a labeled statement in the same function. The goto statement is known as jump statement in C. As the name suggests, goto is used to transfer the program control to a predefined label. The goto statment can be used to repeat some part of the code for a particular condition. It can also be used to break the multiple loops which can't be done by using a single break statement.
Syntax for Goto Statement in C
label: //some part of the code; goto label;
Use of goto statement is highly discouraged in any programming language because it makes difficult to trace the control flow of a program, making the program hard to understand and hard to modify. Any program that uses a goto can be rewritten to avoid them.
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
/* transfer control of the program to the specified label by goto statement example */ // Program to calculate the sum and average of positive numbers // If the user enters a negative number, the sum and average are displayed. #include <stdio.h> int main() { const int maxInput = 100; int i; double number, average, sum = 0.0; for (i = 1; i <= maxInput; ++i) { printf("%d. Enter a number: ", i); scanf("%lf", &number); // go to jump if the user enters a negative number if (number < 0.0) { goto jump; } sum += number; } jump: average = sum / (i - 1); printf("Sum = %.2f\n", sum); printf("Average = %.2f", average); 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. Note: The EMPTY_FILL style is like a solid fill using the current background color (which is set by setbkcolor).
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
/* set the current fill pattern and fill color by setfillstyle() function example */ #include<stdio.h> #include<conio.h> #include<graphics.h> void main() { int gd=DETECT, gm,bkcolor; initgraph(&gd,&gm," "); setfillstyle(EMPTY_FILL,YELLOW); bar3d(2,150,100,200,25,1); setfillstyle(SOLID_FILL,RED); bar3d(150,150,250,200,25,1); setfillstyle(LINE_FILL,BLUE); bar3d(300,150,400,200,25,1); setfillstyle(LTSLASH_FILL,GREEN); bar3d(450,150,550,200,25,1); setfillstyle(SLASH_FILL,CYAN); bar3d(2,250,100,300,25,1); setfillstyle(BKSLASH_FILL,BROWN); bar3d(150,250,250,300,25,1); setfillstyle(LTBKSLASH_FILL,MAGENTA); bar3d(300,250,400,300,25,1); setfillstyle(HATCH_FILL,LIGHTRED); bar3d(450,250,550,300,25,1); setfillstyle(XHATCH_FILL,DARKGRAY); bar3d(2,350,100,400,25,1); setfillstyle(INTERLEAVE_FILL,YELLOW); bar3d(150,350,250,400,25,1); setfillstyle(WIDE_DOT_FILL,LIGHTMAGENTA); bar3d(300,350,400,400,25,1); setfillstyle(CLOSE_DOT_FILL,LIGHTGRAY); bar3d(450,350,550,400,25,1); getch(); closegraph(); }
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 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
/* copy an image from the screen to memory by getimage() function code example */ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> #include <alloc.h> void save_screen(void *buf[4]); void restore_screen(void *buf[4]); int maxx, maxy; int main(void) { int gdriver=DETECT, gmode, errorcode; void *ptr[4]; /* autodetect the graphics driver and mode */ initgraph(&gdriver, &gmode, ""); errorcode = graphresult(); /* check for any errors */ if (errorcode != grOk) { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); } maxx = getmaxx(); maxy = getmaxy(); /* draw an image on the screen */ rectangle(0, 0, maxx, maxy); line(0, 0, maxx, maxy); line(0, maxy, maxx, 0); save_screen(ptr); /* save the current screen */ getch(); /* pause screen */ cleardevice(); /* clear screen */ restore_screen(ptr); /* restore the screen */ getch(); /* pause screen */ closegraph(); return 0; } void save_screen(void *buf[4]) { unsigned size; int ystart=0, yend, yincr, block; yincr = (maxy+1) / 4; yend = yincr; /* get byte size of image */ size = imagesize(0, ystart, maxx, yend); for (block=0; block<=3; block++) { if ((buf[block] = farmalloc(size)) == NULL) { closegraph(); printf("Error: not enough heap space in save_screen().\n"); exit(1); } getimage(0, ystart, maxx, yend, buf[block]); ystart = yend + 1; yend += yincr + 1; } } void restore_screen(void *buf[4]) { int ystart=0, yend, yincr, block; yincr = (maxy+1) / 4; yend = yincr; for (block=0; block<=3; block++) { putimage(0, ystart, buf[block], COPY_PUT); farfree(buf[block]); ystart = yend + 1; yend += yincr + 1; } }
nosound() Function in C
The nosound() function in C language is used to stop the sound played by sound() function. nosound() function is simply silent the system. Sound function produces the sound of a specified frequency and nosound function turn off the PC speaker.
Syntax for nosound() Function in C
#include <dos.h> void nosound();
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
/* silent the system by nosound() function 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 for producing //the sound of frequency 250. sound(250); //function to delay the sound for //half of second. delay(500); //calling the function to stop the //system sound. nosound(); 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 constant-expression : statement(s); break; /* optional */ case constant-expression : statement(s); break; /* optional */ /* you can have any number of case statements */ default : /* Optional */ statement(s); }
• The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type. • You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon. • The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal. • When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached. • When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement. • Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached. • A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.
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
/* switch case statement in C language*/ // Program to create a simple calculator #include <stdio.h> int main() { char operation; double n1, n2; printf("Enter an operator (+, -, *, /): "); scanf("%c", &operation); printf("Enter two operands: "); scanf("%lf %lf",&n1, &n2); switch(operation) { case '+': printf("%.1lf + %.1lf = %.1lf",n1, n2, n1+n2); break; case '-': printf("%.1lf - %.1lf = %.1lf",n1, n2, n1-n2); break; case '*': printf("%.1lf * %.1lf = %.1lf",n1, n2, n1*n2); break; case '/': printf("%.1lf / %.1lf = %.1lf",n1, n2, n1/n2); break; // operator doesn't match any case constant +, -, *, / default: printf("Error! operator is not correct"); } return 0; }


C Program code Find out the prime numbers between 1 to 100, 100 to 999... Input a range, for e.g. if you want the Prime Numbers from 100 to 999 then enter numbers 100 and 999...
C Program code to demonstrate nested printf statements. String will be first printed while executing inner printf. Length of the string "abcdefghijklmnopqrstuvwxyz". So printf will
Take a decimal number as input. Check if the number is greater than 1000 or 900 or 500 or 400 or 100 or 90 or 50 or 40 or 10 or 9 or 5 or 4 or 1. If it is, then store its equivalent roman...
C Language program code to using recursion finds a binary equivalent of a decimal number entered by the user. The user has to enter a decimal which has a base 10 and the program
When we pass the address of an array while calling a function then this is called function call by reference. When we pass an address as an argument, the function declaration...
C program to read elements in a matrix and check whether the matrix is upper triangular matrix or not. Check upper triangular matrix. To check whether a matrix is upper triangular
Program input a number from user and count total number of ones (1s) and zeros (0s) in the given number using bitwise operator. How to count zeros and ones in binary number using