Happy Codings - Programming Code Examples

C Programming Code Examples

C > Games and Graphics Code Examples

Prog to implement a boolean function using a multiplexer logic

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 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
/* Prog to implement a boolean function using a multiplexer logic */ #include<dos.h> #include<math.h> #include<stdio.h> #include<conio.h> #include<stdlib.h> #include<graphics.h> #define N 500 int function[35]; int strobe[5] = { 0,0,0,0,0 }; int store[16] = { 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2 }; int inputs[16]; int output=0,count=0,decieq,choice; int driver=DETECT,mode; /*functions for begining gui*/ struct stars { int x,y,x1,y1,z,c; }STARS[N]; void init() { int i,t; for(i=0;i<N;i++) { STARS[i].c=2; STARS[i].x = random(640); STARS[i].y = random(460); STARS[i].x1= random(320); STARS[i].y1= random(220); t=random(325); if(t==0) STARS[i].z=t+random(25)+1;//TO AVOID ERROR(division by 0) else STARS[i].z=t; } } void draw() { int i; for(i=0;i<N;i++) { if(STARS[i].y<480) putpixel(STARS[i].x,STARS[i].y,STARS[i].c); } } void erase() { int i; for(i=0;i<N;i++) putpixel(STARS[i].x,STARS[i].y,0); //putting black //color at stars position } /* if you use z+=2 stars will go away from you , but remember to change the condition :- if(STARS[i].z<1) {STARS[i].z=325;} to if(STARS[i].z>325) {STARS[i].z=1;} */ void move() { int i; for(i=0;i<N;i++) { STARS[i].x=((STARS[i].x1 * 640)/STARS[i].z)+320;//320 x-origin STARS[i].y=((STARS[i].y1 * 300)/STARS[i].z) +220;//220 y-origin STARS[i].z-=2; if(STARS[i].z<1) STARS[i].z=325; else if(STARS[i].z<162) STARS[i].c=15; else STARS[i].c=7; } } void showstars() { int i; init(); while(!kbhit()) { setcolor(3); //3 for cyan settextstyle(1,0,3); outtextxy(230,5,"PROJECT ON"); settextstyle(10,0,3); setcolor(i); outtextxy(170,30,"MULTIPLEXERS"); setcolor(5); settextstyle(1,0,3); move(); draw(); delay(15); erase(); i++; } closegraph(); restorecrtmode(); } void welcome() { int i, j, x, y, color; int MaxColors; struct palettetype palette; struct viewporttype vp; int height, width; initgraph(&driver,&mode,"f:\tc\bgi"); MaxColors = getmaxcolor() + 1; textcolor(4+BLINK); printf(" WELCOME"); textcolor(15); getpalette( &palette ); setviewport(0,50,630,470,1); getviewsettings( &vp ); width = (vp.right - vp.left) / 15; //width height = (vp.bottom - vp.top) / 10; // height x = y = 0; // Start in upper corner color = 1; // Begin at 1st color for( j=0 ; j<10 ; ++j ) { // 10 rows of boxes for( i=0 ; i<15 ; ++i ) { // 15 columns setfillstyle( SOLID_FILL, color++ );//Set the color bar( x, y, x+width, y+height ); // Draw the box x += width + 1; // Advance to next col color = 1 + (color % (MaxColors - 2));// Set new color } // End of i loop x = 0; // Goto 1st column y += height + 1; // Goto next row } // End of j loop while( !kbhit() ) // Until a key is hit setpalette( 1+random(MaxColors - 2), random( 65 ) ); setallpalette( &palette ); getch(); closegraph(); restorecrtmode(); initgraph(&driver,&mode,"f:\tc\bgi"); showstars(); } /*begining gui ends.text mode begins*/ /*multiplexer functions*/ void message(int num) //gives a message to user { //everytime select input is entered printf(" Only first %d select inputs considered.rest rejected(if any) ",num); } int check(int num) //For checking that a particular no. { //is present in function or not int ctr2; for(ctr2=0;ctr2<count;ctr2++) if(function[ctr2]==num) return (1); //true return(0); //false } void check_invalid_strobe(int ctr2) //for checking invalid select input { if(strobe[ctr2]>1 || strobe[ctr2]<0) { printf(" Invalid select input"); exit(2); } } void decide_output(int count) //decides whether output is 1 or 0 { //for normal mux implementation int ctr2; for(ctr2=0;ctr2<count;ctr2++) { if(decieq==function[ctr2]) { output = 1; break; } } } void decide_complex_inputs(int num) //decides inputs of a Mux which { //implements a function of a higher //level Mux int ctr2; for(ctr2=0;ctr2<num;ctr2++) { if(check(ctr2)) { if(check(ctr2+num)) inputs[ctr2]=1; else { inputs[ctr2]=!(strobe[0]); store[ctr2] = 0; } } else { if(check(ctr2+num)) { inputs[ctr2]=strobe[0]; store[ctr2] = 1; } else inputs[ctr2]=0; } } } void display_complex_input(int num) //displays inputs of a Mux which { //implements a function of a higher //level Mux int i; for(i=0;i<num;i++) { if(store[i]==0) printf(" Input %d = %s(%d)",i,"a bar",inputs[i]); else if(store[i]==1) printf(" Input %d = %c(%d)",i,'a',inputs[i]); else printf(" Input %d = %d",i,inputs[i]); } } void take_input(int num) //for taking select input in normal Mux { int ctr2; printf(" Enter the select input: "); for(ctr2=0;ctr2<num;ctr2++) { scanf("%d",&strobe[ctr2]); check_invalid_strobe(ctr2); } } void take_input_a(int num) //for taking input a in case of complex { //implementation of a function printf(" Enter the value of a(MSB of select input for %d:1) : ",num); scanf("%d",&strobe[0]); check_invalid_strobe(0); printf(" Only one value of MSB considered.rest rejected(if any) "); } void take_complex_select_input(int num) { int ctr2; printf(" Enter the select input: "); for(ctr2=1;ctr2<num;ctr2++) { scanf("%d",&strobe[ctr2]); check_invalid_strobe(ctr2); } printf(" Only first %d select inputs considered.rest rejected(if any)",num-1); printf(" Press any key to continue...."); getch(); } void display_output() { printf(" Output is : %d",output); printf(" Input %d is selected as output.",decieq); printf(" Press any key to continue....."); getch(); } void display_complex_output() { output = inputs[decieq]; printf(" Output is: %d",output); printf(" Input %d is selected as output.",decieq); printf(" Press any key to continue...."); getch(); } void two_is_to_one() { take_input(1); message(1); decieq = strobe[0]*1; decide_output(count); display_output(); } void four_is_to_one() { int ctr2; take_input(2); message(2); decieq = strobe[0]*2 + strobe[1]*1; decide_output(count); display_output(); } void eight_is_to_one() { int ctr2; take_input(3); message(3); decieq = strobe[0]*4 + strobe[1]*2 + strobe[2]*1; decide_output(count); display_output(); } void sixteen_is_to_one() { int ctr2; take_input(4); message(4); decieq = strobe[0]*8 + strobe[1]*4 + strobe[2]*2 + strobe[3]*1; decide_output(count); display_output(); } void thirtytwo_is_to_one() { int ctr2; take_input(5); message(5); decieq = strobe[0]*16 + strobe[1]*8 + strobe[2]*4 + strobe[3]*2 + strobe[4]*1; decide_output(count); display_output(); } void complex_two_is_to_one() { int ctr2; take_input_a(4); take_complex_select_input(2); message(1); decide_complex_inputs(2); decieq = strobe[1]*1; clrscr(); display_complex_input(2); display_complex_output(); } void complex_four_is_to_one() { int ctr2; take_input_a(8); take_complex_select_input(3); message(2); decide_complex_inputs(4); decieq = strobe[1]*2 + strobe[2]*1; clrscr(); display_complex_input(4); display_complex_output(); } void complex_eight_is_to_one() { int ctr2; take_input_a(16); take_complex_select_input(4); message(3); decide_complex_inputs(8); decieq = strobe[1]*4 + strobe[2]*2 + strobe[3]*1; clrscr(); display_complex_input(8); display_complex_output(); } void complex_sixteen_is_to_one() { int ctr2; take_input_a(32); take_complex_select_input(5); message(4); decide_complex_inputs(16); decieq = strobe[1]*8 + strobe[2]*4 + strobe[3]*2 + strobe[4]*1; clrscr(); display_complex_input(16); display_complex_output(); } /*multiplexing functions end*/ /*circuit gui*/ void common_gui(int num) { int y[32],i,i2,k; double j=log(num)/log(2); char str[2]; int stepsize=((280+num*3)-180)/(j+1); for(i=0;i<32;i++) y[i]=80 + (i+1)*10; initgraph(&driver,&mode,"f:\tc\bgi"); outtextxy(20,5,"RED: logic level 1"); outtextxy(250,5,"Press any key to continue....."); outtextxy(20,15,"GREEN:logic level 0"); for(i=0;i<num;i++) { if(check(i)) { setcolor(WHITE); circle(150,y[i],2); setfillstyle(SOLID_FILL,RED); floodfill(150,y[i],WHITE); } else { setcolor(15); circle(150,y[i],2); setfillstyle(SOLID_FILL,GREEN); floodfill(150,y[i],WHITE); } line(154,y[i],180,y[i]); } rectangle(180,40,280+num*3,y[i-1]+40); line(280+num*3,(y[i-1]-40)/2 + 60,280+3*num+40,(y[i-1]-40)/2 + 60); if(output==1) { setcolor(15); circle(280+num*3+44,(y[i-1]-40)/2 + 60,4); setfillstyle(SOLID_FILL,RED); floodfill(280+num*3+44,(y[i-1]-40)/2 + 60,WHITE); } else { setcolor(15); circle(280+num*3+44,(y[i-1]-40)/2 + 60,4); setfillstyle(SOLID_FILL,GREEN); floodfill(280+num*3+44,(y[i-1]-40)/2 +60,WHITE); } outtextxy(280+num*3+50,(y[i-1]-40)/2 + 60," Y(Output = )"); itoa(output,str,10); outtextxy(280+num*3+150,(y[i-1]-40)/2 + 60,str); itoa(num,str,10); outtextxy(140,y[i-1]+72," Block Diagram of "); outtextxy(290,y[i-1]+72,str); outtextxy(293,y[i-1]+72," : 1 Mux"); outtextxy((280+num*3-180)/2 + 150,y[(i-1)/2],str); outtextxy((280+num*3-180)/2 + 160,y[(i-1)/2]," : 1"); outtextxy((280+num*3-180)/2 + 150,y[(i-1)/2+2]," MUX"); outtextxy(280+num*3+170,(y[i-1]-40)/2 + 60,"(I "); itoa(decieq,str,10); outtextxy(280+num*3+185,(y[i-1]-40)/2 + 60,str); outtextxy(280+num*3+192,(y[i-1]-40)/2 + 60," )"); outtextxy(130,y[0]-5,"I0"); itoa(num-1,str,10); outtextxy(126,y[i-1],"I"); outtextxy(133,y[i-1],str); for(i2=0;i2<j;i2++) for(k=0;k<20;k++) { line(180+(i2+1)*stepsize,y[i-1]+40,180+(i2+1)*stepsize,y[i-1]+60); if(strobe[i2]==0) { setcolor(15); circle(180+(i2+1)*stepsize,y[i-1]+62,2); setfillstyle(SOLID_FILL,2); floodfill(180+(i2+1)*stepsize,y[i-1]+62,15); } else { setcolor(15); circle(180+(i2+1)*stepsize,y[i-1]+62,2); setfillstyle(SOLID_FILL,4); floodfill(180+(i2+1)*stepsize,y[i-1]+62,15); } } outtextxy(185+(i2)*stepsize,y[i-1]+62,"S0"); itoa(j-1,str,10); outtextxy(162+stepsize,y[i-1]+62,"S "); outtextxy(170+stepsize,y[i-1]+62,str); if(num==2) { setcolor(0); outtextxy(162+stepsize,y[i-1]+62,"S0"); setcolor(15); } getch(); } void common_complex_gui(int num) { int y[32],i,i2,k; double j=log(num)/log(2); char str[2]; int stepsize=((280+num*3)-180)/(j+1); for(i=0;i<32;i++) y[i]=80 + (i+1)*10; initgraph(&driver,&mode,"f:\tc\bgi"); outtextxy(20,5,"RED: logic level 1"); outtextxy(250,5,"Press anu key to continue....."); outtextxy(20,15,"GREEN:logic level zero"); for(i=0;i<num;i++) { if(inputs[i]==1) { setcolor(WHITE); circle(150,y[i],2); setfillstyle(SOLID_FILL,RED); floodfill(150,y[i],WHITE); } else { setcolor(15); circle(150,y[i],2); setfillstyle(SOLID_FILL,GREEN); floodfill(150,y[i],WHITE); } line(154,y[i],180,y[i]); } rectangle(180,40,280+num*3,y[i-1]+40); line(280+num*3,(y[i-1]-40)/2 + 60,280+3*num+40,(y[i-1]-40)/2 + 60); if(output==1) { setcolor(15); circle(280+num*3+44,(y[i-1]-40)/2 + 60,4); setfillstyle(SOLID_FILL,RED); floodfill(280+num*3+44,(y[i-1]-40)/2 + 60,WHITE); } else { setcolor(15); circle(280+num*3+44,(y[i-1]-40)/2 + 60,4); setfillstyle(SOLID_FILL,GREEN); floodfill(280+num*3+44,(y[i-1]-40)/2 +60,WHITE); } outtextxy(280+num*3+50,(y[i-1]-40)/2 + 60," Y(Output = )"); itoa(output,str,10); outtextxy(280+num*3+150,(y[i-1]-40)/2 + 60,str); itoa(num,str,10); outtextxy(140,y[i-1]+72," Block Diagram of "); outtextxy(290,y[i-1]+72,str); outtextxy(293,y[i-1]+72," : 1 Mux"); outtextxy((280+num*3-180)/2 + 150,y[(i-1)/2],str); outtextxy((280+num*3-180)/2 + 160,y[(i-1)/2]," : 1"); outtextxy((280+num*3-180)/2 + 150,y[(i-1)/2+2]," MUX"); outtextxy(280+num*3+170,(y[i-1]-40)/2 + 60,"(I "); itoa(decieq,str,10); outtextxy(280+num*3+185,(y[i-1]-40)/2 + 60,str); outtextxy(280+num*3+192,(y[i-1]-40)/2 + 60," )"); outtextxy(130,y[0]-5,"I0"); itoa(num-1,str,10); outtextxy(126,y[i-1],"I"); outtextxy(133,y[i-1],str); for(i2=1;i2<=j;i2++) for(k=0;k<20;k++) { line(180+(i2)*stepsize,y[i-1]+40,180+(i2)*stepsize,y[i-1]+60); if(strobe[i2]==0) { setcolor(15); circle(180+(i2)*stepsize,y[i-1]+62,2); setfillstyle(SOLID_FILL,2); floodfill(180+(i2)*stepsize,y[i-1]+62,15); } else { setcolor(15); circle(180+(i2)*stepsize,y[i-1]+62,2); setfillstyle(SOLID_FILL,4); floodfill(180+(i2)*stepsize,y[i-1]+62,15); } } outtextxy(185+(i2-1)*stepsize,y[i-1]+62,"S0"); itoa(j-1,str,10); outtextxy(162+stepsize,y[i-1]+62,"S "); outtextxy(170+stepsize,y[i-1]+62,str); if(num==2) { setcolor(0); outtextxy(162+stepsize,y[i-1]+62,"S0"); setcolor(15); } getch(); } /*circuit gui ends*/ /*main function*/ void main() { int ctr=0; welcome(); clrscr(); printf(" Prog to implement a function using a multiplexer logic:-"); printf(" Enter the function in minterms only."); printf(" Enter the function in form a b c d where a<b<c<d."); printf(" Press enter or provide spaces after each input."); printf(" Any value in input function cannot be repeated."); printf(" Enter the select input in form of 1's & 0's."); printf(" All the entered inputs are assumed to be high."); printf(" Maximun value of the minterm that can be accepted :31 "); textcolor(4+BLINK); textbackground(3); cprintf("Press any key to continue......."); textcolor(15); textbackground(0); getch(); printf(" How many input will you provide: "); scanf("%d",&count); if(count>32) { printf(" Invalid function input.inputs can't be greater than 32"); exit(1); } clrscr(); printf("Enter the function to be implemented : "); for(ctr=0;ctr<count;ctr++) { scanf("%d",&function[ctr]); if(function[ctr]>31) { printf(" Invalid function input"); exit(1); } } printf(" Only first %d inputs considered.rest rejected(if any)",count); fflush(stdin); if(function[count-1] <= 1) { two_is_to_one(); common_gui(2); } else if(function[count-1] <= 3) { label1: printf(" Implement using:- 1.)4:1 Mux 2.)2:1 Mux Enter your choice?"); scanf("%d",&choice); switch(choice) { case 1: four_is_to_one(); common_gui(4); break; case 2: complex_two_is_to_one(); common_complex_gui(2); break; default : printf(" Invalid choice"); goto label1; } } else if(function[count-1] <= 7) { label2: printf(" Implement using:- 1.)8:1 Mux 2.)4:1 Mux Enter your choice?"); scanf("%d",&choice); switch(choice) { case 1: eight_is_to_one(); common_gui(8); break; case 2: complex_four_is_to_one(); common_complex_gui(4); break; default : printf(" Invalid choice"); goto label2; } } else if(function[count-1] <= 15) { label3: printf(" Implement using:- 1.)16:1 Mux 2.)8:1 Mux Enter your choice?"); scanf("%d",&choice); switch(choice) { case 1: sixteen_is_to_one(); common_gui(16); break; case 2: complex_eight_is_to_one(); common_complex_gui(8); break; default : printf(" Invalid choice"); goto label3; } } else if(function[count-1] <= 31) { label4: printf(" Implement using:- 1.)32:1 Mux 2.)16:1 Mux Enter your choice?"); scanf("%d",&choice); switch(choice) { case 1: thirtytwo_is_to_one(); common_gui(32); break; case 2: complex_sixteen_is_to_one(); common_complex_gui(16); break; default : printf(" Invalid choice"); goto label4; } } getch(); }
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; }
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; }
#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; }
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; }
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; }
main() Function in C
In C, the "main" function is treated the same as every function, it has a return type (and in some cases accepts inputs via parameters). The only difference is that the main function is "called" by the operating system when the user runs the program. Thus the main function is always the first code executed when a program starts. main() function is a user defined, body of the function is defined by the programmer or we can say main() is programmer/user implemented function, whose prototype is predefined in the compiler. Hence we can say that main() in c programming is user defined as well as predefined because it's prototype is predefined. main() is a system (compiler) declared function whose defined by the user, which is invoked automatically by the operating system when program is being executed. Its first function or entry point of the program from where program start executed, program's execution starts from the main. So main is an important function in c , c++ programming language.
Syntax for main() Function in C
void main() { ......... // codes start from here ......... }
void
is a keyword in C language, void means nothing, whenever we use void as a function return type then that function nothing return. here main() function no return any value. In place of void we can also use int return type of main() function, at that time main() return integer type value.
main
is a name of function which is predefined function in C library. • An operating system always calls the main() function when a programmers or users execute their programming code. • It is responsible for starting and ends of the program. • It is a universally accepted keyword in programming language and cannot change its meaning and name. • A main() function is a user-defined function in C that means we can pass parameters to the main() function according to the requirement of a program. • A main() function is used to invoke the programming code at the run time, not at the compile time of a program. • A main() function is followed by opening and closing parenthesis brackets.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* basic c program by main() function example */ #include <stdio.h> #include <conio.h> main() { printf (" It is a main() function "); int fun2(); // jump to void fun1() function printf ("\n Finally exit from the main() function. "); } void fun1() { printf (" It is a second function. "); printf (" Exit from the void fun1() function. "); } int fun2() { void fun1(); // jump to the int fun1() function printf (" It is a third function. "); printf (" Exit from the int fun2() function. "); 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(); }
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; }
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; }
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(); }
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; }
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; }
#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; }
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; }
Functions in C Language
A function is a group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions. You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division is such that each function performs a specific task. A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function. The C standard library provides numerous built-in functions that your program can call. For example, strcat() to concatenate two strings, memcpy() to copy one memory location to another location, and many more functions. A function can also be referred as a method or a sub-routine or a procedure, etc.
Defining a Function
The general form of a function definition in C programming language is as follows:
return_type function_name( parameter list ) { body of the function }
A function definition in C programming consists of a function header and a function body. Here are all the parts of a function:
Return Type
A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.
Function Name
This is the actual name of the function. The function name and the parameter list together constitute the function signature.
Parameters
A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.
Function Body
The function body contains a collection of statements that define what the function does. Given below is the source code for a function called max(). This function takes two parameters num1 and num2 and returns the maximum value between the two:
/* function returning the max between two numbers */ int max(int num1, int num2) { /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; return result; }
Function Declarations
A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately. A function declaration has the following parts:
return_type function_name( parameter list );
For the above defined function max(), the function declaration is as follows:
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required, so the following is also a valid declaration:
int max(int, int);
Function declaration is required when you define a function in one source file and you call that function in another file. In such case, you should declare the function at the top of the file calling the function.
Calling a Function
While creating a C function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task. When a program calls a function, the program control is transferred to the called function. A called function performs a defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns the program control back to the main program. To call a function, you simply need to pass the required parameters along with the function name, and if the function returns a value, then you can store the returned value.
Function Arguments
If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function. Formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit. While calling a function, there are two ways in which arguments can be passed to a function: Call by value: This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. Call by reference: This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument. There are the following advantages of C functions. • By using functions, we can avoid rewriting same logic/code again and again in a program. • We can call C functions any number of times in a program and from any place in a program. • We can track a large C program easily when it is divided into multiple functions. • Reusability is the main achievement of C functions. • However, Function calling is always a overhead in a C program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
/* creating a user defined function addition() */ #include <stdio.h> int addition(int num1, int num2) { int sum; /* Arguments are used here*/ sum = num1+num2; /* Function return type is integer so we are returning * an integer value, the sum of the passed numbers. */ return sum; } int main() { int var1, var2; printf("Enter number 1: "); scanf("%d",&var1); printf("Enter number 2: "); scanf("%d",&var2); /* Calling the function here, the function return type * is integer so we need an integer variable to hold the * returned value of this function. */ int res = addition(var1, var2); printf ("Output: %d", res); return 0; }
scanf() Function in C
Read formatted data from stdin. Reads data from stdin and stores them according to the parameter format into the locations pointed by the additional arguments. The additional arguments should point to already allocated objects of the type specified by their corresponding format specifier within the format string. In C programming, scanf() is one of the commonly used function to take input from the user. The scanf() function reads formatted input from the standard input such as keyboards. The scanf() function enables the programmer to accept formatted inputs to the application or production code. Moreover, by using this function, the users can provide dynamic input values to the application.
Syntax for scanf() Function in C
#include <stdio.h> int scanf ( const char * format, ... );
format
C string that contains a sequence of characters that control how characters extracted from the stream are treated: • Whitespace character: the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none). • Non-whitespace character, except format specifier (%): Any character that is not either a whitespace character (blank, newline or tab) or part of a format specifier (which begin with a % character) causes the function to read the next character from the stream, compare it to this non-whitespace character and if it matches, it is discarded and the function continues with the next character of format. If the character does not match, the function fails, returning and leaving subsequent characters of the stream unread. • Format specifiers: A sequence formed by an initial percentage sign (%) indicates a format specifier, which is used to specify the type and format of the data to be retrieved from the stream and stored into the locations pointed by the additional arguments. A format specifier for scanf follows this prototype: %[*][width][length]specifier
specifier
Where the specifier character at the end is the most significant component, since it defines which characters are extracted, their interpretation and the type of its corresponding argument:
i – integer
Any number of digits, optionally preceded by a sign (+ or -). Decimal digits assumed by default (0-9), but a 0 prefix introduces octal digits (0-7), and 0x hexadecimal digits (0-f). Signed argument.
d or u – decimal integer
Any number of decimal digits (0-9), optionally preceded by a sign (+ or -). d is for a signed argument, and u for an unsigned.
o – octal integer
Any number of octal digits (0-7), optionally preceded by a sign (+ or -). Unsigned argument.
x – hexadecimal integer
Any number of hexadecimal digits (0-9, a-f, A-F), optionally preceded by 0x or 0X, and all optionally preceded by a sign (+ or -). Unsigned argument.
f, e, g – floating point number
A series of decimal digits, optionally containing a decimal point, optionally preceeded by a sign (+ or -) and optionally followed by the e or E character and a decimal integer (or some of the other sequences supported by strtod). Implementations complying with C99 also support hexadecimal floating-point format when preceded by 0x or 0X.
c – character
The next character. If a width other than 1 is specified, the function reads exactly width characters and stores them in the successive locations of the array passed as argument. No null character is appended at the end.
s – string of characters
Any number of non-whitespace characters, stopping at the first whitespace character found. A terminating null character is automatically added at the end of the stored sequence.
p – pointer address
A sequence of characters representing a pointer. The particular format used depends on the system and library implementation, but it is the same as the one used to format %p in fprintf.
[characters] – scanset
Any number of the characters specified between the brackets. A dash (-) that is not the first character may produce non-portable behavior in some library implementations.
[^characters] – negated scanset
Any number of characters none of them specified as characters between the brackets.
n – count
No input is consumed. The number of characters read so far from stdin is stored in the pointed location.
%
A % followed by another % matches a single %. Except for n, at least one character shall be consumed by any specifier. Otherwise the match fails, and the scan ends there.
sub-specifier
The format specifier can also contain sub-specifiers: asterisk (*), width and length (in that order), which are optional and follow these specifications:
*
An optional starting asterisk indicates that the data is to be read from the stream but ignored (i.e. it is not stored in the location pointed by an argument).
width
Specifies the maximum number of characters to be read in the current reading operation (optional).
length
One of hh, h, l, ll, j, z, t, L (optional). This alters the expected type of the storage pointed by the corresponding argument (see below).
... (additional arguments)
Depending on the format string, the function may expect a sequence of additional arguments, each containing a pointer to allocated storage where the interpretation of the extracted characters is stored with the appropriate type. There should be at least as many of these arguments as the number of values stored by the format specifiers. Additional arguments are ignored by the function. These arguments are expected to be pointers: to store the result of a scanf operation on a regular variable, its name should be preceded by the reference operator (&) (see example). On success, the function returns the number of items of the argument list successfully filled. This count can match the expected number of items or be less (even zero) due to a matching failure, a reading error, or the reach of the end-of-file. If a reading error happens or the end-of-file is reached while reading, the proper indicator is set (feof or ferror). And, if either happens before any data could be successfully read, EOF is returned. If an encoding error happens interpreting wide characters, the function sets errno to EILSEQ.
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
/* read formatted data from stdin by scanf() function example */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, const char * argv[]) { /* Define temporary variables */ char name[10]; int age; int result; /* Ask the user to enter their first name and age */ printf("Please enter your first name and your age.\n"); /* Read a name and age from the user */ result = scanf("%s %d",name, &age); /* We were not able to parse the two required values */ if (result < 2) { /* Display an error and exit */ printf("Either name or age was not entered\n\n"); exit(0); } /* Display the values the user entered */ printf("Name: %s\n", name); printf("Age: %d\n", age); return 0; }
round() Function in C
Round to nearest. Returns the integral value that is nearest to x, with halfway cases rounded away from zero. Rounds a floating-point number to an integer value. The round() functions round a floating-point number to the nearest integer value, regardless of the current rounding direction setting in the floating-point environment. If the argument is exactly halfway between two integers, round() rounds it away from 0. The return value is the rounded integer value.
Syntax for round() Function in C
#include <math.h> double round (double x); float roundf (float x); long double roundl (long double x);
x
a floating point value for find round value. Function returns the value of x rounded to the nearest integral (as a floating-point value). In the C Programming Language, the required header file for the round() function is math.h.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/* return the nearest integer value of the float/double/argument by round() math function code example */ #include <stdio.h> #include <math.h> int main() { //Define temporary variable float i=5.2,j=6.8; //calculate and display round value printf("round value of %f is: %f\n",i,round(i)); printf("round value of %f is: %f\n",j,round(j)); i=4.9, j=-3.8; //calculate and display round value printf("round value of %f is: %f\n",i,round(i)); printf("round value of %f is: %f\n",j,round(j)); return 0; }
textcolor() Function in C
Use the textcolor function to define what color you want to use for text. You can use this function to vary the text colors of your output. Colors must be written in all caps, or expressed as a numeral.
Syntax for textcolor() Function in C
#include <conio.h> void textcolor(int color);
color
an integer variable or a string (color name) • 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 To use this function conio.h file must be included 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 26 27 28 29 30
/* change the color of drawing text by textcolor() function example */ #include <stdio.h> //to use 'textbackground' #include <conio.h> int main() { // setting the color of background textbackground(GREEN); textcolor(MAGENTA+BLINK); // message cprintf("Change the color to MAGENTA"); textcolor(RED); // message cprintf("Change the color to RED"); // setting the color of background textbackground(RED); // message cprintf("Change the background color to RED"); getch(); 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; }
itoa() Function in C
Convert integer to string (non-standard function). Converts an integer value to a null-terminated string using the specified base and stores the result in the array given by str parameter. If base is 10 and value is negative, the resulting string is preceded with a minus sign (-). With any other base, value is always considered unsigned. str should be an array long enough to contain any possible value: (sizeof(int)*8+1) for radix=2, i.e. 17 bytes in 16-bits platforms and 33 in 32-bits platforms.
Syntax for itoa() Function in C
#include <stdlib.h> char * itoa ( int value, char * str, int base );
value
Value to be converted to a string.
str
Array in memory where to store the resulting null-terminated string.
base
Numerical base used to represent the value as a string, between 2 and 36, where 10 means decimal base, 16 hexadecimal, 8 octal, and 2 binary. The itoa (integer to ASCII) function is a widespread non-standard extension to the standard C programming language. It cannot be portably used, as it is not defined in any of the C language standards; however, compilers often provide it through the header <stdlib.h> while in non-conforming mode, because it is a logical counterpart to the standard library function atoi. Function returns a pointer to the resulting null-terminated string, same as parameter str.
Portability
This function is not defined in ANSI-C and is not part of C++, but is supported by some compilers. A standard-compliant alternative for some cases may be sprintf: • sprintf(str,"%d",value) converts to decimal base. • sprintf(str,"%x",value) converts to hexadecimal base. • sprintf(str,"%o",value) converts to octal base.
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
/* convert integer to string (non-standard function) by itoa() function example */ #include <stdio.h> #include <math.h> #include <stdlib.h> char* itoa(int num, char* buffer, int base) { int current = 0; if (num == 0) { buffer[current++] = '0'; buffer[current] = '\0'; return buffer; } int num_digits = 0; if (num < 0) { if (base == 10) { num_digits ++; buffer[current] = '-'; current ++; num *= -1; } else return NULL; } num_digits += (int)floor(log(num) / log(base)) + 1; while (current < num_digits) { int base_val = (int) pow(base, num_digits-1-current); int num_val = num / base_val; char value = num_val + '0'; buffer[current] = value; current ++; num -= base_val * num_val; } buffer[current] = '\0'; return buffer; } int main() { int a = 123456; char buffer[256]; if (itoa(a, buffer, 10) != NULL) { printf("Input = %d, base = %d, Buffer = %s\n", a, 10, buffer); } int b = -2310; if (itoa(b, buffer, 10) != NULL) { printf("Input = %d, base = %d, Buffer = %s\n", b, 10, buffer); } int c = 10; if (itoa(c, buffer, 2) != NULL) { printf("Input = %d, base = %d, Buffer = %s\n", c, 2, buffer); } 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; }
cprintf() Function in C
Write output directly to the console. The cprintf() function writes output directly to the console under control of the argument format. The putch() function is used to output characters to the console. The format string is described under the description of the printf() function. cprintf takes multiple arguments, applies to each of the format specifier contained in the format string, pointed to by format, and prints the formatted data directly to the current text window on the screen. The number of available format must match the number of arguments.
Syntax for cprintf() Function in C
#include <conio.h> int cprintf( const char *format, ... );
The format string and arguments for cprintf() are the same as those for printf(). See the description of the printf() function for a detailed explanation of the format string and arguments. cprintf() returns the number of characters printed. Unlike fprintf(), printf(), and sprintf(), cprintf() does doesn't translate line-feed characters into carriage-return-line-feed pairs.
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
/* write output directly to the console by cprintf() function example */ int x; do { { clrscr(); design(); t(); textcolor(WHITE); gotoxy(24,3); cprintf("\xDB\xDB\xDB\xDB\xB2 LYDIA'S DEPARTMENT STORE \xB2\xDB\xDB\xDB\xDB"); gotoxy(3,4); cprintf("--------------------------------------------------------------------------"); gotoxy(35,5); cprintf("MAIN MENU"); gotoxy(26,8); cprintf(" 1 - INFORMATION ABOUT PRODUCTS "); gotoxy(26,9); cprintf(" 2 - ENTER PURCHASE RECORDS "); gotoxy(26,10); cprintf(" 3 - ENTER PRODUCTS TO BE SALE "); gotoxy(26,11); cprintf(" 4 - SEARCH FOR RECORD "); gotoxy(26,12); cprintf(" 5 - DELETE RECORD FROM STORE DATABASE "); gotoxy(26,13); cprintf(" 6 - VIEW SALES , PURCHASE & PROFIT REPORT "); gotoxy(26,14); cprintf(" 7 - PRINT RECORDS "); gotoxy(26,15); cprintf(" 8 - BAR GRAPH OF QUANTITY / PROFIT "); gotoxy(26,16); cprintf(" 9 - RETRIEVE INFORMATION "); gotoxy(26,17); cprintf(" H - HELP "); gotoxy(26,18); cprintf(" E - EXIT "); gotoxy(26,23); // cprintf("ENTER YOUR CHOICE :: "); gotoxy(47,23); x=toupper(getch()); } }
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; }
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; }
textbackground() Function in C
Function textbackground is used to change current background color in text mode. To use the textbackground() function all you need to do is before printing any text call this function with a parameter defining the color in capital letters. That will be enough to change the background color of the text.
Syntax for textbackground() Function in C
#include <conio.h> void textbackground(int color);
color
an integer variable or a string (color name) • 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 To use this function conio.h file must be included 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 26 27 28 29 30 31
/* change current background color in text mode by textbackground() function example. */ #include <stdio.h> //to use 'textbackground' #include <conio.h> int main() { // setting the color of background textbackground(GREEN); textcolor(MAGENTA+BLINK); // message cprintf("Change the background to GREEN"); textcolor(YELLOW); // message cprintf("Change the color to RED"); // setting the color of background textbackground(BLUE); // message cprintf("Change the background color to BLUE"); getch(); return 0; }
Math log() Function in C
Compute natural logarithm. Returns the natural logarithm of x. The natural logarithm is the base-e logarithm: the inverse of the natural exponential function (exp). For common (base-10) logarithms, see log10. Calculates the natural logarithm of a number. The log() functions calculate the natural logarithm of their argument. The natural logarithm-called "log" for short in English as well as in C-is the logarithm to base e, where e is Euler's number, 2.718281.... The natural log of a number x is defined only for positive values of x. If x is negative, a domain error occurs; if x is zero, a range error may occur (or not, depending on the implementation).
Syntax for log() Function in C
#include<math.h> double log (double x);
x
Value whose logarithm is calculated. If the argument is negative, a domain error occurs. The log() function takes a single argument and returns a value of type float. Function returns natural logarithm of x. If x is negative, it causes a domain error. If x is zero, it may cause a pole error (depending on the library implementation). It is defined in <math.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
/* compute natural logarithm by log() math function code example */ #include <stdio.h> #include <math.h> int main(int argc, const char * argv[]) { /* Define temporary variables */ double value; double result; /* Assign the value we will calculate the log of */ value = 1.5; /* Calculate the log of the value */ result = log(value); /* Display the result of the calculation */ printf("The Natural Logarithm of %f is %f\n", value, result); return 0; }
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; }
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" ); } }
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; }
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; }
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; }
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; }
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; }
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 ); }
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); } } }
clrscr() Function in C
Function clrscr() clears the screen and moves the cursor to the upper left-hand corner of the screen. If you are using the GCC compiler, use system function to execute the clear/cls command. clrscr() function is also a non-standard function defined in "conio.h" header. This function is used to clear the console screen. It is often used at the beginning of the program (mostly after variable declaration but not necessarily) so that the console is clear for our output.
Syntax to Clear the Console in C
#include<conio.h> clrscr(); OR system("cls"); OR system("clear");
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* clear the screen and moves the cursor to the upper left-hand corner of the screen by clrscr() function example. */ #include <stdio.h> // clrscr() function definition void clrscr(void) { system("clear"); } int main() { clrscr(); //clear output screen printf("Hello World!!!"); //print message 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; }
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); }
putpixel() Function in C
putpixel() plots a point in the color defined by color at (x,y). The header file graphics.h contains putpixel() function which plots a pixel at location (x, y) of specified color. Where, (x, y) is the location at which pixel is to be put, and color specifies the color of the pixel.
Syntax for putpixel() Function in C
#include <graphics.h> void putpixel(int x, int y, int color);
x
X coordinate of the point
y
Y coordinate of the point
color
specifies the color of the pixel To put a pixel on the screen at a particular position, calling the pixel() function is a good way. This function takes three parameters as the position of the pixel and also the color of the pixel. To use these function in your program, we would need to include graphics.h file in your program. You should also use getch() function to make the screen freeze.
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
/* plot a pixel at location (x, y) of specified color by putpixel() 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; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, ""); // putpixel function putpixel(85, 35, GREEN); putpixel(30, 40, RED); putpixel(115, 50, YELLOW); putpixel(135, 50, CYAN); putpixel(45, 60, BLUE); putpixel(20, 100, WHITE); putpixel(200, 100, LIGHTBLUE); putpixel(150, 100, LIGHTGREEN); putpixel(200, 50, YELLOW); putpixel(120, 70, RED); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); 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 just print array in reversed order. It does not reverses the array. Here I am writing the first basic logic to reverse an array. It uses above approach to access array element in...
We have declared one pointer variable and one array. Address of first element of array is stored inside pointer variable. Accept Size of an Array. Now we have accepted element...