0% found this document useful (0 votes)
2K views

Effective Explanation of C Programming Language

Basic c programming in detail effective explanation

Uploaded by

Khalandar Noor
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
2K views

Effective Explanation of C Programming Language

Basic c programming in detail effective explanation

Uploaded by

Khalandar Noor
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 292
C Programs with Solutions C Programs with Solutions By S. ANANDAMURUGAN ME., (Ph.D)., MISTE., MACEEE., Senior Lecturer, Department of Computer Science & Engineering, Kongu Engineering College, Perundurai TamilNadu UNIVERSITY SCIENCE PRESS (An Imprint of Laxmi Publications Pvt, Ltd.) BANGALORE + CHENNAI + COCHIN + GUWAHATI + HYDERABAD JALANDHAR + KOLKATA + LUCKNOW + MUMBAI + PATNA RANCHI + NEW DELHI UNIVERSITY SCIENCE PRESS 113, Golden House, Daryaganj ‘New Delhi-110002 011-43 53 25.00 011-43 53.25.28 won laxmipublications.com infowlaxmipublications.com © 2011 by ¥ 180.00 2011 ‘OFFICES € Bangalore 080-26 75 69 30, € Chennal 044-24 34.47 26 € Cochin. (0484-237 70 04, 405 13 03, © Guwahati 0361-251 36 69, 251 38 81 € Hyderabad 040-24 65 23 33, € Jalandhar 0181-222 12 72 ¢ Kolkata 083.22 27 43 84 € Lucknow 0522-220 99 16 ¢ Mumbai 022-24 91 54 15, 24927869 ¢ Patna 0612-230 00 97 € Ranchi 0651-221 47 64 UCP-9612-180-C PROGRAM WITH SOLUTION-ANA ‘Monit Printagraphies, Delhi Nt Printers, Delhi Contents Chapters 1. C Concepts 2. Introduction—C Programs 3. Fundamentals—C Programs 4. © Debugging 5. Sample Questions 6, Short Questions and Answers 7. Questions Pages 1 12-81 s2-112 113-248 249-261 262-279 280-286 Preface This book gives a rich collection of C programs. These programs that support the theoretical concepts are given in a large number to help students understand the concepts better. This book will be useful for students of BE, MCA, BCA, MSe, and BSc, which have C program- ‘ming language as a part of the course The first chapter deals with the fundamental concepts of C language, ‘The second chapter focuses on introduction C programming. The third chapter provides with detailed program on next level to the basie C program, Fourth chapter focuses on C debugging, The fifth chapter ‘Greater than Vertieal bar 0 Parenthesis lef Slash U_|__ Bracke: lenright Back slash 0 Braces leftright - Tilde % | Perwent - Underseore # [Number sign or Hash $ Dollar = Equal to ? ‘Question mark @ | Atterte 1.5_DELIMITERS Delimiters Use Colon Useful for label 7 Semicolon Terminates the statement (0 Parenthesis Used in expression and function T) Square Bracket ‘Used for aay declaration (Curly Brace ‘Scope of the statement hash Preprocessor directive Comma, Variable separator 1.6 _C KEYWORDS Auto Double Iai Suet Break Else Long Switch Case Enum Register Typedet Char Extem Retum Union Const Float Short Unsigned Continue |For Signed Void Default Goto Sizcot Volatile Do 1 Statie while C Concerts 5 1,7 IDENTIFIERS Identifiers are names of variables, functions, and arrays. They are user-defined names, consisting sequence of letters and digits, with the letter as the first character. 1.8 CONSTANTS Values do not change during the execution of the program Types 1. Numerical constants: — Integer constants These are the sequence of numbers from 0 to 9 without decimal points or fractional part or any other symbols. It requires minimum two bytes and maximum four bytes Egy 10,20, + 30,~ 14 — Real constants Itis also known as floating point constants Bg: 2.5, 5.342 2. Character constants: — Single character constants A character constant is a single character. Characters are also represented with a single digit or a single special symbol or white space enclosed within a pair of single quote marks Ege a, 8. — String constants Siring constants are sequence of characters enclosed within double quote marks. Eg: “Hello”, “india”, “444” 1.9 VARIABLES It is a data name used for storing a data value. Its value may be changed during the program execution. The value of variables keeps on changing during the execution of a program, 1.10 DATA TYPES Data type Size (Bytes) Range Format Specifiers Char 1 = 128 t6 127 Ye ed char 010 255 © Unsi 6 — C Procrams with Sowutions Short or int 32,768 t 32, 767 Unsigned int 0 10 655355 Float 4 Bao 3810 Hae a8 Tone 4 = 2IATAR3O48 to 2147483647 ‘Unsigned long. 4 0 to 4294967295 Double 8 17e—308 to L7er308 Long double 10 Side — 4932 to 1 1eh4932 1.11 OPERATORS It indicates an operation to be performed on data that yields value, ‘Types ‘Type of Operator Symbolic representation Arithmetie operators Relational operators Logical operators Tnerement and decrement operator Assignment operator itwise operator ‘Comina operator Conditional operate 2 1.12_ INPUT AND OUTPUT Reading data from input devices and displaying the resulls on the sereen are the (wo main tasks of any program, Formatted Functions — The formatted input/output functions read and write all types of values Input Output Scant) printé() Unformatted Functions C Concerts 7 — The unformatted input/output functions only work with the charcter data type Input setch() etched getchar() gets 1.13_DECISION STATEMENTS: Output puch) putchar() puto) It checks the given condition and then executes its sub-block. The decision statement decides the statement to be executed after the success or failure of a given condition. Types: If statement Ifelse statement Nested if-else statement Break statement Continue statement Goto statement Switeh() statement Nested switch Qease Switeh() case and Nested if Statement ‘Syntax, TF satement ifeondition) Teelse statement If (condition) t Statement 1; Statement 2; ) else { Statement 3; Statement 4; ) Nested ifelse statement If (condition) 8 C ProcRAMs with SOLUTIONS Statement 2; Elke if (condition) { Statement 3; Statement 4; ) Ese { Statement 5; Statement 6; ) Break statement Break; Continue statement Continue; ‘Goto statement oto label ‘Switch statement ‘Switch (variable oF expression) ‘ Case constant A: Statement; Break; Case constant B: Statement; Break; Defaul Statement; } 1.14 LOOP CONTROL STATEMENTS Loop is a block of statements which are repeatedly executed for certain number of times. Types 1. For loop Nested for loops While loop do while loop do-while statement with while loop C Concerts 9 ‘Statement Syatax For loop For(nitialize count { Statement; Statement; ; lest condition; re-evaluation parameter) Nested for loop forinitialize counter, test condition; re-evaluation parameter) { Statement; Statement; for(initialize couater; test condition; re-evaluation parameter) Statement; Statement; ) ) While loop While (test condition) { Body of the loop Do while loop wo { Statement; ) While(eondition); ‘Doswhile with while loop Do while(condition) Statement; ) While (condition); 1.15 ARRAYS Itis a collection of similar data types in which each element is located in separate memory locations, ‘Types 1. One dimensional array 2. Two dimensional arrays 3. Three or multi dimensional arrays 10 C ProcraMs wir SOLUTIONS ‘Operations Insertion Deletion Searching Sorting Merging 1.16 STRINGS Character arrays are called strings. Group of characters, digits, symbols enclosed within quotation marks are called as strings. Sering Standard Functions Functions Description Swen Determines the length ofa sing 7) Copies esting from source to destination Semepy) Copies charcters of a string to another sring upto the specified length Swiempo Compares characters of two sings Strempd) Compares characters of two strings upto the specified length Stmempd) Compares characters of two sings upto the specified length SeiempO Compares characters of two srings upto the specified length Surwed) Converts uppercase characters ofa string o Tower ease SeruprO Converts lowercase charactors of a sng to upper ease Serdup0 Duplicates « sting Serchr) Determines the fist occurrence of given character in «string Serche) Determines the last occurrence of given character in a sing Sut) Determines the first oocuirence of given sting in another st Seat “Appends source sting 1 destination sting See Reverses all charactors of a sting Steet) Sei all characters of string with» given angument or symbol Sep Finds upto what length two stings are intial Supbik) Searches the fst oocurtence ofthe character in 8 given sting and then displays the string starting fom that chaeter C Concerts 11 1.17_ FUNCTIONS It is a self-contained block or a sub program of one or more statements that performs a special task Declaration of functions Funetion_name (argument/parameter) ‘Argument declaration; { Local variable declaration; Statementl; Statement 2; Return (value); Call by value In this type, value of actual arguments is passed to the formal arguments and the operation is done on the formal arguments. Any change made in the formal argument does not effect the actual arguments because formal arguments are photo copies of actual arguments, Call by reference {In this type, instead of passing values, addresses are passed. Function operates on address rather than values. Here the formal arguments are pointers to the actual argument. 1.18 RECURSION A funetion is called repetitively by itself. 2 INTRODUCTION—C PROGRAMS Chapter 1] Program to find sum of two numbers. inelude ‘Hinelude void main) { int abs; elrser0s printit"Enter two no: ”); scant{“%d%d",&a, deb); printf(* geteh(); ) m="%d",s); Output: Enter two no: $ 6 sum=1 2] Program to find area and circumference of circle. #include voidmaing) { ints; float pi=3.14,arca.ci: elrser(); print“enter radius of ercle:"); InTRODUCTION-C ProcramMs 13 scanf"%d" 8): area=pitr*r; printf(“area of circle-%f ”,area); ci-2*pite, printf(“circumference=%f ”,ci); etch; ) Output: center radius of a circle: $ area of circle=78,000 circumference=31.4 3] Program to find the simple interest. Hinclude ‘finclude void main) { int pyrtsis clrserQ; print{(“enter principle, Rate of interest & time to find simple interest: "); sean“%d%d%d” Sep, Ser, 81); si-(p*r*/100; printf(“simple intrest= 9a! getchO; } Output: center principle, rate of interest & time to find simple interest: 500 5 2 simple interest=S0 4] Program to convert temperature from degree centigrade to Fahrenheit. Hinclude void main() { 14 C Procrams wiTH SOLUTIONS float fi elrser(; ‘enter temp in centigrade: "); vot", Bie) F(1.8%0)+325 printi(“temp in Fahrenheit-%t”.1; etch) 3 Output: center temp in centigrade: 32 temp in Fahrenheit-89,59998 '5] Program to calculate sum of § subjects and find percentage. #includestdio.h> #Hinclude void maing, t int s1,82,83,s4.35 sumotal=500; float per; celrser(); printi(“enter marks of 5 subjects: ”); seantt%od%od%ed%dMd”, &s1,&s2, 893,884,885); sum=sl4s2+83+54+35; printf(“sum=%d" sum); per=(sum* 100)tota; printf(“percentage=%P" per); sgetch(); ) Output: center marks of 5 subjects: 60 6s 50 o oo sum=300 pereentage~60.000 6] Program to show swap of two no’s without using third variable. Hinclude #include INTRODUCTION-C ProcraMs 15 void maing { into elserQ; print(“enter value for a & b:"); seantt"%d%d" a,b); arath; bea-b; wah; printi(“aflr swapping the value of a & b: Yad %d a,b); etch); } Output: enter value for a & b:4 5 after swapping the value ofa & b: 54 71 Program to reverse a given number, Finclude finclude void main) intnar-0; clrser(); print(“enter any no to get its reverse: ") scant" Sn); vwhile(w>=1) { a=n%10; rrl0+9; nen/l0; ) printt“reverse etch; ) Output: center any no to get its reverse: 456 reverse=654 16 C PROGRAMS WiTH SOLUTIONS {| Program to find gross salary. ¥include ¥inelude void main) ‘ int gs,bs,da,e; clrser(); printi(“enter basi salary: "s seani("%d” &bs); a-(10*3)/100; ta=(12"B5)/100 gsrbstdatta; printft“gross salary=%od" 2s); sgotch); } Output: center basie salary: 100 gross salary=122 9] Program to print a table of any number. finclude Hinclude void main() t int gssbs,data elrser(); printi(“enter basic salary: "); seantt"%d" &¢bs); da-(10*bsy/100; ta=(124bs)/100; as-bstdatta; printftgross salary-%d" gs); etch); ) Output: center a no to know table: 2 2r1=2 INTRODUCTION-C ProcRaMs 17 2924 283-6 248 295-10 2612 2714 2816 2018 2*10-20 10] Program to find greatest in 3 numbers. Hinelude ‘finclude void main() { inta,be; lrser(); printf(“enter value of a, b & c:” seanf{"%d%d%d” Sa, deb, &e); ifl(a>b)&&(a>c)) print(“a is greatest”); if(b>e)S&e(b>a)) print“ is greatest”); if((c>a)&A&(C>b)) print“c is greatest"); etch; } Output: enter value for a, b& e: 5 7 4 bis greatest 11] Program to show the use of conditional operator. Hinclude ‘finelude void maing) { clrser(); printi(“enter value for a & b:”); 18 C ProcRAMs wiTH SOLUTIONS scanf("%d%d",8a,&b); (o>b)Pprintta is greater”):print{("b is greater”); getehO; Output: center value for a & b: 5 7 Dis greater 12] Program to find that entered year is leap year or not. Hinclude include void main print{(“enter any year scanf{"%d” Sn) inn%4—=0) printf(“year is a leap year”); else printf(‘year is not a leap year"); sgotch; } Output: center any year: 1947 year is not a leap year 13] Program to find whether given no. is even or odd. +inelude ¥inelude ‘void main() { intn; clrscr(); printi(“enter any no: seani("%d” Sen); ifn42—=0) printt“no is even"); else INTRODUCTION-C ProcRAMS 19 printi'no is odd"); etch; } Output: enter any no: $ no is odd 14] Program to shift inputed data by two bits to the left. Hinelude Hinelude void maing { intxy: lrser(); printf("Read the integer from keyboard :-"); seani(“%d" 8x): x3; as printi(“uiThe left shifted data is = % geteh(); } Output: Read the integer from keyboard = 2 ‘The left shifted data is = 16 15] Program to use switch statement. Display Monday to Sunday. include include voidmain) { char ch; clrser(); printf(“enter m for Mondayint for Tuesdayinw for Wednesday\nh for Thursdayinf for Friday\ns for Saturday\nu for Sunday); seanfi"%e" Sch); switeh(ch) { case ‘mr’ 20 C Procrams witt SOLUTIONS cease ‘M’ printf(“monday"); break; ease ts case ‘T" printf(“tuesday”); break; case “W printf(“wednesday”); break; case “h’ cease “H printf(“thursday”);, break; case ‘f" case “F prinef(“ftiday”); break; case ‘S" printf(*saturday”); break; case ‘U" printi(*sunday”); break; default printf(“wrong input break; } getch); ) Output: center m for Monday 1 for Tuesday INTRODUCTION-C. PROGRAMS ww for Wednesday hh for Thursday £ for Friday s for Saturday uu for Sunday: f friday 16] Program to display arithmetic operator using switch case. Hinelude Hinclude void main() { int abnsmsud; elrser() printienter two no's : scanft"%od%4a” a,b); printi(“enter I for sum'n2 for multiplyin3for subtraction for division: seanft“%od", 8m); switeh(n) ‘ cease | sath; printf(*sum=%d",s}; break; case 2: mab; printf(“multiply=%d",m): break; case 3: b: printf(“subtractior break; cease 4: dab; printf(“divission=%d", 4); break; 21 22 C Procrams wiTH SOLUTIONS default: printf(“wrong input"); break; etch); } Output: enter two no's: 8 4 enter | for sum 2 for multiply 3 for subtraction 4 for division: sum=12 19] Program to display first 10 natural no, & their sum. finclude ¥inelude void main) ‘ int isum-0; elrser0) fori=1sic=10;i+4) ‘ printit“%d no is= %ainiD; sum=sumti; printf(*sum =9%d",sum); getch(); Output: Ino is=1 2no is-2 3nois-3 Ano isa Sno iss 6 no is-6 Tho 8no 9 no is9 10 no is=10 sum=55 18] Program to print stars Sequencel: include Hinelude tHinelude void main() { int i,k; clrser(; INTRODUCTION-C. PROGRAMS 23 24 C PRoGRaMs wiTk SOLUTIONS t foriSi>ii-) printf") for(k=L:k<=i3k +) printf(“"); printf(‘\n"); } etch; } Output: 20] Program to print stars Sequence3. Winelude Hinelude void main() { int iguks clrser(); forti=li<3;it) { for(j-3>=i- printf") { for(k=L:k<= printg( d printf(*in"); } etch); ) Dk) INTRODUCTION-C. PROGRAMS Output: 21] Program to print Fibonacci series up to 100. Hinclude #¥include void main() { int a-1,b-1,e-0,i, clrser(); printf("%d%da.b); forli-Gsi< 1055+) { coat; iffe<100) { printi("%dit",e);, } » ) getch(s } Output: 112358 1321345589 22] Program to find factorial of a number. inelude ifinclude void main() { int m,faer=1; clrserQ; print{(“Enter any no: "); seanf{%d" Sn); 25 26 C ProcraMs WITH SOLUTIONS for(i-nsi>=1si-) { fuct=fact*i; } rint(“Factoral=Y%d" fat) etch; } Output: Enter a no: $ Factorial=120 23] Program to find whether given no. is a prime no. or not. Hinclude #include void main() t int i.-0; lrser(); printi(“Enter any no: "); sented” Sen); fori-2sien-l:i++) { ifln2%im=0) mh break; ) ‘ft 0) printi(*prime 1 else % printf(“Not prime”); etch); Output: Enter any no: 16 Not prime INTRODUCTION-C PROGRAMS 24] Program to display sum of series 1+1/241/3+. Ain. ‘Winclude Hinelude void main() { int n,isum=0; clrser(); print{(“Enter any no: "); seanf{"%d” Sn); printf(“1”); for(i=2;i<—ne i++) printf" 1/%d +"); forti=I;i<=nsi+) printf 1%a"ns print(*inSum=L getch(); ) #include void main { int n,isum-0; elrser(); printf(“Enter any no: ” seanft%od" Sn); for(i=lsiensiniv2) t printt(“%od=".i); 27 28 C PROGRAMS WITH SOLUTIONS } printi("%d".m); printf(\nsum=9 etch: } Output: Enter any no: 7 1534547 Sum=16 26] Program to use bitwise AND operator between the two integers. Winclude Hinelude void main() { int abe; clrser() printf("Read the integers from keyboard "); seantt"%od Yd” 8,8); cma; printf(“inThe Answer after ANDing is: %d",0); etch; ) Output: Read the integers from keyboard:- 8 4 ‘The Answer after ANDing is: 0 27] Program to add two number using pointers. Hinclude void main0) { int *p1,*p2,sum; clrser(); print % scant“ %od%d”,&*p1,&*p2); sum=*pl+*p2; ater two no's: printf("sum=%d" sum); getch0) Output: enter two no's: 10 20 sum-30 28] Program to add two number using pointers. Hinclude void main() { int *pl,*p2,sum; elrser(); printf(“enter two no's: "); scanit"%d%d”,&*p,8*p2); sum="pl+*p2; printi('sum=%d” sum); etch); , Output: enter two no’s: 10 20 sum=30 INTRODUCTION-C. PROGRAMS 29] Program (o show sum of 10 elements of array & show the average. Hinelude Hinelude void main) { inta[S},max,is clrser(); printf(“enter element for the array: ”); fortiMO5i ‘finclude void maing { intal3]2] 1312): clrserQ;, print(“enter value for a matrix: "); for(i=O;i<3;i+4) { forG-05<25+4) seanf{"%d”,Sai]iD; ) printf(“enter value for b matrix: ") for(i-O;i<3si+4) { for(jOj<25+4) seanf("%d" Sis ) prine(*\na matrix shin” for(i-0;i<3;i++) { for(jO;j<255+4) 32 C Procrams witt SoLuTions t printf" %d "af LSDs ) prinen"); } printf(*inb matrix isinin”); for(i-Gicdi+) { forGi-05<25 { printf" %d "BUILD: ) prinef"n"); } etch; } Output: center value for a mattix: 7 center value for b matrix: 3 2 1 4 5 6 a matrix is 78 94 56 INTRODUCTION-C ProcRAMs 33 bb matrix is 32 14 56 32] Program to find sum of two matrices, include tinelude void main ‘ inta[3]2) (3121 13102} clrscx(); printi(“Enter value for | matrix: ”) forti-O:i<3:i44) ‘ fonfr0jeai+4) seanft“%d, Sali); for(HOi3:i+4) { forG=05<2;)+) fab b0I0); } printf(‘Sum of matrix isin”); fortiO:i<3:i+4) { forGr0je2sit¥) t printi(“%odit” fis 34 C Procrams wit SOLUTIONS printfn"); } sgeteh(); Output: Enter value for 1 matrix: L Enter value for 2 matrix: 4 Sum of matrix is 37 98 88 33] Program to find subtraction of two matrices. Hinchude ¥include void main) { intals] (S}elS)is clrser(); printf(‘enter value for array a"); fortiO:i Hinelude void main() { inta[3]2).012).¢(3]2}ais clrser(; printf(“enter value for 1 matrix: ") for(i-O;i<3si-4) { for(j-0j<25+4) scanf{“¥%d",&afilljD; ) printf(“enter value for 2 matrix: ") for(iMO;i<3:i+4) { for(i=0;5=25)+-19 35 36 C Procrams with SOLUTIONS seanft%d" iJ); , forti-O:i ‘Hinelude void main() { inta[3]2).b2I3 Lid: clrser(; print{(“Enter value for matrix: ") forGi-OiiediH4) { for(-Oj<2I+) seanf('%d" fall): ) print*Matrixn”); for(iMO;i<3;i44) { forG-0j<25+4) print %d "alii printf"\n"); } for(HOsicdi+4) print{(“Transpose matrix:in"); forti-0;i<2;i++) { for(j-05-35+) printf(* %d "bUiILD: printf0"); 3 etch); ) 37 38 C PROGRAMS WITH SOLUTIONS Output: Enter value for matrix: 4 Matix: 45 61 23 “Transpose matrix 462 513 36] Program to find the maximum number in array using pointer. finchude include void main() ( ‘int max,i,*a[5]; elrser();, printfenter element forthe array: ") font-si<5i'1) seant(%ed" ali) smax*a{0}; for(i bicsi-t) ( iftmax*afi) mana ) print maximam no= %d"max); etch: } INTRODUCTION-C PRocRAMS 39 Output: enter elements for array: 5 4 1 2 maximum no=7 37] Program to show input and output of a string. Hinelude inelude void main) { char af50]; elrser(); printf(“enter any string: "); tsa); puts(a)s etch); 3 Output: center any string: hi everyone hi everyone 38] Program to find square of a number using functions. tinclude #include void main { int rev(int intra; elrser(; printfenter any no: "); scanf("%od" fea); rrev(a)s printf(“square is : Yd); 40 C ProcRaMs WITH SOLUTIONS etch: ) int rev(int x) ( retum(xt); } Output: center any no: $ square is : 25 39] Program to swap two numbers using functions, Hinclude Hinclude void main) { void swap(int.int); inta,byr, clrser(); printf(“enter value for afb: seanf("%d%d",8a,&eb); swap(a.b); etch; } void swap(int a,intb) { inttemp; temp=a; amb; betemp; printf(“after swapping the value for a & b is : Yd %ed",a.b)5 ) Output: center value for a&b: 4 5 after swapping the value for a & b: 5.4 INTRODUCTION-C. PROGRAMS 40) Program to find factorial of a number using functions. tinclude sinelude void main() ( intags ‘int fact(int); elrser();, printfenter ano: ") scanf("%a" a) f=fact(a); print factorial= 4d"; getch(); ) int fact(nt x) ( in fae=1.s for(i-xi>-li-) facrfac*is retum(fac); ) Output: center a no: $ factorial=120 41] Program to show table of « number using functions. ¥inelude Finelude void main() { void table; clrsex(); tabled: gcteh()s 41 42 C Procrams wiTl SOLUTIONS void tabled { inen.is, printf(“enter a no to know table: scanf{%d” Sen); forti=tii { printhe"%od*%od%din” n,n), } } Output: center a no to know table: 2 212 2024 29366 24-8 295-10 26-12 2714 28-16 20-18 210-20 42] Program to show call by value. Hinclude Hinelude» void main) { int a.b,swap0) elrser(; a5; blo, printf("valuc of a=%d & value of b=%d before swap ".a,b) swap(a,b); INTRODUCTION-C. PROGRAMS print(snvalue of a Yd & b=%d after swap”,a,b); sgoteh(); intswap(intx,inty) ‘ inttemp; temp-x ys y-temp; } Output: value of a=5 & value of b=10 before swap value of a=$ & b=10 after swap 43] Program to show call by reference, include Hinelude ¥inelude void main() { void max} clsser(); max; etch); } void max() { inta[S] maxis printi(‘How many no’s you want to enter: ”); seanf("%d” Sen); printf(“Enter element for the array") forti0:i inelude void main) { ints elrser(); printf(“enter number: " seantt“%d” Sn) itn<0) printi(“invalid number"); else printf(“%d!—%d"n,fact(n)); sgeteh()s ) int facttint x) { ito) retum 1; else return(x*fact(x-1)); } Output: center number: $ st=120 46] Program to find whether a string is palindrome or not. tinclude Hinelude 45 46 C Procrams wiTl SOLUTIONS void maing { char s1[20],s2[20]; lrser0: print(entera string: "s seanf("%s"s1); strepy(s21); strrev(s2); ifoteemp(s12)—-0) printfstring is a palindrome"); clse printf“not a palindrome sting"); etch ) output: center a string: abe not palindrome sting 47. File Operations: include=stdio > finchude void main() ( file “fp char ¢; ipl; clrsex(); fp-fopen(“test.c”,"w")s printt*\nenter the contents for filel(#.end)\n"); e=getchar(); while(e!="#") { puto(etpys e=getchar(); } rowind( tp) fp-fopent“test. "; INTRODUCTION-C ProcRAMs 47 fp1=fopen(“tes.c°,"w"); fgete( tp); while(e!=cof) fputo(etpy c=fgeto(tp)s ) felose(fpls felosettp%); fpl=fopent“tes.c" printi(‘inthe contents in file 2); while(e!=eof) ‘ putehar(e); cmfgete(fpl); felose(fp1); etch); } Output: center the contents of filel(#-end) good moming? the contents of file2 ‘good moming 48, Merging One Dimensional Array — Hinelude=stdio.h> cluding The Repeating Element inelude void main) { inta{50} b(50].n1,n2,ix; clrser(); printf(“enter the number of elements in the first array"); scanf(“%d" Sn); printf(“enter the elements\n") 48 C ProcRaMs wiTH SOLUTIONS for(Ojienl i++) t printf(“enteral%a]",i+1); seantt“%d” ali); 3 printf(“enter the number of elements in the second array”); seanf{%d" €en2); printf(“enter the elements forti-O;isn2sir) ter b(%a] +1); seanttYea bis 3 forx-O;x Hinelude ifinclude #inelude void main() { char s{100];, int vow=,cons=0,spe=0,pune=0,L; clrser(); printf(“enter the statementin”); gets(s); sstrlen(s); for(iH03i<1i+4) { ittisalpha(sfi)) { ins} "a" Ist { e'Isti [slo's ) 50 C PRrocraMs WITH SOLUTIONS vow; , else { cons; ) , iflisspace(stiD) ‘ sper; 3 iNGispunct(s{i)) ‘ pune+s 3 ) printi(‘\nno.of words=%d” spot); printf printf(*\nno.of consonants=%d",cons); inno.of vowels-%d", vow}; printf(*inno.of space=%d" spe); printf(“inno.on special characters=%d" pune); getch(); } Output: Enter the statement *Nothing is impossible in the world Noof words6 No.of vowel 0 No.of consonants=19 No.of space=S No.of special characters=1 INTRODUCTION-C. PROGRAMS 450, Write a program to create enumerated data type for 12 months. Display their values in integer constants. Finelude Hinelude void main() { Enuin month(an, Feb, Mar, Apr, May, June, July, Aug,Sep, Oct, Nov, Dec) celrser(); printt‘Jan-%d", Jan); print(“Feb="4d", Feb); prinft‘Sune=%d”, June); print"Dee=%ad", Dec): ) Output: Jan=0 Fob=1 Jume=$ Dee=I1 51 3 FUNDAMENTALS—C_ PROGRAMS Chapter 1. A program to evaluate the equation yxn_ when n is a non-negative integer. inelude ‘Hinelude void main() { {nt count, n; float xy; printf(“Enter the values of x and n:"); scani(%f%d", &ex,&n); sr; count=1; while(count<=n) t yy, ccount++; } printf; n-%d; x to power n-%E", x, ny) ) Output: Enter the values of x and n: 2.5 4 X=2,500000; n=4; x to power n= 39,062500 2. A program to print the multiplication table from 1*1 to 12*10, ‘include #include 52 FUNDAMENTALS—C. PROGRAMS Hdefine COLMAX 10 define ROWMAX 12 ‘void main() { int row, column, y; row=1; print{("MULTIPLICATION TABLE *) printi( yrrow*column; printi(‘%d", y)s ccolumn=column +1; } while(column<-COLMAX); printi("in"); row=row+l; 3 while(row<-ROWMAX); printf Output: MULTIPLICATION TABLE 1 2 4 5 6 7 8 9 2 4 6 8§ W 2 4 6 18 2 3 6 2 15 I 2 M4 27 3 4 8 12 6 0 4 2® 32 36 40 5 1S 2% 2 % 35 40 45 50 6 2 W M4 3 3% 4 4 St 60 7 1 2 ® 3 42 4 56 68 70 8 16 4 32 40 48 56 6 2 80 54 C ProcRAMs with SoLUTIONS 9 8 7 % 4 SB RD A 10 2% 30 4 50 6 7 8 9% 100 no 3 4 55 66 77 88 99 10 12 2 36 48 6 72 84 95 108 120 43. Program uses a for loop to print the powers of 2 table for the power 0 to 20, both positive and negative. #include inelude void maing { long int p; intn; double print" print“2t0 powern nto power-n"); ‘ = 1.04(double)p; printi(“0ld 10%d %20.121¢ pana): ) print 3 ‘Output: 2t0 power n a 2 to power-n 1 0 1,000000000000 2 1 ‘0,500000000000 FUNDAMENTALS—C PRrocrams 55 4 2 1025000000000 8 3 0.125000000000 16 4 0.062500000000 32 5 0.031250000000 6 0.015625000000 7 0.007812500000 8 1.003906250000 9 .001953125000 10 0.000976562500 n 0.000488281250 2 0.000244140625 1B 0.000122070313 14 0.000061035156 1s 0,000030517578 16 0,000015258789 131072 7 0,000007629395 262144 18 0,000003814697 524288 19 0.000001907349 1048576 20 0.000000953674 4. A class of n students take an annual examination in m subjects. A program to read the marks ‘obtained by each student in various subjects and to compute and print the total marks obtained by each of them, Finclude inelude #idofine FIRST 360 ¥ define SECOND 240 void maing ‘ intn,m, i, jr mumber, marks, total; printi(“Enter number of students and subjects”); seanf{Yed%d", &n,&m); prinf("\n") for(=1; i<-n; ++i) { printf(“Enter roll number:”); 56 C ProcRAMs WITH SOLUTIONS seanf(“%d", &roll_number); total=0; printf(“Enter marks of Yd subjects for ROLL NO”, m, roll number); for(i=1:jem;j+) { seanf{"%d”, &marks); total-total+marks; printf(’“TOTAL MARKS ~%d"”, total); iftotal>-FIRST) printi(“(Firstdivision)”); elseif (total>=SECOND) printf(“(Second division)”; else printi(“(***FAIL***)");, ) Output: Enter number of students and subjects 36 Enter roll_number: 8701 Enter marks of 6 subjects for ROLL NO 8701 81.75.8345 61 59 ‘TOTAL MARKS =404 (First division) Enterroll_number:8702 Enter marks of 6 subjects for ROLL NO 8702 51.4955.47 6541 ‘TOTAL MARKS =308(Second division) Enter roll_number: 8704 40 1931.47 3925 ‘TOTAL MARKS-201(*** FAIL ***) . The program illustrates the use of the break statement in a C program, ‘finclude #finelude void main() FUNDAMENTALS—C PRocRAMS 57 { intm; float x, sum, average: printft"This program computes the average of a set of computers”); printf(“Enter values one after another"); printf(“Enter a NEGATIVE number at the end”) sum=0; for{m=I:m<=1000; +m) { scant("%of”,&x): iftx<0) br } average=sum/(float)(m-1); printi("n"); print{(“Number of values =%d"”.m-1); printi(‘sum=%P", sum); printf(“Average%f", average); J Output: ‘This program computes the average ofa set of numbers Enter values one after another Enter a NEGATIVE number at the end 2123.24 22.2622-1 Number of values =6 Sum= 138.000000 ‘Average™23,000000 6. A program to evaluate the series 1/1 Hinclude #inelude ‘define LOOP 100 ‘define ACCURACY 0.0001 void main) { 58 C ProcRAMs with SOLUTIONS int; float x, term, sum; printf(“input value of x"); seani("%I", &x); sum=0; for(term: { sum+=term; iftterm<-ACCURM goto output; :n=1.265800; No, of terms-7 Input value of x: .75 EXIT FROM LOOP Sum-3,999774; No, of terms34 Input value of x:.99 FINAL VALUE OF N IS NOT SUFFICIENT TO ACHIEVE DESIRED ACCURACY /. Program illustrates the use of continue statement, ‘finclude #inelude #Yinelude void maing) FUNDAMENTALS—C. PROGRAMS t int count, negative; double number, sqroot; printi(“enter 9999 to STOP"); count; nogative=0; while(count<=100) { printi(“enter a number:"); seanf(“%6l"", S&number); if{oumber—9999) break; if{number<0) { printi(‘Number is negative "); nogativer+s continue; 3 sqrootsqrt{number); printi(‘Number-%If square root=%If”, number, sqroot); count; ) printf('Number of items done ~%d', count); printi("Negative items=%d", negative); printi(“END OF DATA”); Output: Enter 9999 to STOP Enter a number: 25.0 ‘Number=25,000000 Square root =5.000000 Enter a number: 40.5 ‘Number =40,500000 Square root~6.363961 Enter a number:-9 59 60 C PRrocrams witl SoLuTioNs Number is negative Enter a number: 16 ‘Number= 16.000000 Square root=4.000000 Enter a number: 14.75 ‘Number is negative Enter a number: 80 ‘Number=80,000000 Square root-8.944272 Enter a number: 9999 ‘Number of items done=# Negative items=2 END OF DATA 8. Program to prin binomial coefficient table Hinelude +#inelude define MAX 10 void main() { intm,x,binom; prinetm x"); for (m-0; m<=10;++m) print“ m0; { printf("9624", m); X-0; bio while(x<=m) { iffm=-0 x= =0) print(“%td”, binom) else FUNDAMENTALS—C. PROGRAMS { bbinom=binom* (mm-x+I)/x; printf(‘%4d”, binom); } while(m=-MAX); printi(* Output: Me 012 4.5 6 oT o 1. 2 1 2 1 3 1 3 3 1 4 1 4 6 4 1 5 1 5 wb Ww Ss 1 6 1 6 I 0 I 6 1 7 1 7 m3 35 m7 B 1 8 WW 56 1 S65 2B 9 1 9 3% 84 126 126 8 10 1 10 45 120 210-282-210, 9, Program to draw a histogram, Hinclude ‘define NS void main) { int value[N]; inti, jm: js nN; +4) fori { 8 36 120 1 9 4s 10 10 61 62 C PROGRAMS WITH SOLUTIONS print(“enter employees in group-%d:", m1) seanf(“Yéd", 8x); value{n}=x; printh(“¥%d”, valueln); 3 printi(‘in"); printf(“[n"); for(n=0; n include void main) { float p, cost, pl, cost; for(p=0; po=10; p=pt0.1) { cost=40-8*p+p*p; iffp==0) 63 64 C ProcRAMs wiTh SOLUTIONS costl=cost; continue; ) if(cost>=cost!) break; cost=c0st plop: } pHiptpl)i2.0; cost=40-8&p*p*p; print{("MINIMUM COST=%.2f AT p=%.1{", cost, p): } Output: ‘MINIMUM COST = 24.00 AT p=4.0 - Program for plotting of two functions (y1=exp(-ax); y2=exp(-ax’ /2). fincludesstdio.h> +¥inelude inelude voidmaind) ‘ inti; float a,x, y1, y25 0.4; printf printi(“0 fox(x-0; <5; x=x+0.25) yl Gnd (S0%expl-ax}+0.25); y2={int) (SO%expl-atx*w/2)+0.5); ityl=-2) { if==25) printf"X_[; else printi("[); for(i-1s e=yl-1; +4) printi("); printf"), continue; ) iftyl>y2) t iftx==2.5) printf"); else print(“*") for(i=1si<-(yl-y2-1); Hi) print"); print(“0") continue; , itx—25) prinef°XP5 che print(* for(i=1; is=yl-1; ++i) printf"); print(“0") forf=lsi<=(y2-y1-D;-+4) FUNDAMENTALS—C. PROGRAMS 65 66 C ProcRaMs witl SoLuTiONs ‘Output: 12, Write a program using a singlesubseribed variable o evaluate the following expressions ‘Total= }) X3 the values of x1, x2,..... are read from the terminal ‘finclude ‘inelude void maing) { inti; float x[10}, value, total print{(“ENTER 10 REAL NUMBERS"); for(iH0;i<10;i++) scanf{“%4t", &value); ales total=0.0;, for(i=0; i<10; ++) 13. FUNDAMENTALS—C PRoGRAMS 67 total = total + x{i}*x[i]; printf"n"); for(i=0; i<10; 4+) printt'x{%2d] =%S.20", +1, xfs printf(“total=%,2F" total); } Output: ENTER 10 REAL NUMBERS. 112.23.3.445.5 667.788 9.9 10.10 X{1-1.10 x(2}-2.20 X[3]-3.30 x{a}-4.40 X(5}-5.50 X(6]=6.60 X(7}-7.70 X[8}-8.80 X{9}=9.90 X{L0}-10.10 Total = 446.86 Given below isthe list of marks obtained by a class of $0 students in an annual examination, 43 65 512779 11 56 61 8209 25 3607 49 55 63 74 81 49 37 40.49 16 75 87 91 33 24 5878.65, 56 76 67 45 54 36 63 12 21 73 49 51 19 39 49 68 93 85 59 Write a program to count the number of students belonging to each of the following groups of ‘marks: 0-9,10-19,20-29,---,100. Hinelude Hinelude iidefine MAXVAL 50 decline COUNTER 11 void main) 68 C ProcRAMs with SOLUTIONS { float value [MAXVAL]; int, low highs int group[ COUNTER} {0,0,0,0,0,0,0, forti=0; MAXVAL; i++) { seanf(“%f", &value[i)): ++group|(int)(valuefi)/10)]; ) printi(‘in"); printi(“GROUP RANGE FREQUENCEY"); for(i~0; ic COUNTER; i+) t low-i*10; ») hhigh=100; else high-lowt9s printi("%62d%43d to %3d%d" iH1, low, high, group[il); ) Output: {3 65 51 27 79 11 56 61 82.09 25 36 07 49 55 63 74 81 49 37 40 49 16 75 87 91 33 24 58 78 (65 56 76 67 45 54 36 63 12.21 73.49 51 19 39 49 68 93 85 59 (Input data) SROUP RANGE FREQUENCY 1 009 2 2 Low 19 4 3 201029 4 4 301039 5 5 40 10.49 8 6 501059 8 7 60 1069 7 14, FUNDAMENTALS—C PRoGRAMS 69. 8 70079 6 9 80 t0.89 4 10 9099 2 ul 100 to 100 0 Write a program for sorting the elements of an array in descending order. tinclude #inelude void main() { int arr, emp, i j.m; elrserO; printf(“enter the number of elements in the array”); seanf{"%d”, &en); ar=(int* malloc(sizeoftint)*n); forti-O;i ‘Winclude void main { int tary, ij,n, LARGE; celrser(; printf(“Enter the number of elements in the array”); seanf{"%d”, &n); ‘art(int*) malloc(sizeoftint)*n); forti-0; ie; 114) printf(“Enter a number"); Sani; seantt"% } LARGE-art[0]; fortljiengi+) { iffan{i}>LARGE) LARGE=ar{i} } printf(‘“The largest number in the array is : %d”, LARGE); etch); 16. FUNDAMENTALS—C PRrocraMs 71 ‘Output: Enter the number of elements in the array:5 Enter a number: 32 Enter a number: 43, Enter a number: 23 Enter a number: $7 Enter a number: 47 ‘The largest umber in the array is : 57 Write a program for removing the duplicate element in an array. ifinclude Hinelude HincludeartiD) { temp=anfis anfij-ant{j); anf{jJ-temp; 72 C ProcRAMs wITH SOLUTIONS } } print(“Elements of aay after sorting”); for(i-0; in; i++) printt"%4d", refi): a Fh white(i=n) ‘ itlanti { for(e=js xem x44) arrx]-ar{x+1]; fi) print{(“Elements of array afer removing duplicate elements”); forti=0; i=n; i++) printf(“%d”, aril); etch; } Output: Enter the number of elements in the array:5 Enter a number: 3 Enter a number: 3 Enter a number: 4 Enter a number: 6 Enter a number: 4 FUNDAMENTALS—C PRrocraMs 73 Elements of array after sorting: Elements of array after removing duplicate elements: 4 6 17. Write a program for finding the desired k" smallest clement in an array. include Hinelude void maing { int ars ij, temp, ks elise; print(enterthe number of elements in the array”); scanf(‘“%ed", &n); arr{int*)malloc(sizeof{int)*n); fort-Osiemi-+) ( printf(“Enter a number") seanf(“%ed", S&arr[i]); fortj-ittsjemj+4) ( iffar[i] Hinclude ‘define N10 void maing) { inti,j.ms float median, af], t; printf(“Enter the number of items"); scanf{"%d”, Sn); printi(“Input %d values ",n); forinls msi) seanf("%ot", Salil); for(i-1yig-nlsie) { for(j=lsi iali}alie1)) ali: alilFali+l: rs) ales } else continue; ) , inna ~-0) median (afn/2}-a{n/2+1)/2.0; else ‘medianafn/2+1 forti=I;miconjitt) printf", afi; printf(‘median is %f", median); ) Output: Enter the number of items 5 Input 5 values 1.111 2.223.333 4.444 5.555 FUNDAMENTALS—C. PROGRAMS 75 76 C ProcRAMs WITH SOLUTIONS 5.595000 4.444000 3.333000 2.222000 1.111000 ‘Median is 3.333000 Enter the number of items 6 Input 6 values 358946 {9.000000 8.000000 6.000000 5.000000 4.000000 3.000000 Median is 5.500000 19. Program to calculate standard deviation, inelude ‘Winclude iidefine MAXSIZE 100 void main() { inti; float value [MAXSIZE], deviation; sum=sumsq printf("Input values: input -I to end”); for(in1; I MAXSIZE; it+) { scantt'%t", SevalueiD); ) iffvaluefi break; sum'=valuefi); mil; ‘mean=suny/float)a; for(i-1icmny i++) { finchude define STUDENTS 3 fidefine TTEMS 25 void main() { char key[items 1}, response{ITEMS +1); int count, i, stadent,n, correct{ITEMS +}; printi(“Input key to the items”) forti-0; #inelude void main() int M[SII6] s{5]I6], e{6], Mvalue[5][6], Svalue [5][6]Mweek{5], Sweek{5], Mproduct(6], Sproduet[6}, Mtotal, Stotal, i,j, number; print{(“Enter products manufactured week wise”); 80 C PROGRAMS WITH SOLUTIONS print(°MI1, M12, M21, M22, ete”); forilsimhi) for ISSi-) scantt"*d”, &MUlLDs printf(Enter products sold week wise”); printf("SI1, $12,-, $21,$22,-ete’ for(i 1; i<=4; i++) for-iSi) scantt'ad", &SIi)s printf(enter the cost of each product”); fon ljeSii) seanit'%d", &CUD; for(i=1; i<=4; i++) ISI) Mvaluefil[i]-MUllielils Svaluefill}-Slilbileli: } for(i-1s ima i++) t Mweekli}-0; Sweek| fox(i-1s 55:5) { Mweck{i] “-Mvalue(ifj}; Sweeki}+=Svaluefilil 3 3 for(i1s 55:54) { Mproduet{J=0; Sproduetf fon(i-1s <4 i+) { “Mproduet{i] +=Mvaluefilljl FUNDAMENTALS—C PRrocRAMs 81 Sproduct{i}+= Svalue(ii); } Mrotal=stotal=0; fortinlsi=dsi+) { ‘Mtotal+-Mweck{i]; Stotal-Sweek|i]; ) printi(“inin”); printi(“Following is the list of things you can"); printi(“request for enter appropriate item number and press RETURN key”); printf("1. Value matrices of production & sales”); printf("2, Total value of weekly production & sales”); printi('3. Product-wise monthly value of production& sales”); printi(“4. Grand total value of production & sales”); printi(“S Exit”); snumber0;, while) { print{(“ENTER YOUR CHOICE"); seantt%d”, &number): printf\n"); iflnumber= { print(“GOOD BYE”); break; } switel{number) { case 1 printf(*VALUE MATRIX OF PRODUCTION"); fort pis4 5-4) { printf("Week (%d), i"); 82 C ProcRAMs WITH SOLUTIONS for(i Ls}S:34) printit"9474", Mvalue); printf"\n"); printf(°VALUE MATRIX OF SALE si) fon(il; { printf("Week(%od)”, is for(i-lsje-Siih¥) printi(‘%674", Svalue(iJiD; printi("n"); breaks print“TOTAL WEEKLY PRODUCTION & SALI printf" PRODUCTION SALES”); ” printit - foe(i-1s ied +4) t printi(“week(%d", i); printf("7674%674", Mwweck{i], Sweek{i); : break; print(“PRODUCT WISE TOTAL PRODUCTION & SALES"); printh PRODUCTION SALES"); printf - foriHlsi-S:34-1) { printi(“Product(%d" ji; printi(“%474%74", Mproduet}, Sproduct{j}; 3 break; case 4: printh("GRAND TOTAL OF PRODUCTION SALES”); FUNDAMENTALS—C PRrocraMs 83 printf(“Total produetion=%d", Mtotal); break; default printit“Wrong choice, select gain”); break; } ) Printf(“Exit from the program”); } ‘Output: Enter products manufactured week wise , M21, M22,-——-ele now 2 4B BoB 4 Is BR 2 6 Ww Iso wou oi BR Enter products sold week wise SU, S12, —--, $21, $22, 0 B 9 2 2 0 2 4 10 no4 wb 4 2 RW B oH wo etc Enter cost of each product 102030 15.25 Following is the list of things you can request for enter appropriate item number and press RETURN key. 1. Value matrices of production & sales 2. Total value of weekly production & sales 3. Product-wise monthly value of production & sales, 4, Grand total value of production & sales 5. Exit 84 — C PROGRAMS WITH SOLUTIONS Enter your choice: | VALUE MATRIX OF PRODUCTION Week (I) 110. 300 360. 210. 325 Week (2) 130 260 420 225 300 Week (3) 120 320 300 225 350 Week (4) 140 220 450 210 300 VALUE MATRIX OF SALES Week (1) 100 260 270 180. 275 Week (2) 120 200 360 210 250 Week (3) 110 280 300 210 300 Week (4) 120 200 390 165. 250 Enter your choice: 2 ‘TOTAL WEEKLY PRODUCTION & SALES PRODUCTION SALES Week(1) 1305 108s Week(2) 1335 1140 Week(3) 1305 1200 Week(4) 1315 1125 Enter your choice: 3 PRODUCT WISE TOTAL PRODUCTION & SALES. PRODUCTION SALES Product(1) 500 450 Product) 1100 450 Product(3) 1530 450 Product(4) 855 450 Produet(S) 1275 1075 Enter your choice: 4 GRAND TOTAL OF PRODUCTION SALES Total production=5260 FUNDAMENTALS—C PRocRAMs 85 Total sales~4550 ENTER YOUR CHOICE:5 GOOD BYE Exit from the program 22, Write a program to read a series of words from a terminal using scanf function, ifinclude Hinelude void main() { char word! [40], word2[40}, word3[40}, word4[40]; printf(“enter text:"); seantt"'%s%s", word], word2); seang{"%s", word3); scang{“%s", word4); printf("n"); printi("wordl=Ysinword2=%sin”, wordl, word2); printit"word3=Yesinword4=%sin”, word3, word”) } Output: Enter text Seventh Street, sakthinagar, erode Word!=seventh, Word2=street Word3-sakthinagar Word4-erode 23, Program to read a line of text from terminal #inelude inelude void main() { char line[81], character; 86 C ProcRAMs with SOLUTIONS inte; 0; printf(“Enter text, Press at end”); do { charcter=getchar(); line[e}=character; oy ) while(character!="\n’); cel; line{e}="0"; printit"\n%sin”, line); } Outp Enter text.press at end 24. Write a program to copy one string into another and count the number of characters copied, Hinclude ‘finclude void main) { cchar string! [80], string2[80}; inti; printf(“Enter a stringin printf“2"); seanf{*%s, string2"); for(i-O; string2[i}!="\0"s i++) string] [iJ-string2i); stringl[iJ-"0"; printf"n"); FUNDAMENTALS—C. PROGRAMS printi(“%s\n", stringl); printf(“number of charcters = % } Output: Enter a string 2 Manchester Manchester Number of characters=10 Enter a string 2westminister Westiminister Number of charactes 5. Program for printing of the alphabet set in decimal and character form. tiinclude include void main() { char ¢; printf(“tnin”); for(e-65; e122; c=e+1) { iNe>908&e<97) continue; printiYodd-Yoc", cc); } printf(*o"); } Outp: [65-A[66-B]67-C]68-DI69-E|70-F 87 88 —_C PROGRAMS WITH SOLUTIONS (71-G[72-H]73-1|74-J|75-K|76-L [77-MI78-N}79-O[80-P)81-Q)82-R [83-S]84-T]85-U]86-V|87-W88-X [89-Y[90-]97-]98-Bpp9-Clloo-d NO1-<{102-f103-s[104-0]1055}106, 1107-K{108-1]109-m110-nfL11-0f112-p 11S 4115-16-11 7-uft 18-7 [119 20-xf121-y[122-2] 26. Program to concatenation of strings. +inelude #include void main) ‘ inti,j.ks char first_name[10]=(ANANDA}; char second_namef10}={MURUGAN}; char last_name[10] = {SELVARAJ}; char name(30]; for(i; frst_namefi]!="\0"; +4) name rst_namefil; nnameliJ=""s for(j-0; second _name{j]!=! si name[i*j+1}-second_nameljl; namelisit 5 for(k=0; last _name{k] name[ittk+2]="0"; printf(“nin"); printf(“%sin", name); } INO k++) utp: ANANDA MURUGAN SELVARAJ FUNDAMENTALS—C. PROGRAMS 27. Program to illustration of string handling functions. ¥inelude ¥inelude include void maing { char s1 (20), s2[20}, s3[20]; mx 11285 printi(‘enter two string constants”); printit"?"); scanit%s %s", S182); xe stromp(s $2); iffx!-0) { printistrings are not equal"); streat(sl, 82); } else print(*strings are equal”); stropy(s3.s 1); sstelen(s1); I2=strlen(s2); LB=stren(s3); printf("s1=%s length =%d characters”, s1); printi('s2=%s length ~%d characters”, 52,12); printit's3=%s length “Yd characters", 83,13); ‘Output: Enter two string constants amanda murugan Strings are not equal s ‘ananda murugan length=13 characters 89 90 C ProcRAMs WITH SOLUTIONS S2=murugan length=7 characters 3-ananda murugan length=13 characters Enter two string constants anand anand Strings are equal s $2=anand length=5_ characters wand Iength=5 characters ‘S3anand length=5 characters 28. Write a program that would sort a list of names in alphabetical order. #include ‘finclude ‘define ITEMS 5 define MAXCHAR 20 void main() { char string(ITEMS][MAXCHAR], dummy[MAXCHAR]; inti-0,j-0; printf(“enter names of %d items”, ITEMS); while(i0) { strepy(dummy, stringlj-1]); strepy(stringli-1),stingLi); strepy(string{j}, dummy); ) 3 } FUNDAMENTALS—C PRrocRAMs 91 printf(“alphabetical list”) for(i=0; i ifinclude void main) { char linc(81], ctr: int i, e, end=0, characters =O, words=O. lines=0; printf(“KEY IN THE TEXT"); print{("“GIVE ONE SPACE AFTER EACH WORD WHEN COMPLETED, PRESS. RETURN"); while(end==0) { 0; while((ctr=getchar()) line[o++ ctr: line[e]="0"; 92 — C PRocRAMs witl SoLuTioNs i break; alse { words++; for(i-0;linefi]!="0"; i+) iflinefi] = =" * | line{i] == “\v) words++; } linestines+1; characters characters + strlen(line); printf"n"); printf(“number of lines=%d", lines); printi(“number of words=%d", words); printf(“number of characters=%d", characters); } ‘Output: KEY IN THE TEXT GIVE ONE SPACE AFTER EACH WORD WHEN COMPLETED, PRESS RETURN Admiration is a very short-lived passion. Admiration involves a glorious obliquity of vision Always we like those who admire us but we do not like those whom we admire, Fools admire, but men of sense approve Number of lines=4 ‘Number of words=36 Number of characters205 30, Program to alphabetize @ customer list. ‘Winelude #inelude FUNDAMENTALS—C PRrocraMs 93 ‘Hdefine CUSTOMERS 10 void main { cchar first_name[20] [10], second_name[20][10], surname[20][10], name{20](20}, telephone[20][10], dummy[20]; inti printi(“input names and telephone numbers”); print) {fox(i=0; CUSTOMERS; i++) t seantl'tes %s %8 %s",firs|_nameli, second_namefi), surname, telephoneli}s steepy(name(i}, sumamel)); steca(nameil, "95 durmmy{0}=first_namefi}(0}; dummy streat(namefi), dummy); strcatinameli, "9s dammy{0}-second_namefil(0} dummy(1]="0"; streat(namei), dummy); ) forli-1; i<-CUSTOMERS-1; iH) for(=1; “CUSTOMERS -i; +4) ifltremp(namefj-1], namefj))>0) t strepy(dummy, namel-1 steepy(namelj-, namelj) steepy(namelj}, dummy); strepy (dummy, tlephonel-t)); stecpy(telephone(j-1, telephone) strepy(telephone{j), dummy); 3 printf(“CUSTOMERS LIST IN ALPHABETICAL ORDER"); 94 — C ProcRAMs wiTl SOLUTIONS for(i-0; ic CUSTOMERS; i++) print"%-20sit%10 } *, name{i),telephone[i); Output: Input names and telephone numbers anandamuragan 9486153102 Renukadevi 9486644542 CUSTOMERS LIST IN ALPHABETICAL ORDER anandamurugan 9486153102 Renukadevi 9486644542 3 | Program for functions with no arguments and no return values Hinclude ‘Winclude void printiine(void); void value (void); void main) { printline(); valueQ; printlined; } void printline(void) printf”, printf"n"); } void value(void) { int year, period; FUNDAMENTALS—C. PROGRAMS float inrate, sum, principal; printf seanft%t”, &principal); rincipal amount?"); printf(“interest rate?"); scant", Sinrate); printi(“period?”) scanf('%od”, &period) sum-prin year=I; ‘pal; while(year<=period) { sum=sum*(I+inrate); year=year+1; ) print"in’68.2F %5.2F %Sd %12.2fn", principal, inrate, period, sum); ) ‘Output: Principal amount? 5000 Interest rate? 0.12 Period? 5 5000.00 0.2 5 88171 95 32. Program for functions with arguments but no retum values. ‘Hinclude include void printline(charc); ‘void value (float, float, int); void main) { 96 C PROGRAMS WITH SOLUTIONS float principal, inrate; int period; print{(“Enter principal amount, interest”); printf(“rate and period”); seanf("%6f Yt %d”, & principal, &inrate, &period); printline(‘e"); 3 void printline(char ch) { inti fort iHLsi<=5251+) printf("%e", ch); printi(‘in"); , void value({oat p, float, int n) { int year, float sum; sum=p; year=1; while(year==n) { sum=sum*(141}; year=yeart 1; ) printi(“votityoft%detin”, p, rn,sum); ‘Output: Enter principal amount, interest rate, and period 5000.12 5 ULULELLLLLLLL LULULULLULELLLLILELL, 5000,000000 0120000 $8811, 708984 FUNDAMENTALS—C PROGRAMS 97 33. Program for functions with arguments and return values. finclude Hinelude void printline(char ch, inten); value (float, float, int); void maing) { float principal, inrate, amount; int period: prini(“enter principal amount, int est") printf(“rate, and period”); seantl"%I%2t%x printline, » &eprincipal, &inrate, &period); : amount-value(prinipal,inrate, period; printitn%ferstwrotiedt6finin”, principal, inate, period, amount); printtine(; ) void printline(charch, inten) ‘ inti; for(i 1; len; printt“%4e",ch); printf("n"); } value(flotp, float, int m) { int year float sum; sump; vyear=l; while(year<=n) { Sum=sum*(I+2}; 98 C ProcRAMs with SOLUTIONS vyear=yeartl; } return(sum); ) Output: Enter principal amount, interest rate, and period 5000 0.12 $ '5000,000000 0.120000 5 8811.00 34, Write a function power that computes x raised to the power y for integers x and y and returns double-type value, include #nctude void maing { intxys double power (nt, int); printitentorxy:") seant("%d%id", 8,8); print{(“%ed to power %d is %f", x,y, power (x,y));, ) Aouble power (int x, nt y { PA10; ity) while) pis se wher) pox: returm(p) 3 FUNDAMENTALS—C PROGRAMS 99. Output: Enterxy:16 2 16 to power 2 is 256.000000 Enter xy : 16-2 16 to power -2is 0.003906 35. Write a program to show how user-defined funetion is called, finclude ‘finelude voidmain { int, y-2.25, addi); printf("2-%d", 2); add(a,b); ‘ return(atb); 36, Write a program to define user-defined function. Call them at different places. Hinelude +inelude void y0s voidy() { printit"Y"); void maing { 100 C PROGRAMS WITH SOLUTIONS void a0, BO, €0, 40: return) celrser(); y0s a); bos 05 05 ) void ad) ( printi(“A"); y0s ) void ( printfi“B”); a); ) void c() { a0; 60: print } void 0 ( printf(“D"); 03 bO: aQs ) Output: YAYBAYAYBAYCDAYBAYCBAYAY, FUNDAMENTALS—C Procrams 101 37. Write @ program to show how similar variable names can be used in different functions. include #include void main() ‘ int b=10, = return; print{("In main) B=Y%d_ C=¥6d”, be); fan; 3 fund) ‘ int b=20, 10; printi(“In fun() B=%d c=%d", b,c); 3 Output: In main() B=10 eS In fun() B=20 e=10 38, Write a program to show the effect of global variables on different functions. include Hinelude intb=10,¢=5; void main) { clrser(); print(“In main ( funds be print(“Again In main () B=%d e=6a", be); } fund 102 C PRocams with SoLuTIONs { bee print" In fun () B=¥%d e=%d", be); } Output: In ming B= In fun) BI e-4 Again In main() B=12 e=3 39. Write a program to display message using user-defined function. Winclude #inelude void main() { void message(); message(); } void message() { puts (“Have a nice day”); } ‘Output: Have a nice day 40. Write a program to return more than one value from user defined function. Hinclude ‘Winclude void main() { int x,y, add, sub, change(int*, int, int int*); clrser(; 41. FUNDAMENTALS—C Programs 103 printi(“Enter values of X and ¥:"); seantt%ed %d, Sex, &y) change(&x &y, &add, &sub); print“Addition:%d”, add); printf(“Subtraction:%d’, sub); return 0; ) chango(int* a, int*b, int, int) { c=tatth; sdotath; ) ‘Output: Enter values of x & y:5. 4 ‘Addition: 9 Subiraction:1 Write a program to pass arguments to user-defined function by value and by reference. Hinelude finclude void main) { inky, other, int”, clrser(); print(“Adadress of k&em in main): %ut6u", em); other kéem); return 0; ) cother(int k, int*m) { print(“Address of kéem in other: Yéud6u, kan"); ) 104 C PRocRaMs wiTH SoLuTIONS ‘Output: Address of km in main(): 65524 65522 Address of km in other(): 65518 65522 42, Write a program to return only absolute value like abs() function, ‘Winclude #finclude void main() { int uabs(int), x; clrser(; printf(“enter a negative value:"); scant xeuabs(x)s 6d", x); uabs(int y) ‘ ity) return(y*-1); else return(y); ) Outp Enter a negative value: -5 XS 43. Write a program to calculate square and cube of an entered number. Use function as an argument, ‘Winclude inelude void main() { FUNDAMENTALS—C ProcRams 105 intm; clrser(); printi("Cube: %d”, cubesqrtinputQ)); ) input) { intk; printf("Number.”) printf("Square:%d", m*m);, return m; ) ccube(m) { retum m*m*m; } Output: Number:2 Square: 4 Cube:s 44, Write a program to assign return value of a function to another variable. Hinclude ifinclude void main) { int puttin); intx; clrser(; x=input(x); 106 C PRocRaMs wiTH SoLuTIONs printt=94d" x); } inputintk) ‘ printi(“Enter value of x="); scanft"%d", 8k); return() ‘Output: Enter value of x=5 include include void main() ( int input) int sqr(int); ints clrser(); ssqr(-inpat(s)+1); prith"Square=2%d, x") ' input) ( printt“Enter value of x="); scant, & return(h)s ( sartint m) { FUNDAMENTALS—C PRroGRams 107 retum (pow(m2)); } Output: Enter value of x= Square-9 46. Write a program to perform multiplication and division of numbers with retum value of function ifinclude inelude inelude void maing) { intinputint int sqrtint); ints; elrser(; xesqr(S*input(x)/2) printi(“Square=%d, x"); ) input(intk) { print{(“Enter value of: seantt"%d, &K"}; return(k); { sqr(int m) { return (pow(m,2)); } Outp Enter value of x=5 Square=144 108 C PRocRams WITH SOLUTIONS 47. Write a program to use (+++) operator with return value of funetion. include #include ifinelude void main) { intinputin) int sqr(int); ititxy “0; clrser(); resqrey-Cinput(a)))); printf(“Squar 5 } inputGinek) { print(“Enter value of x"); scantt"%d", 8); return; ) sqr(itm) { return (pow(m,2)); } utp: Enter value of x=7 Square~64 48, Write a program to use mod(%) with function, ifinclude #include void main { inti0; ifhj0% FUNDAMENTALS—C PROGRAMS print(’Number is even"); else print(“Number is odd”); return 0; ) io { ints; elrser(); printi(“Enter a number"); 8°, 8x); return(x); ) ‘Output: scanf(" Enter a number:5 Number is odd 49. Write a program to evaluate the equation s=sqr(a()#b() using function. finclude #include void main) t int s-0, a0, bO,sqrtint); lrser()s s-sqr(aQ#0): printf(“square of sum=%d”, 8) retum 05 ) a0) { inta; printf(“Enter value of 2”); seanf{"%d", 8a}; return(a); 109 110 C Procrams with SoLuTioNs int; printf(“Enter value of b:"); scanf{“%d”, &b); return(b); ) sar(int x) { return(x*x); ) Output: Enter value of 2:5 Enter value of b: 3 Square of sum=64 50, Write a program to call user-defined function through if statement. #ineludesstdio.h> #inelude void main() ‘ int a0; clrser(); if{aQ%42= ~0) printi(“The number is even"); else printi(“The number is odd”); } 20 { inta; print{(“Enter value of a:"); FUNDAMENTALS—C PROGRAMS scanf"%od" fea): retum(a): ‘Output: Enter value of a:5 ‘The number is odd 81. Write a program to call user-defined function through switch) statement ‘include include ‘inelude Hinclude void main) { int ad; intx=5; elrser(): switeh(a()) { case's’: printf("Square of %d is ® break; printi(“Cube of %d is Yad", x, pow(x,3)); break; case’d printi(“Double of Yad is Yd", x, x*2); break; default printf("Unexpected choice printed as it is : %d”, x); ) ) a0) ‘ char e~"e 1, x, pow(x,2)); i 112 C PRocrams with SoLuTIONs printf(“Enter your choice square(s), cube(c), double(d) tche(); emtolower(); return(e); } utp: Enter your choice squares), cube(c), double (d):D Double of Sis 10 52, Write a program to call function through the for loop. ifinclude Winclude ‘include void main) { int plus(int), m=1; celrser(; for(; plus(m); m+) { printf("%3 ) } plus (int k) { ik =10) { exit(1); return NULL: } else returm(k); ) Output: 123456789 4 C DEBUGGING Chapter Find the output or error(s) for the following Programs: 1. void main { int const * p=S; printit'%d"-+C*p } Answer: Compiler error: Cannot modify a constant value. Explanation: p is a pointer to a “constant integer”. But we tried to change the value of the “constant integer”. 2. maid) { char sf J+"man"; intis forti=O:s[ i hi++) prinutn%evecvev%e" sl i |As#i.*(s)i[sDs ) Answer Explanation: sfil, *(i*8), *(sHi), ifs] are all different ways of expressing the same idea. Generally array ‘name isthe base address for that array. Here s is the base address. iis the index number' displacement 13 114 C ProcRams with SoLuTioNs from the base address. So, indirecting it with * is same as si). ifs] may be surprising. But in the case of C itis same as sli] 3. main( { float me= 1 double you= 1.1; iftme—you) printf love Us else printit“I hate U"); Answer: Thate U Explanation: For floating point numbers (float, double, long double) the values cannot be predicted exactly. Depending on the number of bytes, the procession with of the value represented varies, Float takes 4 bytes and long double takes 10 bytes. So float stores 0.9 with less precision than long double. Rule of Thumb: ‘Never compate or at operators (=, >, <, <=, >= east be cautious when using floating point numbers with relational 4. main) { static int var = 5; printf(“%d "var; iffvar) mains } Answer: 54321 Explanation: When static storage class is given, itis initialized once. The change in the value ofa static variable is retained even between the function calls. Main is also treated like any other ordinary function, which can be called recursively. 5. main) { int ef 7 2.8,3.4,4,6.7,5}; C Desuccinc 5 intip-eteres fortF=Oj14, NOT (!) operator has more precedence than * >" symbol. ! is a unary logical operator. fi (110) is 0 (not of true is false). 0>14 is false (zero). 15. #include main) { C Desuccinc 119 char s[J={'a","b''e7"in'*e° M0}; char *p,*str*str1; p=&s[3}; stp; sirl=s; print h% ++tstr1-32); } Answer: n Explanation: pis pointing to character “in. stl is pointing to character ‘a’ +p. “pis pointing to “in and thats incremented by one.” the ASCII value of *n" is 10, which is then incremented to 11. The value of Hp is 1. +44str str is pointing toa" thats incremented by 1 and itbecomes‘b'. ASCH value of’ is 98 Now performing (11 + 98 ~ 32), we get 770°M"); So we get the output 77 :“M" (ASCILis 77) 16. #include maing { nt [22112] = {10.2,3.4}, {5,6.7.8) int *p.ta; -a{2][2112]; ‘SomeGarbageValue~ Explanation: p=8&a[2][2][2] you declare only two 2D arrays, but you are trying to access the third 2D (which you are not declared) it will print garbage values. *q=***a starting address of ais assigned integer pointer. Now q is pointing to starting address of a. Ifyou print *q, it will print first element of 3D array. 17. Hinclude ‘maing) { 120 C ProcRams with SoLuTioNs struct xx { int char name{}>"hello”; b struct xx *s printt“%6d".s>x); printf(“%s”.s->name) } Answer! Compiler Error Explanation: You should not initialize variables in declaration 18, #include main { struct xx int; struct yy { char s; struct xx *p; b struct yy *q5 } Answer: Compiler Error Explanation: ‘The structure yy is nested within structure xx. Hence, the elements are of yy are to be accessed through the instance of structure xx, which needs an instance of yy to be known. If the instance is created afler defining the structure the compiler will not know about the instance relative to xx. Hence for nested structure yy you have to declare member. C Desuccinc = 121 19. main() { print(*inab”) printf printfa”); ) Answer: hai Explanation: \n - newline Ab = backspace \v - linefeed 20, main() { inti-s; print ZadYodrodedVodYid ie tins; ) Answer 45545 Explanation: ‘The arguments in a function call are pushed into the stack from left to right, The evaluation is by popping out from the stack and the evaluation is from right to lef, hence the result 21. Hdefine square(x) xx maing) { itis i= 64isquare(4); printed"; d Answer: o Explanation: The macro call square(4) will substituted by 4*4 so the expression becomes i = 64/4*4. Since / and * has equal priority the expression will be evaluated as (64/4)*4 ie,, 16%4 = 64, 122 C PRocRaMs with SoLuTioNs 22, main() { char *p="hai friends”,*p1; pl-p: while(*p!="\0") Hh, printh(%s %s";p,pl)s , Answer: ibjlesioet Explanation: ++#p++ will be parse in the given order > *p that is value atthe location currently pointed by p will be taken > Hp the retrieved value will be incremented > when ; is encountered the location will be incremented that is p++ will be executed Hence, in the while loop initial value pointed by pis “h’, which is changed to “’ by executing |p and pointer moves to point, ‘a” which is similarly changed to *b’ and so on. Similarly blank space is converted to *", Thus, we obtain value in p becomes “ibj!gsjfoet” and since p reaches “\0" and pl points to p thus pl does not print anything. 23, #inelude define a 10 ‘main { Aefine a 50 printh%d",a) 3 Answer: 50 Explanation: The preprocessor directives can he redefined anywhere in the program, So the most recently assigned value will be taken 24, define clrser() 100 ‘main { C Desuccinc 123 clrserQ; printf(%adin'clrsen()); ) Answer: 100 Explanation: Preprocessor executes as a seperate pass before the execution of the compiler. So textual replacement of clrser() to 100 oceurs. The input program to compiler looks like this: main) { 100; printf("%din”, 100); Note: 100; is an executable statement but with no action, So it doesn’t give any problem. 25. main() { print{(“%p" main); ) Answer Some address will be printed. Explanation: Funetion names are just addresses (just like array names are addresses) ‘main() is also a function. So the address of function main will be printed, %p in print specifies that the argument is an address. They are printed as hexadecimal numbers, 26, main() { clrser(); elrser(; Answer No outputlertor 124 — C PRocRaMs with SoLuTIONs Explanation: ‘The first clrser() occurs inside a function. So it becomes a function call. In the second clrser(}; isa function declaration (because it is not inside any function), 27. cnum colors (BLACK.BLUE,GREEN} ‘main { printf(“¢6d..%d..%6d",BLACK,BLUE,GREEN); return(1);, ) Answer: 0.1.2 Explanation: ‘num assigns numbers starting from 0, if not explicitly defined, 28. void main) { cchar far *farther,*farthest; %d.. od” sizeof farther).sizeofl farthest) Explanation: The second pointer is of char type and not a far pointer. 29, main() { int i=400,=300: prints("%d..%od! } Answer! 400..300 Explanation: printf takes the values of the first two assignments of the program. Any number of printt’s ‘may be given, All of them take only the first two values, If more number of assignments «given in the program, then printf will take garbage values. C Desuccinc = 125 30. maind) { char *p; pe"llello”; printf("%ocln",*84p); Answer: H Explanation: * is a dereference operator & is a reference operator. They can be applied any number of times provided itis meaningful. Here p points to the first character inthe string “Hello”, *p dereferences it and so its value is H, Again & references it to an address and * der itto the value H. 31. main) printit% if (2) goto here; my ) ) fund) { here print("PP } Answer: Compiler error: Undefined label ‘here" in function main, Explanation: Labels have functions scope, in other words the scope of the labels is limited to functions ‘The label “here” is available in function fn) hence itis not visible in function main, 126 C PRocRaMs wiTH SoLuTIONS 32. main() { static char names{5][20]={*pascal”, “ada”, “cobol”,*fortran”,*per!”}; inti char *t; ‘=names[3]; ‘names[3}-names( 4]; ames|4]=t; For (i-Osicmdsit+) printf(%s”,namesfi)); ) Answer Compiler error: Lvalue required in funetion main Explanation: Array names are pointer constants, So it cannot be modified. 33. void main) { intiv$ printh'%od"it+ +++); ) Answer: Output Cannot be predicted exactly. Explanatio Side effects are involved in the evaluation of i 34. void main { inti-s; printh(“%d"i+++—+); ) Answer: Compiler Error Explanation: ‘The expression i+++++ is parsed asi ++ ++i which is an illegal combination of operators, 35. 36. a7. C Desuccinc = 127 ‘Winclude main) { inti 1-2; switeh(i) { cease |: printi"GOOD"); break; case js printit"BAD”); break; } ) Answer: Compiler Error: Constant expression required in function main, Explanation: The case statement can have only constant expressions (this implies that we cannot use variable names directly so an error), Note: Enumerated types can be used in case statements. ‘main { itis printf(“%d",scanft"%d",d)); /! value 10 is given as input here } Answer: 1 Explanation: Scanf retums number of items successfully read and not 1/0. Here 10 is given as input which should have been scanned successfully. So number of items read is 1 Hidefine flg,g2) gife2 ‘main() { int var12=100; 128 38. 39. C PROGRAMS WITH SOLUTIONS rine" *flvar,12)); Answer: 100 main) { inti-o; fon(sit+sprintt("%d",i) printi("%d”,i; d Answer: 1 Explanation: Before entering into the for loop the checking condition is “evaluated”. Here it evaluates to 0 (false) and comes out of the loop, and iis incremented (note the semicolon after the for loop). Hinelude ‘main() { char s[]-{‘a’,"b’,‘c"\n’,°c", 10°}; char *p,ts,*stl; p-as(3} su=p; strl=s; print -44p + -+4st1-32); ) Answer: M Explanation: P is pointing to character “wr is pointing to character ‘a -+44p meAnswer:“p is pointing to “in’ and thats incremented by one.” the ASCII value of “nis 10. Then it is incremented to 1. The value of +p is [1, +s meAnswerstl is pointing to “a that is incremented by 1 and it becomes “b. ASCII value of * is 98. both 11 and 98 is added and resul is subtracted from 32 Le, (114+98-32)=770M");, C Desuccinc = 129 40. #include ‘main { struct xx ‘ int x3; char name||=“hello”; } struct xx *s=malloc(sizeofistruct 0); printf("%od"s>x); print{(“%s" s->name}; ) Answer: Compiler Enror Explanation: Initialization should not be done for structure members inside the structure declaration 41. #includestdio.h> ‘main() struct xx ‘ intx; struct yy { char s; struct xx *p; } struct yy *q; } } Answer: Compiler Error Explanation: In the end of nested structure yy a member have to be declared. 130 42. 4B. 44, C PROGRAMS WITH SOLUTIONS main() { extem inti 20; print%6d” sizeof); ) Answer Linker error: undefined symbol Explanation: exten declaration specifies that the variable iis defined somewhere else. The compiler passes the external variable to be resolved by the linker. So compiler doesn’t find an error. During linking the linker searches for the definition of i Since itis not found the linker flags an error. main() { rintf("%d”, out); } int out=100; Answer: Compiler error: undefined symbol out in function main, Explanation: The rule is that a variable is available for use from the point of declaration, Even though a is a global variable, itis not available for main. Hence an error. ‘main t exten out; printi("%d", out: ) int out=100; Answer! 100 Explanation: This is the correct way of writing the previous program, C Desuccinc 131 45, main) { show(); } void show0) { printf(“I'm the greatest”); ) Answer: Compier error: Type mismatch in redeclaration of show. Explanation: ‘When the compiler sees the function show it doesn’t know anything about it. So the default rotum type (i, int) is assumed. But when compiler sees the actual definition of show mismatch occurs since it is declared as void, Hence the error, The solutions are as follows: 1, declare void show) in main. 2, define show() before main0), 3. declare extern void show() before the use of show0). 46. main() { intal2](3]21= ((12,4 (78) 84) (22}423) 84115 printt"%u %u Yu Md na, printf%u 9ou Yau %d \w"atl *at],**at],***a41); sea.thtay, } Answer: 100, 100, 100,2 114, 104, 102,3 Explanation: ‘The given array is a 3-D one, It can also be viewed as a I-D array. 2]4][7[s[3f4]2]2][2]3]3]4 100 102 104 106 108 110 112 14 16 8 120 122 thus, for the first printf statement a, *a, **a give address of first element since the indirection ***a gives the value. Hence, the first line of the output. 132 C PRocRaMs wiTH SoLuTIONS for the second printf a1 increases in the third dimension thus points to value at 114, **a+1 increments in second dimension thus points to 104, *¥a +1 inerements the first dimension thus points to 102 and ***a41 first gets the value at first location and then increments it by 1. Hence, the output. 47. main() t inta{] = (10,20,30,40,50) j,*P: for()=0; <5; +4) ‘ printit“%od forlj=0; <5; +4) ‘ printf(“%d” *p); pe ) } Answer: Compiler error: Ivalue required, Explanation: Error is in line with statement a++, The operand must be an Ivalue and may be of any of scalar type for the any operator, artay name only when subscripted is an Ivalue. ‘Simply array name is a non-modifiable Wwalue. 48. main() ‘ statie int af] ~ {0,1,2,3,4); int *pl]= faa*Lat2a3ah); int pir pire; primftin %d %d %d”, ptrp, *ptr-a, **ptr); Spies; printf(“in %d %d %d”, ptrp, *ptra, **ptr); C Desuccinc 133 sepa: printf(“n %d %d %d", ptrp, *ptr-a, **ptr); ptr: printt"n %od %d %d”, ptr-p, *ptr-a, **ptr); } Answer: ul 22 333 444 Explanation: Let us consider the array and the two pointers with some address a oli f2[3]« 100 102 104106108 » 100 | 102] 104 | 106 | 108 1000 1002 1004 1006 1008 ptr 1000 2000 After execution of the instruction ptr++ value in ptr becomes 1002, if scaling factor for integer is 2 bytes. Now ptr —p is value in pir— starting location of array p, (1002 ~ 1000) / (scaling factor) = 1, *ptr—a-= value at address pointed by ptr ~ starting value of array a, 1002 has a value 102 so the value is (102 - 100)/(scaling factor) = 1, **ptr is the value stored in the location pointed by the pointer of ptr= value pointed by value pointed by 1002 = value pointed by 102 = 1. Hence the ‘output of the firs printf is 1, 1,1 After execution of *ptr+ increments value of the value in ptr by scaling factor, so it becomes1004. Hence, the outputs for the second printf are ptr ~ p= 2, *ptr—a=2, **ptr= 2. After execution of *++ptr increments value of the value in ptr by scaling factor, so it becomes1004. Hence, the outputs for the third printf are ptr—p =3, *ptr—a=3, **ptr =3, After execution of +44ptr value in ptr remains the same, the value pointed by the value is ineremented by the scaling factor. So the value in array p at location 1006 changes from 106 10 108, Hence, the outputs for the fourth printf are ptr — p= 1006 - 1000 =3, *ptr—a= 108 — 100=4, **ptr 4 134 C PRocRaMs WITH SOLUTIONS 49. main) ‘we keep writing over in the sam { char int js for (j-0; j<3; j++) seantt%s” (a+); for G0; j<3; 5-4) printi(“%e" *(q+); for (HO; 5<3; j++) printht"%s" (qr): ) Explanation: Here we have only one pointer to type char and since we take input in the same pointer thus location, each time shifting the pointer value by 1. Suppose the inputs are MOUSE, TRACK and VIRTUAL. Then for the first input suppose the pointer starts at location 100 then the input one is stored as, 50. mio|lu]s|e|wo mi/tfrR{ale|]«] ‘The third input stars filling from the location 102 mMi{tf vj] of re{r]ufa}e fo This is the final value stored. ‘The first printf prints the values at the position q, q+1 and q+2 =M TV ‘The second printf prints three strings starting from locations q, q+, q*2 ie, MTVIRTUAL, TVIRTUAL and VIRTUAL, main() { void "vp: char ch = ‘g’, *ep = “goofy”; intj=20; yp = &ch; prineft“9 vp = &is print %ad",*(ine *)vp); vp= ep; "(char *\vp); When the second input is given the pointer is incremented as j value becomes 1, so the input is filled in memory starting from 101 C Desuccinc 135 printf("%4s” (char "wp + 3); ) Answer: e20ly Explanation: Since a void pointer is used it can be type casted to any other type pointer. vp = &ch stores address of char ch and the next statement prints the value stored in vp after type casting it to the proper datatype pointer: the output is ‘g’. Similarly the output from second printf ‘20”, The third print statement type casts it to print the string from the 4* value hence the output is “fy” SI. main () { static char *s[] = {“black”, “white”, “yellow” char **ptr[ ]= (8-3, +2, s#1, 8}, **p; p= ptr ot: printh(%s",*--*+4p +3); } Answer: ck Explanation: “violet"};, In this problem we have an array of char pointers pointing to start of 4 strings. Then we have ptr which isa pointer toa pointer of type char and a variable p which is a pointer to a pointer of type char p hold the initial value of ptr, ie., p= $3, The next statement increment value in p by 1, thus now value of p= s#2. In the printf statement the expression is evaluated *--+p causes gets value s#1 then the pre decrement is executed and we get s+l — 1 = the indirection operator now gets the value from the array of's and adds 3 to the starting address. The string is printed starting from this, position, Thus, the output is ‘ck’, 52. main) { int i,m; char *x =“git’ = stlen(e; *x= xin for(i=0; fen; ++i) 136 C PRocRaMs with SoLuTIONs ( printi%sin".x); } } Answer: (blank space) id a 1 Explanation: Here a string (a pointer to cha) is initialized with a value “git”. The strlen funetion retums the length of the string, thus n has a value 4, ‘The next statement assigns value at the nth location (10°) to the first location. Now the string becomes “Oi”. Now the printf statement prints the sting after cach iteration it increments it starting position. Loop starts from 0 to 4 The first time x[0] = "0" hence i prints nothing and pointer value is incremented. The second time it prints from x{1] i. “il and the third time it prints “I” and the last time it prints “and the loop terminates. 53. intijs fon(i-Oi<=105+4), { i assert(i<5); ) Answer: Runtime error: Abnormal program termination, assert failed (i<5), “file name>, Explanation: Asserts are used during debugging to make sure that certain conditions are satisfied. If assertion fails, the program will terminate reporting the same, After debugging use, #undef NDEBUG and this will disable all the assertions from the source code. Assertion is a good debugging tool to make use of. 54, main() { inti; 58. 56. 57. 58. C Desuccinc 137 printf("i=Y%d, +1=%d in", ti) Explanation: Unary + is the only dummy operator in C. Where-ever it comes you can just ignore it Jjust because it has no effect in the expressions (hence the name dummy operator) ‘What are the files which are automatically opened when a C file is executed? Answer: sidin, stdout, stderr (standard input,standard output standard error), What will be the position of the file marker? a: fseck(ptr,0,SEEK_SET); bs: feeck(ptr, Answer! a: The SEEK, SET sets the file position marker to the starting of the file. bb: The SEEK_CUR sets the file position marker to the current position of the file. ‘main { char name[10}.s[12]; OED 8) scant ) How scanf will execute? Answer: First it checks for the leading white space and discards it,Then it matches with a quotation mark and then it reads all character upto another quotation mark. ‘What is the problem with the following code segment? while ((fgets(receiving array, 50, fle_ptr)) != EOF); Answer & Explanation: {gets retus a pointer, So the correct end of file check is checking for != NULL. 138 C PRocRaMs wiTH SOLUTIONS 59. main) { main; Answer: Runtime error : Stack overflow. Explanation: ‘main function calls itself again and again. Each time the function is called its return address is stored in the call stack. Since there is no condition to terminate the function call, the cal stack overflows at runtime. So it terminates the program and results in an 60. main) { char *eptrc; void *yptrv; e=10; 0; epu=Be; vpl=&v; printi(“Yoc%v".e,v) ) Answer: Compiler error (at line number 4): size of v is Unknown, Explanation: You can create a variable of type void * but not of type void, since void is an empty type. In the second line you are creating variable vptr of type void * and v of type void hence an error. 61. main) { ‘chat *str1="abed”; ‘char st2{]>“abed”; printi("Yed Yd %d" sizeot{strl),sizeof{ste2) sizeoft“abed”)); Answer: 255 C Desuccinc 139 Explanation: In first sizeof, stl is a character pointer soit gives you the size ofthe pointer variable. Insecond sizeof the name str2 indicates the name of the array whose size is 5 (including the 0" termination character) The third sizeo i similar to the second one. 62, main) { char not; not=!2; print ) Answer: 0 Explanatio 1 isa logical operator. In C the value 0 is considered to be the boolean value FALSE and any non-zero value is considered to be the boolean value TRUE. Here 2 is a non- zero value so TRUE, !TRUE is FALSE (0) so it prints 0. “mot 63. #fdofine FALSE -1 #idefine TRUE 1 ¥define NULL 0 rmain() { NULL) puts("NULL"); else iRFALSE) puts¢“TRUE"); else puts(“FALSE” } Answer: TRUE Explanation: The input program to the compiler afler processing by the preprocessor is, main({ ino) puts(*NULL"); 140 C ProcRaMs with SoLuTIONs else if-1) puts(“TRUE") else puts(*FAL ) Preprocessor doesn’t replace the values given inside the double quotes. The check by iffcondition is boolean value false soit goes to else, In second if-1 is boolean value true hence “TRUE” is printed. 64, main() { intk=1; printt“%d—1 is *TRUE*"FALSE"); } Answer: 11 is TRUE Explanation: When two strings are placed together (or separated by white-space) they are concatenated (ths is called as “stringization” operation). So the string i sift is given as “Y%d—=1 is %s", The conditional operator(?: ) evaluates to “TRUE”. 65. main) { imtys scang{*%d", fey); input given is 2000 if (Y%A=0 && y%100 = 0) | y%100 = 0) print%6d is a leap year"); else printi("%6d is not a leap year"); ) Answer: 2000 is leap year Explanation: ‘An ordinary program to check if leap year or not. C Desuccinc = 141 6. #define max 5 ‘define int arel[max} main() ‘ typedef char an2{max]; art ist=(0,1,2,3.4}5 ar nam printf(“%od %s"list[0].name); } Answer! Compiler error (in the line aI list= {0,1,2,3,4}) Explanation: an? is declared of type array of size 5 of characters, So it can be used to declare the variable name of the type arr2. But it is not the case of arrl. Hence an error. Rule of Thumb: ‘defines are used for textual replacement whereas typedef are used for declaring, new types. 67. inti=10; ‘main { exter inti; { int 20; { const volatile unsigned i prine%ed i), } printi(“%d”,i; ) printed"); } Answer! 30,20,10 Explanation: “(7 introduces new block and thus new scope. In the innermost block iis declared as, const volatile unsigned, 142 C PRocRaMs wiTH SoLuTIONS ‘which is a valid declaration. i is assumed of type int. So printf prints 30. In the next block, i has value 20 and so printf prints 20, In the outermost block, i is declared as extem, so no storage space is allocated for it, After compilation is over the linker resolves it to global variable i (since itis the only variable visible there). So it prints i's value as 10. 68, main) { int { int i=10; Rais } printf(“%d",*j) Answer: 10 Explanation: ‘The variable iis a block level variable and the visibility is inside that block only. But the lifetime of iis lifetime of the function soit lives upto the exit of main function. Since the {is sil allocated space, *j prints the value stored ini since j points i 69, main) print" = Yd, -i= Yd "sis } Answer: Explanatio iis executed and this execution doesn’t affect the value of i, In printf first you just print the value of i, After that the value of the expression -i = -(-1) is printed. 70. #include ‘main C Desuccinc 143 { const int i=4; float js jets printt(%od %f i-4i)s 4 Answer Compiler error Explanation: ‘iis a constant. You cannot change the value of constant. 71. Hinelude ‘main { int af2][212]= { (10,2,3,4}, (5,6,7,8} Js int *p.*a; pseal2](2112I5 printt(%od..%6d",*p.% } Answer: garbagevalue..1 Explanation: pr&al2](2][2] you declare only two 2D arrays but you are trying to access the third 2Diwhich you are not declared) it will print garbage values, *q=**%a starting address of ais assigned integer pointer now q is pointing to staring address of aif you print *q ‘meAnswer:t will print first element of 3D array. 72, #include main() t rogiste char jf)= “hello”; printf(“%s %d" j,i); 144 2. 74. C PROGRAMS WITH SOLUTIONS Answer: hello Explanation: If you declare i as register compiler will treat it as ordinary integer and it will take integer value. i value may be stored cither in register or in memory. ‘main { inti-Sj-6.25, printh(“%d".i-H4)); } Answer: nL Explanation: The expression i++ is treated as (- struct aaa{ struct aaa *prev; ints struct aga *next; % main() ‘ struet aaa abe,def.ghijkl; intx=100; abe.i-O;abe.prev-&jk; abomext&def; defi=1;def prev=Babe;definext=Sghi; ghi.i-2;ghi prev-&edef; shimext=8jkl; jkLi+3gkl.prev=Qghijkl next=Babe; xeabennext>next=prev->nextis printt“%d"x); } 76. C Desuccinc = 145 Answer: 2 Explanation: Above all statements form a double circular linked list; abe.next->next->prev->next->i ‘this one points to “ghi” node the value of at particular node is 2. struct point ¢ int; ity; h strut point orig and ( pp~Aorigin; printf(“origin is(%d%d)in",(*pp).x,(*pp).y)s print“orginis 40%A)0" pp>xppy): ) Answer: origin is(0,0) origin is(0,0) Explanation: pp is a pointer to structure. We can access the elements of the structure either with arrow mark or with indirection operator. Note: Since structure point is globally declared x & y are initialized as zeroes. ‘main() int i+_J_abe(10); printi(“%adin”, i); ) im_L_abetint iy { 146 C ProcRaMs wiTH SoLuTIONs return(i++); Answer: 9 Explanation: roturn(i++) it will first retum i and then increments. ie,, 10 will be returned, 77. main) ‘ char *p; im*q; long *r; p=qr=0; pets as rH printi(“%p...26p..%p"sp.a.0), Answer (0001...0002..0004 Explanation: ++ operator when applied to pointers increments address according to their corresponding data-types. 78. main) { char e=* *x,convert(2); geto(©): if{(e>="a") && (e<='2")) xreonvert(e); printf“%ec" ) convert(2) { return 2-32; ); 79. 80. C Desuccine ) Answer Compiler error. Explanation: Declaration of convert and format of gete() are wrong, ‘main(int arge, char **argv) { printf(“enter the character”); getcharQ; sum(argv[]argv[2): ) surn(num num?) int mum num2; { return num -+num2; ) Answer Compiler error. Explanation: 147 argv[1] & argv[2] are strings. They are passed to the funetion sum without converting it to integer values. #include intone_dl]=(1,23}; main() { int "pte; pirone_ds pirt=3; printfa" ) Answer: pt); garbage value 148 C ProcRaMs wiTH SoLuTIONS Explanation: pir pointer is pointing to out of the amay range of one_d 81. include aad { print“), 3 ‘bbbO{ printthello"; ) ece(}{ printfi“bye”); 3 main() ( int (*ptr[3))0; pir[0}-aaa; ptr(1}=bbb; ptr[2}=cce; ptrl2]0; bye Explanation: ptr is array of pointers to Functions of return type int ptr0] is assigned to address ofthe function aaa. Similarly ptr[1] and ptr[2] for bbb and cce respectively. ptr{2]0 is in effect of writing eced, since ptr{2] points to ece. 82. #include main) { FILE *ptr, char i; ptr-fopen(“zzz.0","1"); 83. 84. C Desuccine while((i=fgetch(ptt)!-EOF) printf“%c".i); ) Answer: contents of 277.¢ followed by an infinite loop. Explanation: The condition is checked against EOF, it should be checked against NULL, ‘main { inti=0;-0; if && J) prineht"%od.%6d i++ printh"%d.%di,); } Answer: 0.0 Explanation: 149 The value of is 0. Since this information is enough to determine the truth value of the boolean expression. So the statement following the if statement is not executed. The values of i and j remain unchanged and get printed. maing) { inti i= abe(); primin“%d"i); ) abet) { AX = 1000; ) Answer: 1000 150 a5. 86. C PROGRAMS WITH SOLUTIONS Explanation: ‘Normally the return value from the function is through the information from the accumulator. Here _AH is the pseudo global variable denoting the accumulator. Hence, the value of the accumulator is set 1000 so the function returns value 1000, inti; main(){ int; for ( t4:scanf"%d”,&i)-printh(%dn”,i)) printft%d-"s-); } Ifthe inputs are 0,1,2,3 find the a/p Answer 40 341 2 Explanation: Let us assume some x= scanf("%d”, fi) the values during execution will be, toi x 40 4 31 2 22 0 main(){ int a= Ojint b= 20;char x =I;char y iffabxy) printt“hello”); , Answe bello Explanation: The comma operator has associativity from left to right. Only the rightmost value is retumed and the other values are evaluated and ignored. Thus the value of last variable y is returned to check in if. Since it is anon zero value if becomes true $0, “hello” will be printed. C Desuccinc 151 87. mainO{ unsigned int; for(i=1:i>-2:i~ printi(“e aptitude”); ) Explanation: { is an unsigned integer. It is compared with a signed value, Since the both types doesn’t match, signed is promoted to unsigned value. The unsigned equivalent of -2 is ‘a huge value so condition becomes false and control comes out of the loop. 88. Inthe following pgm add a stmt inthe function fun such thatthe address of a” gets stored in) main(){ int *j; ‘void fun(int **); fun(&j); ) void fun(int **K) { int /* add a stmt here*/ } Answer *k= ha Explanation: The argument of the function is a pointer to a pointer. 89. What are the following notations of defining functions known as? {int abe(int a,float b) ‘ /* some code *) 3 ii im abe(a,b) int a; float b; ‘ /* some code*/ } 152 90. on. 92. C PROGRAMS WITH SOLUTIONS Answer! i. ANSI C notation ii, Kemighan & Ritche notation. main) { char *p povedin”s pet printitp-2,300); ) Answer: 300 Explanation: The pointer points to % since it is ineremented twice and again decremented by 2, it points to *%din’ and 300 is printed. main) { char a[100); a{O]="a'a[1]"b'al2]-“e'sal4}"as abo(a)s abe(char afD){ aby print(%4e",*a); att printi("%c",*a) , Explanation: The base address is modified only in function and as a resulta points to “b’ then after incrementing to ‘eso be will be printed fane(a.b) int ab; 93. C Desuccinc 153 { return( ) ‘main { int process(),fune() printf(“The value of process is %d !\n ",process(fune,3,6));, ) process(pfvall,val2) int pH Os int all val2; { return((*p0) (vallval2)); } Answer The value of process is 0 ! Explanation: The function ‘process’ has 3 parameters - 1, a pointer to another function 2 and 3, integers. When tis function is invoked from main, the following substitutions for formal parameters take place: fume for pf, 3 for vall and 6 for val2. This function returns the result ofthe operation performed by the function ‘func’. The function func has two integer parameters. The formal parameters are substituted as 3 for a and 6 for b. since 3 is not equal to 6, a~=b returns 0. Therefore the function returns 0 which in tum is retumed by the function ‘process’ void main) { static int i=S; it~ main; prine"%od i); 154 C PRocRaMs wiTH SoLuTIONS Explanation: The variable “I” is declared as static, hence memory for I will be allocated for only once, as it encounters the statement, The function main() will be called recursively unless I becomes equal to 0, and since main() is recursively called, so the value of static Iie,, 0 will be printed every time the control is returned, 94. voidmain) { int k-ret(sizeof{float)); printf(“n here value is %d" +k); } int ret(int ret) { ret += 2.5; retumn(ret); ) Answer! Here value is 7 Explanation: ‘The int retint re, ie, the function name and the argument name can be the same. Firstly, the function ret() is called in which the sizeof{float) ie, 4 is passed, after the first expression the value in ret will be 6, as ret is integer hence the value stored in ret will have implicit type conversion from float to int, The ret is retumed in main() itis printed after and preincrement. 95. void main ‘ char af]="1234500"; intisstrlen(a); print(“here in 3 %din”, +); ) Answer: here in 3 6 Explanatio The chat array ‘a’ will hold the initialized string, whose length will be counted from 0 till the null character. Hence the ‘I’ will hold the value equal to 5, after the pre-increment in the printf statement, the 6 wil be printed C Desuccinc = 155 96. voidmain) { unsigned giveit int gotit; printf(“You”,++giveit); print“%u in’ gotit—givet); } Answer: 065535, Explanation: give it value is incremented. In printf, the value of gotit is the decrement of give it, 97. void main() { iftprintf(“%sin",a)) printf(“Ok here a"); else printi(“Forget tin”); , Answer: Ok here Explanation: printf will return how many characters does it print. Hence printing a null character returns | which makes the if statement truc, thus “Ok here” is printed. 98. void main) { void *¥; int integer~2; int *i-integer; printf(“%od"int*)*V)s ) Answer: Compiler Error. We cannot apply indirection on type void®. 156 C PRocRaMs wiTH SOLUTIONS Explanation: Void pointer is a generic pointer type. No pointer arithmetic can be done on it. Void pointers are normally used for |. Passing generic pointers to functions and returning such pointers, 2. As a intermediate pointer type. 3. Used when the exact pointer type will be known at a later point of time. 99. voidmain() int _— printi("%d%d%d"i,4); , Answer: Garbage values. Explanation: An identifier is available to use in program code from the point of its declaration. So expressions such as i = i++ are valid statements, The i, j and k are automatic variables and so they contain some garbage value. Garbage in is garbage out (GIGO) 100. void main) { Explanation: Since static variables are initialized to zero by default, 101. void main) { while(1){ iffprintt(“%d" printf(“%d") break; else continue; } C Desuccinc = 157 Answer: Garbage values Explanation: The inner printf executes first to print some garbage value, The printf retums No, of characters printed and this value also cannot be predicted. Still the outer printf prints something and so retums a non-zero value. So it encounters the break statement and comes out of the while statement, 102. main) { unsigned int i=10; while(i->-0) printf(“¢ou"i); Answer: 10987654321 065535 65534. Explanation: ‘Since iis an unsigned integer it ean never become negative. So the expression i-- >0 will always be true, leading to an infinite loop. 103. #include main) { intxy=2.2.85 iffx=y%2) 2-2; printt(“%d %d" 2.x); } Answer: Garbage-value 0 Explanation: The value of y%2 is 0. This value is assigned to x. The condition reduces to if (x) or in other words if(0) and so z.goes uninitialized, Thumb Rule: Check all control paths to write bug free code 158 C PRocRaMs with SoLuTIONs 104, main) { int af 10} printit'%d,4a1-*a3); } Answer: 4 Explanation: a anda cancels out. The result is as simple as 1+3 = 4! 108. #define prod{ajb) a*b ‘main Answer: 10 Explanation: ‘The macro expands and evaluates to as: xt DAy- => x(24y-1 > 10 106. main() { unsigned int -65000; while(i++!=0); print"); } Answer: 1 Explanation: Note the semicolon after the while statement. When the value of i becomes 0 it comes out of while loop. Due to post-inerement on i the value of i while printing is 1 107. main() t C Desuccinc 159 inti-0; while(+(+-)!-0) primed” } Answer: “1 Explanation: Unary + is the only dummy operator in C. So it has no effect on the expression and ‘now the while loop is, while(i~!=0) which is false and so breaks out of while loop. The value—I is printed due to the post-decrement operator. 108. main() { float 5,g=10; printht%fin” <2); printtt“%lfin" Pg); printi(“%lfin", fod g)); ) Answer Line no 5: Etror: value required Line no 6: Cannot apply leisift to float Line no 7: Cannot apply mod to float Explanation: Enumeration constants cannot be modified, s0 you cannot apply ++ Bitawise operators and % operators cannot be applied on float values. fimod() i to find the modulus valucs for Moats as % operator is for ints 109. main) { inti-10; void pascal flint nt nt Nii; print %6d".; 160 10. C PROGRAMS WITH SOLUTIONS d void pascal flinteger:,integer:jinteger :k) { writetij hs } Answer: Compiler error: unknown type integer Compiler error: undeclared funetion write Explanation: Pascal keyword doesn’t mean that pascal code can be used. It means that the function follows Pascal argument passing mechanism in calling the functions. ‘void pascal flint int int k) { print" ) void edee! flint int j int k) sd %d Yd’, i, KD, { printh(“Yod %d %d”i, 3, K); ) main) { inti=10; Aisi; printit %din”); 10; Aisi i), printi%d".i); ) Answer: 1011213 12111013 Explanation: Pascal argument passing mechanism forces the arguments to be called from left to right, edec! is the normal C argument passing mechanism where the arguments are passed from right to lef. C Desuccinc 161 111. What is the output of the program given below? main() ‘ signed char i-0; for(i Osi) printit“%edin".): ) Answer: 128 Explanation: ‘Notice the semicolon at the end of the for loop. The initial value of the iis set to 0. The inner loop executes to increment the value from 0 to 127 (the positive range of char) and then it rotates to the negative value of -128. The condition inthe for loop fails and so comes out of the for loop. It prints the current value of i that is -128, 112. main) { unsigned char forts OiH) 5 prinit%din"i); Answer: infinite loop Explanation: The difference between the previous question and this one is that the char is declared to be unsigned. So the i++ can never yield negative value and i>0 never becomes false so that it can come out of the for loop. 113. main() { char for(i>O3i+4) 5 prinaitedin"s 162 C PRocRaMs with SoLuTIONS Answer: Behavior is implementation dependent. Explanation: The detail ifthe char is signed/unsigned by default is implementation dependent. Ifthe implementation treats the char to be signed by default the program will print -128 and ‘terminate. On the other hand if it considers char to be unsigned by default, it goes to infinite loop. Rule: You can write programs that have implementation dependent behavior. But don’t write ‘programs that depend on such behavior. 114, Is the following statement a declaration/definition, Find what does it mean? int (*x)[10]; Answer: Definition, x is a pointer to array offsize 10) integers. Apply clock-wise rule to find the meaning of this definition, 115. What is the output for the program given below? typedef enum errorType{ warning, error, exception, }error; main() { error gl; gl=l; printi%d",g1); } Answer Compiler error: Multiple declaration for error. Explanation: ‘The name etroris used in the two meanings. One means tha itis a enumerator constant with value 1. The another use is that it is @ type name (due to typedef) for enum cerrorType. Given a situation the compiler cannot distinguish the meaning of error to know in what sense the error is used: error gl; gl=error, Hf which error it refers in each case? C Desuccinc 163 When the compiler can distinguish between usages then it will not issue error (in pure technical terms, names can only be overloaded in different namespaces), Note: The extra comma in the declaration, enum errorType{waming, error, exception,) is not an error. An extra comma is valid and is provided just for programmer's 116. typedef struct error {int warning, error, exception; error; main) { error gl; glerror = printit“%d",g1.error): } Answer: 1 Explanation: The three usages of name errors can be distinguishable by the compiler at any instance, so valid (they are in different namespaces). ‘Typedet struct error{int warning, error, exception; }etror; This error can be used only by preceding the error by struct kayword as in: struct error someEtror; typedef struct error int warming, error, exception; error; This can be used only after . (dat) or -> (arrow) operator preceded by the variable glerror=1; printh"%d",g1 error); typedef struct error{int warning, error, exception; error; This can be used to define variables without using the preceding struct keyword asin error gl; Since the compiler can perfectly distinguish between these three usages, it is perfectly legal and valid, Noti This code is given here to just explain the concept behind. In real programming don’t use such overloading of names. It reduces the readability of the code. Possible doesn't ‘mean that we should use it! 164 C PRocRaMs wiTH SOLUTIONS 117. ifdef something int some~0; endif ‘main() { int thing= 0; prinut%d %din", some ,thing); ) Answer: Compiler error : undefined symbol some Explanation: This isa very simple example for conditional compilation. The name something is not already known to the compiler making the declaration int some = 0, effectively removed from the source code. 118, #if' something int some=0; Hendit ‘main { int thing =0; printh"%d %din”, some ,thing); } Answer! 00 Explanatio This code is to show that preprocessor expressions are not the same as the ordinary expressions, If a name is not known the preprocessor treats it to be equal to zero, 119, What is the output for the following program? ‘main { int aneQD3IL3]; C Desuccinc 165 printf(“%edin", (ar2D—* an2D)&4(* atr2D == arr2D[0)) }s } Answer: 1 Explanation: This is due to the close relation between the arrays and pointers. N dimensional arrays are made up of (N-1) dimensional arrays, arr2D is made up of a 3 single arrays that contains 3 integers each, arr2D an2D[1] an2D/2] ar2D[3] Te name arr2D refers to the beginning ofall the 3 arrays. *are2D refers to the start of| the first LD array (of 3 integers) that is the same address as arr2D. So the expression (an2D = *arr2D) is true (D. Similarly, *an2D is nothing but *(arr2D + 0), adding a zero doesn’t change the value ‘meaning, Again art2D[0] i the another way of telling *(arr2D ~ 0). So the expression (*(an2D + 0) = an2Dj0) is true (D) Since both parts of the expression evaluates to true the result is true(T) and the same is printed 120. voidmain0) { iff~-0 = (unsigned int)-1) printft*“You can answer this if you know how values are represented in memory") Answer: ‘You can answer this if you know how values are represented in memory. Explanation: ~ (tilde operator or bit-wise negation operator) operates on 0 to produce all ones to fill the space for an integer. -1 is represented in unsigned value as all 1’s and so both are equal. 166 C PRocRaMs with SoLuTIONs 121. int swap(int *a,int *b) { sattb;tb=ta-tbjtata*; ) maing) { intx=10,y=20; swap( dex, dey); printf("x= %d y = %din”. x,y); Explanation: This is one way of swapping two values, Simple checking will help understand this 122. main() { char *p = “aygm”; printh(%oe"++*(pHH)); ) Answer: b Explanation: Address of p is incremented and the value of p is incremented after that. 123, main) { printh"%d" d Answer: Compiler error: Lvaluc required in fumetion main Explanation: ++i yields an rvalue, For postfix ++ to operate an Ivalue is required 124, main() { char *p = “aygm”; C Desuccinc 167 char ¢; +epHy printi(%oe",e); } Answer: b Explanation: There is no difference between the expression ++*(p+-+) and +++#p++, Parenthesis just works as a visual clue for the reader to see which expression is first evaluated. 125. int aaa() {printf(“Hi");} int bbq) {printf{*hello”);) iny eve(){printftbye”?s} ‘main() { int (* ptr{3)) Qs pir{0] perl pal?) pur[2] } Answer 10: bye Explanation: int (* pt[3])0 says that pur is an array of pointers to fantions that takes no arguments and retums the type int. By the assignment ptr] ana; it means that the first funtion pointer in the array is initialized wit the address of the function aaa, Similarly, the other two array elements also gt initialized with the addresses ofthe functions bbb and cee: ‘Since ptr[2] contains the address of the function cce, the call to the function ptr{2]) is same as calling ece(). So it results in printing “bye”. 126, main) { 168 127. 128. 129. C PROGRAMS WITH SOLUTIONS inti-s; print%ed ) Hi=9); Answer: 1 Explanatioi The expression can be treated as i = (++i==6), because — is of higher precedent sperator, In the inner expression, ++ is equal to 6 yielding true(1). Hence the char pf }="%aha"s pltd="e' print. 65); } Answer: A Explanatio ‘Due to the assignment p[1]=‘c" the string becomes, “Yoc\n”. Since this string becomes the format stig for printf and ASCH value of 6 is “A, the same gets printed. void ( * abe( int, void ( *def) 0))) Os Answer! abc isa ptrto.a function which takes 2 parameters (a). an integer variable.(b). a ptrto 1 funtion which retums void. the return type of the function is void. Explanation: Apply the clock-wise rule to find the result, main() { while (stremp(“some",“some\0")) printf(“Strings are not equalin” 3 C Desuccinc 169 Answer: No output, Explanation: Ending the string constant with \0 explicitly makes no difference, So “some” and “some\0” are equivalent. So, strcmp retums 0 (false) hence breaking out of the while loop. 130. main) { char str1{] = ('3',0°m’*e")s char str2{] = {'s'‘0",'m',‘e",00"}; while (stremp(stel,stt2)) printf("Strings are not equalin”); } Answer: “Strings are not equal” “Strings are not equal Explanation: If a string constant is initialized explicitly with characters, “\0" is not appended automatically to the string, Since stel doesn’t have null termination, it teats whatever the values that are in the following positions as part of the string until it randomly reaches a ‘\0", So strl and str2 are not the same, hence the result. 131. main) { ) printt(“%d".i); Answer: Compiler Error: Lvalue required. Explanation: [As we know that increment operators return rvalues and henee it cannot appear on the left hand side of an assignment operation 170 132. 133. 134, C PROGRAMS WITH SOLUTIONS void main) { int ¢mptr,*eptr; ptr = (int*)malloe(sizeoftint); printft"%ed",*mpt); int Yeptr=(int*)ealloc(sizeoRtint), 1); printh%6d",*eptr); ) Answer: garbay Explanation: ‘The memory space allocated by malloc is uninitialized, whereas calloc returns the allocated memory space initialized to zeros. void main) { static int i while(i<=10) (2H printed", i); Answer: 32167 Explanatio ‘Since ii static itis initiaized to 0, Inside the while loop the conditional operator evaluates to false, executing i-, This continues till the integer value rotates to positive value (32767). The while condition becomes false and hence, comes out of the while loop, printing the i value, ‘main { inti-10j-20; JPOP printt(%od %d" i) C Desuccinc 171 Answer: 1010 Explanation: The Ternary operator (7: ) is equivalent for if-then-else statement, So the question can be written as: inti) { inp else isis 135. 1. const char *a; 2. char* const a; 3. char const *a; Differentiate the above declarations. Answer: 1, “const” applies to char * rather than ‘a’ (pointer to a constant char ) oF: illegal Hi legal 2. ‘const’ applies to ‘a’ rather than to the value of a (constant pointer to char ) se'F : legal a“Hi" illegal 3. Same as 1 136, main) { inti-s-10; Fi8-j&&10; printi(“%ed % “ids 172 C PRocRaMs WITH SoLuTIONs Answer 110 Explanation: The expression can be written as i-(i8~(&&10)); The inner expression (j&810) evaluates to 1 because j==10, i is 5. i= 5&1 is 1, Hence the result 137. main() intina jr? j=j| i+ && prinu“YOU CAN”); printh%ad % Answer: 41 Explanation: The boolean expression needs to be evaluated only till the truth value of the expression is not known. j is not equal to ze10 itself means that the expression’s truth value is 1, Because itis followed by || and irue | (anything) => true where (anything) will not be evaluated. So the remaining expression is not evaluated and so the value of i remains the same Similarly when && operator is involved in an expression, when any of the operands, become false, the whole expression’s truth value becomes false and hence the remaining expression will not be evaluated. false &é& (anything) => false where (anything) will not be evaluated, 138, main) { register int a=2; printht“Address of a = %d” Sa); printf(*Value of a = %d",a); Answer: Compiler Error: *&” on register variable Rule to Remember: & (address of ) operator cannot be applied on register variables. C Desuccmc 173 139, main) { float i=1.5; switeh(i) { cease 1: printf(“1"); cease 2: printf(“2"); default: printt(“0"); ) ) Answer: Compiler Error: switch expression not integral Explanation: ‘Switch statements can be applied only to integral types. 140, main) { extern i; printh%odn"i);, { inti-20; printf("édin”,i); } } Answer: Linker Error : Unresolved extemal symbol i Explanation: ‘The identifier iis available in the inner block and so using extern has no use in resolving it 141, main) { inta-2,f1,"12; f1=1-éa; sIMDiat-2.5; 174 ProcRams wit SOLUTIONS printf("in’od %d %d”.a,*f1,*2); ) Answer: 161616 Explanation: fl and £2 both refer to the same memory location a. So changes through fl and ultimately affects only the value of a 142. main) { char *p-"GOOD”; char af ]="GOOD" printf(*n sizeoftp) = %d, sizeofl*p) = %d, strlen(p) = %d”, sizeofip), sizeof(*p), strlen(p)); printf(“\n sizeof{a) = %d, strlen(a) = %d”, sizeofa, strlen(a)); } Answer: sizeof(p) = 2, sizeof*p) sizeofla) = 5, stlen(a) Explanation: sizeoflp) = sizeofichar*) => 2 sizeof(*p) => sizeof{char) => 1 Similarly, sizeof{a) => size of the character array => 5 | strlen(p) = 4 When sizeof operator is applied to an array it returns the sizeof the array and itis not the same as the sizeof the pointer variable, Here the sizeofta) where a is the character array and the size of the array is 5 because the space necessary for the terminating NULL character should also be taken into account, 143. #define DIM( array, type) sizeof{array)/sizeot(type) main() ‘ int anf 10); printi(“The dimension of the atray is %d", DIM(atr, int)): C Desucamc 175 Answer: 10 Explanation: The size of integer array of 10 elements is 10 * sizeoftint), The macro expands 10 sizeof{arr)sizcof{int) => 10 * sizcoftin! / sizeoflint) => 10. 144. int DIM(int array() { retum sizeoflarray)isizeoftint }; ‘maing) ‘ int an{ 10}; print“The dimension of the array is %d", DIM(arr); ) Answer: 1 Explanation: Arrays cannot be passed to functions as arguments and only the pointers caa be passed. So the argument is equivalent to int * array (this is one of the very few places where [] and * usage are equivalent), The return statement becomes, sizeof{int *)/ sizeoftint) that happens to be equal in this case. 145, main() { statie int a3][3]-41,2,3,4,5,6,7.89}; inti static *pl}={a.at1,a+2}; fatinOsi<3:i*) ‘ for(i=0;5<35+4) printhevodwrodrediodin”.*(*(p+i)~)), SCG DDE DDAC DD: 176 C ProcRaMs wit SOLUTIONS Answer! Explanation: *(*(p*i)4) is equivalent to pili 146. main() { void swap); intx=10,y=8; swap(dx,dy); printhYod y-%d" x9); ) void swap(int *a, int *b) { sare, th O48, ta Mb; } Answer: x=l0y-8 Explanation: Using "like this is away to swap two variables without using a temporary variable and that too ina singe statement Inside main), void swap(); means that swap is a function that may take any number of arguments (not no arguments) and returns nothing. So this doesn’t issue a compiler error by the call swap(&x, fy); that has two arguments This convention is historically due to pre-ANSI style (referred to as Kemighan and Ritchie style) style of function declaration, In that style, the swap function will be defined as follows, C Deuces 177 void swap() int *a, int * ‘ tah tb, th ta, tay } ‘where the arguments follow the (). So naturally the declaration for swap will look like, void swap() which means the swap can take any number of arguments. 147, main) { inti=2575 int *iPtr= 8s printi(“%ed %d”, *((char*)iPtr), *((char*)iPur+1) J; } Answer: WW Explanation: The integer value 257 is stored in the memory as, 00000001 00000001, so the individual bytes are taken by casting it to char * and get printed. 148, main ‘ inti = 258; int *iPtr= &ei; print“%6d %d",*((char*)iPt), *((char*)iPtr+1) ); Answer: 21 Explanation: The integer value 257 can be represented in binary as, 00000001 00000001. Remember that the INTEL machines are ‘small-endian’ machines. Small-endian means that the lower order bytes are stored in the higher memory addresses and the higher order bytes are stored in lower addresses, The integer value 258 is stored in memory as (00000001 00000010, 178 C ProcRaMs wit SOLUTIONS 149, main) { int 00; char *ptr = &i Hepem2; print Ds ) Answer: 356 Explanation: The integer value 300 in binary notation is: 00000001 00101100. Itis stored in memory (small-endian) as: 00101100 00000001. Result ofthe expression * 1 per= 2 makes the ‘memory representation as: 00101100 00000010, So the integer corresponding to it is (09000010 00101100=> 556. 150. #include ‘main() { char * str=“hello”; char * ptr = st char least ~ 127; while (*pt+) least = (*ptr Sari; “p= 0: } ‘Answer & Explanation: Ifthe body of the loop never executes p is assigned no address. So p remains NULL ‘where *p=0 may result in problem (may rise to runtime ertor“NULL pointer assignment” and terminate the program) 157. What is wrong with the following code? int *fo00, { ints = malloc(sizeof{int)100); assert(s != NULL); rotur s; Answer & Explanation: ssert macro should be used for debugging and finding out bugs. The check s != NULL is for error/exception handling and for that assert shouldn’t be used. A plain if and the corresponding remedy statement has to be given. 158, What is the hidden bug with the following statement? assert(val+ |= 0) Answer & Explanation: assert macro is used for debugging and removed in release version, In assert, the experssion involves side-effects. So the behavior of the code becomes different in case of debug version and the release version thus leading to a subtle bug. Rule to Remember: Don’t use expressions that have side-effects in assert statements. 182 C ProcRaMs wit SOLUTIONS 159. voidmain) { int *1=0x400; ii points tothe address 400 *i=0; 1 set the value of memory location pointed by is } Answer Undefined behavior Explanation: The second statement results in undefined behavior because it points to some location whose value may not be available for modification, This type of pointer in which the ‘non-availability of the implementation of the referenced location is known as ‘incomplet type’ 160. #define assert(cond) if(!(cond)) (printi{stderr, “assertion failed: %s, file %s, line %d \n” cond, __FILE_,__LINE_), abort) void main() { inti~ 10; ifli==0) assert < 100); else printit"This statement becomes else for if in assert macro”); Answer No output Explanation: ‘The else part in which the printf is there becomes the else for if in the assert macro. Hence nothing is printed, The solution is to use conditional operator instead of if statement, define assext(cond) ((cond) (0): ({printf (stderr, “assertion failed: \ %s, file %s, ine %d \n" cond, _ FILE, abort())) C Desuccnc 183 Note: However this problem of “matching with nearest else” cannot be solved by the usual method of placing the if statement inside a block like this, ‘define assert(cond) { if(t(cond))\ (iprintistderr, “assertion failed: %s, i _FILB_,_LINE_), abort() \ 3s, line Yd \n" fteond,\ 161. Is the following code legal? struct a ‘ intx; struct ab; ) Answer: No Explanation: It is not legal for a structure to contain a member that is of the same type as in this cease, Because this will cause the structure declaration to be recursive without end, 162. Is the following code legal?” struct a { int; struct a; } Answer: Yes, Explanation: +b is a pointer to type struct a and so is legal, The compiler knows, the size of the pointer to a structure even before the size of the structure is determined(as you know the pointer to any type is of same size). This type of structures is known as ‘self- referencing’ structure. 184 C ProcRaMs wit SOLUTIONS 163. Isthe following code egal? typedef struct a { inex; atype *h; JaType Answer: No Explanation: The typename aType is not known at the point of declaring the structure (forward references are not made for typedef) 164. Is the following code legal? typedef struct a aType; struct a { intx; aType *b; % Answer: Yes Explanation: The typename aType is known at the point of declaring the structure, because it is already typedefined. 168. Is the following code legal?” void main) { typedef struct a aType; Type someVariable; struct a intx; aype *b; C Desuccmc = 185 Answer: No Explanation: When the declaration, typedef struct a aType; is encountered body of struct a is not known. This is known as ‘incomplete types’. 166. void main t printi(“sizeof (void *) = %d in”, sizeofl void *)); printi(“sizeof (int *) = %d \n", sizeoiint *); print(“'sizeof (double *) =%d \n", sizeof{double *)); printf("sizeof{struct unknown *) = %d \n”, sizeof{struct unknown *)); } Answer: sizeof (void *) = 2 sizeof (int) =2 sizeof (double #) = 2 sizeof(struct unknown *) = 2 Explanation: The pointer to any type is of same size, 167. char inputString[100] = {0}; ‘To get string input from the keyboard which one of the following is better? 1) gots(inputString) 2) fgets(inputString, sizeoflinputString), fp) ‘Answer & Explanation: The second one is better because gets(inputString) doesn’t know the size of the string, passed and so, if a very big input (here, more than 100 chars) the charactes will be \written past the input string. When fgets is used with stdin performs the same operation as gets but is safe. 168, Which version do you prefer of the following two? 1) printi(%s",str; or the more curt one 2) printfistr), 186 169. 170. C ProcraMs WITH SOLUTIONS Answer & Explanation: Prefer the first one. If the str contains any format characters like %d then it will result in a subtle bug, void main { inti-l int Fip= &i, tip = ej; intk = *ip'*ip; printf , Answer: Compiler Error: Explanation: nexpected end of file in comment started in line 5”. The programmer intended to divide two integers, but by the “maximum munch” rule, the compiler treats the operator sequence / and * as /* which happens to be the starting of comment. To force what is intended by the programmer, intk = *ip/ tip; 1 give space explicity separating / and * int ip/(*ip); 1 put braces to force the intention will solve the problem. void main) eh printf("%e %d \n”, ch, chs 3 Answer: Implementaion dependent Explanation: The char type may be signed or unsigned by default. Ifitis signed then cht is executed after ch reaches 127 and rotates back to -128, Thus ch is always smaller than 127. C Deuccnc 187 171. Is this code legal? int *ptr, pir= (int *) 0x400; Answer: Yes Explanation: The pointer pte will point atthe integer in the memory location 0x400. 172. maing) { char a[4]-“HELLO” print%s",a; , Answer: Compiler error: Too many initializes Explanation: The array a is of size 4 ut the string constant requires 6 bytes to got stored. 173, maing { char a[4}-“HELL”; prints"; Answer: HELL%@!-@!@72@- Explanation: The character array has the memory just enough to hold the string “HELL” and doesnt have enough space to store the terminating null character, So it prints the HELL correctly and continues o print garbage valucs till t accidentally comes aeross a NULL character 174. main() { inta=10,*j; void *k; 188 C ProcRaMs wit SOLUTIONS kes printf(“in %u You ".k) ) Answer: Compiler error: Cannot increment a void pointer Explanation: ‘Void pointers are generic pointers and they can be used only when the type is not known and as an intermediate address storage type. No pointer arithmetic ean be done on it and you cannot apply indirection operator (*) on void pointers. 178. main() { exter inti { inti-20; ( const volatile unsigned i=30; print(“%d"); } printit"%di; 4 print%d; } inti 176. printf can be implemented by using lis. Answer: Variable length argument lists 177. char *someFun() t char *temp = “string constant”; return temp; } intmaing) { puts(someFun(); ) C Desucanc 189 Answer: string constant Explanation: The program suffers no problem and gives the output correctly because the character constants are stored in code/data arca and not allocated in stack, so this doesn’t Iead to dangling pointers. 178. char *someFunl0) Answer { char temp ]= “string"; return temp; } char *someFun20 { char temp{ ]= {'s' ‘tr i'¢n'g"}; return temp; ) int main() { puts(someFun!(); puts(someF un); } Garbage values. Explanation: Both the functions suffer from the problem of dangling pointers. In someFunl() temp is a character array and so the space for itis allocated in heap and is initialized with character string “string”. This is created dynamically as the function is called, so is also deleted dynamically on exiting the funetion so the string data is not available in the calling function main() leading to print some garbage values. The function someFun2() also suffers from the same problem but the problem can be easily identified in this 179. What will print it? ‘main { 190 180. 181. 182. C ProcrAMs WITH SOLUTIONS char *k1="hitechskill.com”; char *12; K2=(char*)malloc(20); ‘memset (K2, 0, 20); while(*k2++ = e144); 2); print%s Answer: empty string What will be printed as the result of the operation below? ‘main() What will be printed as the result of the operation below? ‘main() { int a=5, rintl(2%d,%d, dn? aa <2,a>>2); } Answer: 5,20,1 ‘What will be printed as the result of the operation below? define swap(a,b) ararbsb=a-bsana-b; void main() { int m=5, n= 183. 184, C Desucans swap (enn); printi(‘%6d %din"sm.n); swap2(m.n)s print%d Yan"); ‘nt swap2intx, int y) { int temp; temp=x; x mp; return 0; ) Answer: 10, 5 10,5 ‘What will be printed as the result of the operation below? main) { char *ptr = “SC Systems”; pees printh(“%esin" pt); pis print('%s\n" ) Answer: SC Systems Systems ‘What will be printed as the result of the operation below? maing) { char sI[]="SC"; char s2]]= “Systems”; 191 192 188, 186. 187. 188. C ProcraMs WITH SOLUTIONS printf(%s"s1); ) Answer: SC What willbe printed asthe result ofthe operation below? mand) { char *ptrl; char *ptr2; ptrl=(char *)malloe(25); ptr2=(char *)malloc(25); strepy(ptel SC); strepy(plr2,"Systems"); streat(ptrl pt2); prints" ptr); 3 Answer: SCSystems The following variable is available in file1.c, who can access it?: slatie int average; Answer: All the functions in the filel.c can access the variable. ‘What will be the result of the following code? ‘define TRUE 0 /! some code while(TRUE) { Hi some code ) Answer: This will not go into the loop as TRUE is defined as 0. ‘What will be printed as the result of the operation below? intx; int modifyvalue) C Desuccnc 193 return(x+=10); int changevalue(int x) { return(x*=1); voidmain) { int x=10; xHy changevalue(x); xHy modifyvalue(; printf (“First output:%din" x); xhy changevalue(x); printf(“Second output:Yodin”,x); modifyvalue(); printi(“Third output:%d\n",x); ) Answer: 12,13, 13, 189, What will be printed as the result of the operation below? ‘main() { int x=10, yoy: printed Yd"); 194 190. 191. 192. C ProcRAMS WITH SOLUTIONS Answer: 11, 16 How many times main is get called? raid) { printt"Jumbore main; ) Answer: Till stack overflow What is output for the following program? +include main() t int*p,tqi PALint *)100; artint *)200; map: prints(“%d") , 3) 100 6) 25 ©) 0d) compile error Answer : b) 25 What is output for the following program? include ‘define swap(ajb) temp=a,a~b,b=temp; main) { int 6 inttemp; ila) swvap(a.b); printt"a%6d,b- Yd" a,b); ) C Desucanc 195 a) a-Sb=6 b)a-G6b=5 c)a-Ob=6 d) None Answer: a) a=5 b=6 193. What is output for the following program? Hinclude ‘main { unsigned char is for(i 0si<3O0si++) { printft*") } 2)299- b)300 cinfinite d)none Answer: c) (infinite) 194, What is output for the following program? include ‘main int int sum=5; switeh(n) { ‘case 2:sum=sum-2; break; case 3:sum* break; default :sum=0; prine(“%d" sum); } a)l5 b)0 66 d)none Answer: a) 15 196 195. 196. 197. C ProcRAMS WITH SOLUTIONS What is output for the following program? include ‘main() { inta-10,b>5) printt“a=96d,b=%d",a,6); 3 a)a-0,b=5 bja-10 b= c)a0,b-0 d)none Answer: a) a=( ‘What is output for the following program? #inelude ‘main() { inta[S]i,tips for(i Osie i alii ima; printt“%d”,*(ip+3*sizeoftint)); 30 b)S hl Anone Answer: d) none What is the size of the structure? ‘Hinelude ‘main { struct { char a; short b; inte; temp: C Desucans 197 ) a)7 byS c)12 )120 Answer: )8 198. Define pointer to function that take argument as character pointer and return void pointer Answer: void *(*(char *) 199, 5-2-3*5-2 evaluates 18 then i) -Ieft as rcitive * has precedence over ~ i) - right associative * has precedence over - iit) * left associative has precedence over * iv) * right associative - has precedence over * a)i bi ili div Answer: iv 200. ind the output of the following program, void main() t float b=1,2=1,3; a=1/2*beh; printh%.20",a); } 2) 0.00 v0.0 ©) 0.50 dos Answer: a) 0.00 201. Find the output ofthe following program. void mind static in 3} printi%4c",*(+10}-90) } 198 202. 203. 204. C ProcRAMS WITH SOLUTIONS a) Garbage value ) Runtime error ©) Compiler error 4) None of these Answer: d) None of these Find the output of the following program. void main() { rinth(“%6%P6%d%96%M%");, } 2) b) %%N6% ©) RM 4) None of these Answer: a) %%6% Find the output ofthe following program, int vO) float m=0; return m+ , int main) { printf(“%.76",v0) ) ) 0,0000000 b) 0.00 ©) Exror 4) None Answer: a) 0.000000 Find the output of the following program. void main() { 208. 206. inti-2jr; Pe printit%6d"j); } al bo 92 4) None of these Answer: a) 1 Find the output ofthe following program. void main) { int a=10,b-20; printf(“Yod : Yd",a,b); } 2) 10:30 b) 30:10 ©) Garbage value )20:10 Answer: b) 30:10 Find the output ofthe following program, void main() printf("Good”); 8) Good b) God C Desucanc 199 200. C PROGRAMS WITH SOLUTIONS ©) We can’t predict 6) Error Answer: a) Good 207. Find the output of the following program, void main) { int a=100,b-200; printh("%e",a>b?'a"s"b’y; } ab bya ©) 200 4) 100 Answer: a) b 208, Find the output of the following program, void main() { char a=65,0-97;, ift'a>b") printf("A") printf(*B") } a) AB dA OB 4) Error Answer: a) AB 209. What will be the output? void main() { do { 210. 2. 212. C Desucane if(0) ‘main; printf(“Thaal”); pwhile(O)s } 2) Thaal ) Infinite Loop ©) Syntax error 4) Nothing get printed Answer: a) Thaal For the following C program define AREA(R)3.144%x"x) main) {float 11=6,25,12°2.5.a; a AREA CI) print{("in Area of the circle is %f", a); a=AREA(?2); printf("in Area of the circle is %f", a); } ‘What is the output? Answer: Area of the citele is 122,656250 Area of the cirele is 19,625000 ‘What will be the output? void main() { int d=5; printf(“%E "ds Answer: Undefined ‘What will be the output? void main) { 201 202 —C PROGRAMS WITH SOLUTIONS switch() ‘case 1: printi("%ad"i)sbreak; { case 2-printi(“%d”,i);break; ‘case 3eprinti(%d”,i);break: ) switeh() ease 4:printf( ) Answer: 1,234 213. What wil be the output? void main() { char *5=*\123458in"; printf(“%d" sizeofis)); ) Answer: 6 214, What will be the output? void main) { unsigned i-1; * unsigned char k~ -1 => k=255; ¥ signed je-1; /* char k= -1 => k=65535 */ 65535 */ unsigned or signed int k=-1 itis) printtess”); else itt) printi(“greater") else iti) printf(“equal”); } Answer: less C Desuccinc 203 215. What will be the output void main() { float j-1000*1000; prins%E } 1, 1000000 2. Overflow 3 4, None Answer: 4 216. A structure pointer is defined of the type time , With 3 fields min,sec hours having pointers to intergers. Write the way to initialize the 2nd element to 10, 217. What will be the output? void main) { inti-7; printh"seditrtins)s ) Answer: 56 218, im) void main { 4); 1.2; £01.23); fint,intint ke) { 204 219. 220. 221. C ProcrAMs WITH SOLUTIONS rint"%d %d %d ik) ) What are the number of syntax errors in the above? Answer: None What will be the output? void main) t inti-r printtyoditH¥it); } Answer: 56 What wil be the output? fdefine one 0 Ffdef one printft“one is defined ") #ifadet one printf(“one is not defined Answer: “one is defined What will be the output? void main) { int count=10,*temp,sum=0; temp=&count; emp=20; temp=∑ “temp=count; printf("%d Yd %ed } Answer: 20 20.20 .count,*temp,sum);, 222. 223, 224, 228, C Desucanc ‘What is alloca)? Answer + It allocates and frees memory after use/after getting out of scope. What willbe the output? rmain() { static i=3; printed" iy, return i>0 2 main0:0; } Answer: 321 What wil be the output? char *¥000) { char result{100)}; strepy (resul“anything is good"); return(result); } void maing { char is FFfo00) printf%4s".p; Answer: anything is good, ‘What will be the output? void main { char *s[]>{ “dharma”, “hewlett-packard”,’siemens”,“ibm”);, char **p; Ps prints" +p); 205 206 226. 227. C ProcraMs WITH SOLUTIONS prinefi"%s",* p++); printf(“%s"--+*p) ) Answer: “harma” (p-~add(dharma) && (*p)~harma) “harma” (after printing, p->add{hewlett-packard) &&(*p)->harma) “ewlett-packard” What will be the output? main) {inti-0; for(i=0;i<20;i-+) {switch(i) case O55 cease 102; case SiS; default itt; breaks} printi(“ed,”,i); ) ) a) 0,5,9,13,17, +b)5,9,13,17 9121722 41621 6) Syntax error Answer: (a) ‘What will be the output? main) {char ¢=-64; inti--32 unsigned int u 16; ite>i) {printf(“pass!,”) ife>2); ) Answer: 5 201 210 C PRocRaMs wit SOLUTIONS 234, Find the output for the following C program, define swapl (ab) a=a+bsb=a-bia=a-b; ‘main() swapl (xy) printed %odin" x,y); swap2(uy)s printf(“%ed Yd” x,y); ) int swap2(int aint b) { inttemp; temp=a; Answer: 105 235. Find the output forthe following C program. rmaind) ‘ char *pte = “Ramco Systems” (pty; prinitvésin" ptr; pret; printt"%sn" pt; } Answer: Samco Systems 236, Find the output for the following C program, inelude ‘main C Desucaa = 211 sls; printht%s"1; J Answer: Compilation error giving it cannot be an modifiable “value. 237. Find the output for the following € program, ¥include main() { char *pl; char *p2; pl=(char *) malloc(25); p2=(char*) malloc(25); strepy(pl,"Rameo"); stiepy(p2,"Systems"); streat(p1,p2); printi"%s" pl); , Answer: RameoSystems 238, Find the output for the following C program given that [1]. The following variable is available in file1.c static int average_float; Answer: All the functions in the filel.¢ can access the variable, 239, Find the output for the following C program. if define TRUE 0 some code while(TRUE) { some code ) Answer: This won't go into the loop as TRUE is defined as 0, 212 C PROGRAMS WITH SOLUTIONS 240. struct list int x; struct list *next; head; the struct head.x ~100 Is the above assignment to pointer is correct or wrong ? Answer: Wrong 241, What is the output of the following ? ‘main() {ints iL; Sema printtt%di); Answer: 4 242, main() {FILE *ipl,*ip2; fpI-fopen(“on fp2-fopen(“on fpute’A’ fp) pute fp2) felose(tp!) felose(fp2) } Find the Error, If Any? Answer: No error, But It will over writes on same file 243. What will be the output? Hidefine MAN(Ly) (0)>(9)%)9) inti=10; C Desuccmc 213 IAX(iE A); rintli%od %d Yad Yds } Answer: 1050 244. intz,x-Sy-10,2-4b-2; yt bia; ‘What number will z in the sample code above contain? Choice 1.5 Choice 2 6 Choice 3-10 [Ans] Corected by buddy by running the program Choice 411 Choice § 12 245. With every use of a memory allocation funetion, what funetion should be used to release allocated memory which is no longer needed? Choice 1 unallocd) Choice 2 dropmem() Choice 3 dealloc() Choice 4 release() Choice § free() [Ans] 246. void *ptr myStruct myAmray(10]; pir= myArray; Which of the following is the correct way to increment the variable “ptt”? Choice 1 ptr ptr + sizcoffmyStruct); [Ans] Choice 2 +4(nt*)ptr; Choice 3 ptr ptr + sizcofimyAray); 214 247. 248, C ProcRAMs WITH SOLUTIONS Choice 4 increment(pte); Choice § ptr ptr sizeoltpt; cchar* myFune (char *ptr) { ptr retum (pte); } intmaing) { char *x, *ys x="HELLO"; y= myFune (x); res a", printt (*y return 0; ) What will print when the sample code above is executed? Choice 1 y = HELLO Choice 2 y= ELLO Choice 3 y=LLO Choice 4 y= LO [Ans] Choice § x= 0 struct node *nPtr, *sPtr; /* pointers fora linked list. */ for (nPt=sPtr; nPtr; nPtr=nPtr->next) { free(aPtr); ) ‘The sample code above releases memory from a linked list. Which of the choices below accurately deseribes how it will work? C Desucamc 215 Choice 1 It will work correctly since the for loop covers the entire list. Choice 2 It may fail since each node “nPir” is freed before its next address can be accessed. (Ans) Choice 3 In the for loop, the assignment “nPtr=uPt->next” should be changed to r=nPtrnext”, Choice 4 This is invalid syntax for freeing memory. Choice § The loop will never end, 249. What function will read a specified number of elements from a file? Choice 1 fileread() Choice 2 getline) Choice 3 readfile() Choice 4 fread((Ans) Choice § gets() 250. “My salary was increased by 15%!” Select the statement which will EXACTLY reproduce the line of text above. Choice 1 printt"\"My salary was increased by 15/%\N\"n" Choice 2 printf("My salary was increased by 15%!\n"); (Ans) Choice 3 printt"My salary was increased by 15% Choice 4 printft*V"My salary was increased by 15%%!\"\n"),[Ans Choice § printf(‘V"My salary was inereased by 15°%"Nn"); Nn") 251. What isa difference between a declaration and a definition of a variable? Choice 1 ‘Both can occur multiple times, but a declaration must occur first Choice 2 ‘There is no difference between them, Choice 3 ‘A definition occurs once, but a declaration may occur many times. 216 282. 254, C ProcRAMS WITH SOLUTIONS Choice 4 A declaration occurs once, but a definition may occur many times. [Ans] Choice 5 Both can occur multiple times, but a definition must occur frst. int testarray[3][2][2] = {1, 2, 3,4, 5, 6,7,8,9, 10, 11, 12}; ‘What value does testarray{2][1][0] in the sample code above contain? Choice 13 Choice 2.5 Choice 3.7 Choice 49 Choice § 11[Ans]. int a=10,b; +Ha prine%d,%d,%6d%6d" b.arsaytta);, What will be the output when following code is executed? Choice 1 12,10,11,13 Choice 2 22,10,11,13 Choice 3 22,11,11,11 Choice 4 12,11,11,11 Choice § 22,13,13,13[Ans] imtx[]=(1,4,8,5,1,4}5 int pty; pir =x+4; ya ptr =x; What does y in the sample code above equal? Choice 1-3 Choice 2 0 Choice 3 4[Ans] 255, 286. 257. C Desucanc Choice 4 4+ sizeof{ int) Choice § 4* sizcoft int) void myFune (int x) { ifx>0) %d,”s x); int main) { smyFune(5); retum 0; ) What will the above sample code produce when executed? Choice 1 1,2,3,4,5.5, Choice 2 4,3,2,1,0,0, Choice 3 5,4,3,2,1,0, Choice 4 0,0, 1,2,3,4 (Ans) Choice § 0,1,2,3,.4,5, uss What does the operation shown above produce? Choice 11 Choice 2 6 Choice 3.8 Choice 4 14 [Ans] Choice 5 15 ‘define MAX_NUM 15, Referring to the sample above, what is MAX_NUM? Choice 1 MAX_NUM is an integer variable. Choice 2. MAX_NUM is a linker constant. 217 218 — C PROGRAMS WITH SOLUTIONS Choice 3 MAX_NUM is a precompiler constant. Choice 4 MAX_NUM is a preprocessor macro. [Ans] Choice § MAX_NUM js an integer constant. 258. Which one of the following will turn off buffering for stdout? Choice 1 setbufl stdout, FALSE ); Choice 2 setvbut{ stdout, NULL ) Choice 3 setbufl stdout, NULL); [Ans] Choice 4 setvbull stdout, IONBF ); Choice 5 setbuf{ stdout, _IONBF ); 259. What is a proper method of opening a file for writing as binary file? Choice 1 FILE f= fisrite( “test.bin”, “b” ); Choice 2 FILE *f= fopenb( “test bin”, “w" ); Choice 3 FILE *f= fopen( “test.bin”, “we” ); Choice 4 FILE *£= fiwriteb( “test.bin” }s Choice § FILE *f= fopent “test.bin”, “bw” ); [Ans] 260. Which one of the following functions is the correct choice for moving blocks of binary data that are of arbitrary size and position in memory? Choice 1 memepy() Choice 2 memsei() Choice 3 stmepy() Choice 4 strepy) Choice § memmove()[Ans] 261. intx=2*3+4*5; ‘What value will x contain in the sample code abov. Choice 1 22 Choice 2 26[Ans] Choice 3 46 Choice 4 50 Choice 5 70 262. void * array_dup (a, number, size) const void * a; size_t number; C Desucanc 219 size_t size; { void * clone; size_t bytes; NULL); bytes = number * size; assert(a lone = alloca(bytes): i (etone) retur clone; ‘memepy(clone, a, bytes); return clone: ) ‘The function array_dupQ), defined above, contains an error, Which one of the following correctly analyzes it? Choice 1 Ifthe arguments to memepy() refer to overlapping regions, the destination buffer will be subject to memory corruption, Choice 2 array_dup() declares its first parameter to be a pointer, when the actual argument will be an array. Choice 3 The memory obtained from alloca() is not valid in the context of the caller Moreover, alloca() is nonstandard, [Ans] Choice 4 size_tis not a Standard C defined type and may not be known to the compiler. Choice § ‘The definition of array_dup() is unusual. Funetions cannot be defined using this syntax 263. intvarl; Ifa variable has been declared with file scope, as above, can it safely be accessed globally from another file? Choice 1 Yes; it can be referenced through the register specifier, Choice 2 No; it would have to have been initially declared as a static variable. ‘Choice 3 No; it would need to have been initially declared using the global keyword.[Ans] Choice 4 Yes; it can be referenced through the publish specifier. Choice § Yes; it can be referenced through the extern specifier, 220 264. 265. 266. 267. C ProcRAMs WITH SOLUTIONS time_t Which one of the following statements will properly initialize the variable t with the current time from the sample above? Choice 1 t= clockQslAns] Choice 2 time( &t}; Choice 3 t= ctimeQ; Choice 4 (= localtimed; Choice § None of the above Which one of the following provides conceptual support for function calls? Choice 1 The system stack{Ans] Choice 2 The data segment Choice 3 The processors registers Choice 4 ‘The text segment Choice 5 ‘The heap Cis which kind of language? Choice 1 Machine Choice 2 Procedural[Ans] Choice 3 Assembly Choice 4 Object-oriented Choice § Strictly-typed int myAmay[2](3) for i=0;i<33i-+1) for GO; )<25-9) { myArraylji] ~ ctr; ett; } What is the value of myArray[1][2]; in the sample code above? Choice 11 Choice 22 C Desuccnc © 221 Choice 3.3 Choice 4 4 Choice § 5 {Ans} 00,10,01,11,12 268. jx xt); printitx-M6din", x) What will be printed when the sample code above is executed? Choice 1 x-0 Choice 2 x=1 Choice 3 x-3 Choice 4 x=4[Ans] Choice § x5 269. intx=3; if{x=2); x=; iftx—=3) else x What value will x contain when the sample code above is executed? Choice 11 Choice 2 2[Ans] Choice 3.3 Choice 4 4 Choiee $ 5 270. char *ptr; char myString[] = “abedefg”; r= myString; prt 5; ‘What string does ptr point to in the sample code above? Choice 1 fg [Ans}/*because string*/ Choice 2 ef, 222 271. 272. 273. C ProcRAMS WITH SOLUTIONS Choice 3 defy Choice 4 cdefg Choice § None of the above doublex=-3.5,y=3.5; print “%6.0F : %0fn",cel{ x ), cell y ) print “%.0F: %.0f\n", floor x }, floor y)}: What will the code above print when executed? ceil rounds up 3.2=4 floor =>rounds down 3.2-3 Choice 1 -3:4 -4:3 [Ans] Choice 2 -4:4-3 Choice 3-4:3-4 Choice 4 -4:3-3 Choice § -3:3-4:4 Which one of the following will declare a pointer to an integer at address 0x200 in memory? Choice 1 int *x; *x = 0x200;{Ans] Choice 2 int *x=&0x200; Choice 3 int *x=*0x200; Choice 4 int *x=0x200; Choice 5 int *x( &0x200 ); intx= 5; inty=2; char op switch (op) { default : x += 1 /*It will go to all the cases*/ xoy After the sample code above has been executed, what value will the variable x contain’? Choice 14 Choice 2.5 Choice 3.6 [Ans] C Desucawc 223 Choice 47 Choice § 8 274, x= 3, counter = 0; while (1) { +teounter; Referring to the sample code above, what value will the variable counter have when, ‘completed? Choice 1.0 Choice 21 Choice 3 2[Ans] Choice 43 Choice 5 4 278. char ** array [12][12][12]; Consider array, defined above. Which one of the following definitions and initializations of p is valid? Choice 4 char ** (* p) [12][12] = array; [Ans] Choice 2 char **** p = array; Choice 3 char * (* p) (12][12][12] = anay; Choice 4 const char ** p [12][12][12] = array: Choice § char (** p) [12][12] = array: 276. void (*signalt int sig, void (*handler) (int) (int); Which one of the following definitions of sighandler_t allows the above declaration to be rewritten as follows: sighandler_t signal (int sig, sighandler_t handler); Choice 1 typedef void (*sighandler_0 (int)(Ans] Choice 2 typedef sighandler_t void (*) (int); Choice 3 typedef void *sighandler_t (int); Choice 4 define sighandler_t(x) void (*x) (int) Choice 5 #define sighandler_t void (*) (int) 224 — C PROGRAMS WITH SOLUTIONS 277. Allof the following choices represent syntactically correct function definitions. Which one of the following represents a semantically legal function definition in Standard C? Choice 1 Code:{Ans] int count_digits (const char * buf) { assert(buf != NULL); int ent =0, is for (i= 0; bul] != 80"; 14) if (isdigit(butTi)) nth; retum ent; } Choice 2 Code: int count_digits (const char * bul) { int ent = 0; assert(buf != NULL); for (int i= 0; bul] != 40"; 4) if (sdigi(butlip) ents; return ent; Choice 3 Code: int count_digits (const char * bul) { intent =i: assen(buf != NULL); for (i = 0; buffi] != *\0"; i++) if Gsdigitbutfi)) nth; return ent; ) Choice 4 Code: int count_digits (const char * bul) { assert(buf != NULL); C Desucamc = 225 for (= 0; uli] I= 40"; ++) if Gsdigit(outTi)) ents return ent; ) Choice § Code: int count_digits (const char * bul) { assert(buf != NULL); int ent = 0; for (int i= 0; bul] != 90"; +4) if Gsdigit(obutli)) ents, return ent; } 278. struct customer *ptr ~ malloc( sizeof{ struct customer ) ); Given the sample allocation for the pointer "pte" found above, which one of the following statements is used to reallocate ptr to be an array of 10 elements? Choice 1 ptr realloc( ptr, 10 * sizeof{ struct customer) [Ans] Choice 2 realloc( ptr, 9 * sizeof{ struct customer ) ) Choice 3 ptr+=malloc( 9 * sizeof{ struct customer ) ) Choice 4 ptr realloc( ptr, 9* sizeof struct customer } ); Choice 5 realloc( ptr, 10 * sizeof{ struct customer ) }; 279. Which one of the following is a true statement about pointers? Choice 1 Pointer arithmetic is permitted on pointers of any type. Choice 2A pointer of type void * can be used to directly examine or modify an object of any type. Choice 3 Standard C mandates a minimum of four levels of indirection accessible through a pointer. Choice 4 AC program knows the types of its pointers and indirectly referenced data items at runtime. [Ans] Choice § Pointers may be used to simulate call-by-reference. 226 280. 281. 282. C ProcRAMs WITH SOLUTIONS Which one of the following functions returns the string representation from a pointer to a time_t value? Choice 1 localtime Choice 2. gmtime Choice 3 strtime [Ans] Choice 4 asetime Choice § time short testarray(4J[3] = { {1}, {2,3}, (4,5, 6} printf “?éd\n", sizeof testarray ) ); Assuming a short is two bytes long, what will be printed by the above code? Choice 1 Itwill not compile because not enough intializers are given. Choice 26 Choice 3.7 Choice 412 Choice § 24 [Ans] char buf [] = “Hello world!"; char * buf= “Hello world!”; Interns of code generation, how do the two definitions of buf, both presented above, differ? Choice 1 The first definition certainly allows the contents of buf to be safely modified at runtime; the second definition does not Choice 2 The first definition is not suitable for usage as an argument to a function call; the second definition is Choice 3 The first definition is not legal because it docs not indicate the size of the aay to be allocated; the second definition is legal Choice 4 They do not differ — they are functionally equivalent. [Ans] Choice 5 ‘The fitst definition does not allocate enough space for a terminating NULL character, nor does it append one; the second definition does. |. Ina C expression, how is a logical AND represented? Choice 1 @@ Choice 2 || Choice 3 AND. Choice 4 && [Ans] Choice § AND C Desucanc = 227 284. How do printfi's format specifiers %e and %f differ in their treatment of floating-point numbers? Choice 1 %e always displays an argument of type double in engineering notation; Yo always displays an argument of type double in decimal notation. [Ans] Choice 2 %e expects a corresponding argument of type double; %f expects @ corresponding argument of type float. Choice 3 %e displays a double in engineering notation if the number is very small or very large. Otherwise, it behaves like %f and displays the number in decimal notation Choice 4 %e displays an argument of type double with tailing zeros; Y%f never displays trailing zeros. Choice 5 %e and %af both expect a corresponding argument of type double and format it identically. %e is left over from K&R C; Standard C prefers %f for new code. 285. Which one of the following Standard C functions ean be used to reset end-of-file and error conditions on an open stream? Choice 1 clearerr() Choice 2 fseek((Ans) Choice 3 ferror() Choice 4 feof) Choice § setvbutt) 286. Which one of the following will read a character from the keyboard and will store it in the variable e? Choice 1 ¢ = gete: Choice 2 gete( &e ); Choice 3 c= getchar( stdin ); Choice 4 getchar( &e ) Choice $ c= getchar(); [Ans) 287. Hinelude itis void increment( inti) 228 288, 289. C ProcRAMS WITH SOLUTIONS intmain) { for( i= 0; i < 10; inerement( i) ) ( } print(“i-%adin”, is return 0; } What will happen when the program above is compiled and executed?” Choice 1 Itwillnot compile. Choice 2 twill print out:i=9. Choice 3 Itwill printout: 10, Choice 4 Itwill printout: i=11 Choice 5 It will loop indefinitely [Ans] char ptrl[] = “Hello World”; char *ptr2 = malloc( 5 ); pad = pir; ‘What is wrong with the above code (assuming the call to malloc does no fil)? Choice 1 There will be a memory overwrite. Choice 2 There will be a memory leak Choice 3 There willbe a segmentation fault Choice 4 Not enough space is allocated by the malloc. (Ans) Choice 5 Itwill not compile imi=4; switch (i) ( default ease 3: ims, C Desucamc = 229 ca if (= 9) break; printf("i= %din”, i); ‘What will the output of the sample code above be? Choice 1 i=5[Ans’ Choice 2 i=8 Choice 3 i=9 Choice 4 i= 10 Choice § i= 18 290. Which one of the following C operators is right associative? Choice 1 = [Ans Choice 2 , Choice 3 [] Choice 4 * Choice $ > 291. What does the “auto” specifier do? Choice 1 It automatically initializes a variable to 0, Choice 2 It indicates that a variable's memory will automatically be preserved.[Ans] Choice 3 It automatically increments the variable when used. Choice 4 It automatically initializes a variable to NULL. Choice § It indicates that a variable's memory space is allocated upon entry into the block. 230 292. 293. 294. C ProcRAMs WITH SOLUTIONS How do you include a system header file called sysheaderh in a C source file? Choice 1 include [Ans Choice 2 #incl “sysheaderh” Choice 3 sincludefile Choice 4 include sysheaderh Choice 5 #incl = 2) return 2; Choice 4 if (x= 0) return 1; Choice § if (x < 1) return 1; [Ans] {more probable} 307. /* Increment each integer in the array ‘p’ of * size ‘n’. * void inerement_ints (int p [/*n*/), int n) { assert(p != NULL); /* Ensure that ‘p’ isn't a null pointer. */ assert(n >= 0); /* Ensure that ‘n’ is nonnegative. */ while (0) / Loop over ‘n’ elements ofp’. */ { ‘prt /* Increment *p. */ ptt; /* Increment p, decrement n, */ ) } Consider the function inerement_ints(), defined above. Despite its significant inline ‘commentary, it contains an error. Which one of the following correctly assesses it? C Desucana = 235 Choice 1 *p++ causes p to be incremented before the dereference is performed, because both operators have equal precedence and are right associative. Choice 2 An array isa nonmodifiable lvalue, so p cannot be incremented directly. A navigation pointer should be used in eonjunetion with p. Choice 3 *p++ causes p to be incremented before the dereference is performed, because the autoincrement operator has higher precedence than the indirection operator. (Ans) Choice 4 The condition of@ while loop must be a Boolean expression. The condition should be n= 0. Choice 5 An array cannot be initialized to a variable size. The subscript n should be removed from the definition ofthe parameter p. 308. How is a variable accessed from another file? Choice 1 The global variable is referenced via the extern specifier.[Ans] Choice 2 The global variable is referenced via the auto specifier. Choice 3 The global variable is referenced via the global specifier, Choice 4 The global variable is referenced via the pointer specifier. Choice $ The global variable is referenced via the ext specifier. 309. When applied to a variable, what does the unary “&” operator yield? Choice 1 The variable’s value Choice 2 The variable’s binary form Choice 3 The variables address [Ans] Choice 4 The variable’s format Choice § The variable’s right value 310. * sysiedefth */ Wif defined(_STDC__ || defined(_cplusplus) Hidefine __P(protos) protos Helse #define _P(prot0s) 0 Yendit P* sidion*/ include iv t div_P(nt, int) 236 C PROGRAMS WITH SOLUTIONS The code above comes from header files for the FreeBSD implementation ofthe C library What is the primary purpose of the __P() macro? Choice 1 The _PO macro has no function and merely obfuscates library function declarations. It should be removed from further releases of the C library Choice 2 The _P() macro provides forward compatibility for C++ compilers, which do not recognize Standard C prototypes. Choice 3 Identifiers that begin with two underscores are reserved for C library implementations, It is impossible to determine the purpose of the macro from the context given. Choice 4 The __P() macro provides backward compatibility for K&R C compilers, which do not recognize Standard C prototypes. [Ans] Choice § The _P( macro serves primarily to differentiate library functions from application-specific functions. 311. Which one of the following is NOT a valid identifier? Choice 1 __ident Choice 2 auto [Ans] Choice 3 bigNumber Choice 4 942277 Choice § peaceful_in_space 312. int read_ong_string (const char ** const buf) { char * p = NULL: const char * fwd = NULL size_tlen=0; assert(bud; do { p=realloc(p, len += 256); itp) return 0; if (!fwd) fwd =p; else fwd = strchi(p, 0; C Desucanc 237 } while (fgets(fwd, 256, stdin); *buf= ps return 1; } ‘The function read_long_string(), defined above, contains an error that may be particularly visible under heavy stress. Which one of the following describes it? Choice 1 The write to *buf is blocked by the const qualifications applied to its type. Choice 2 If the null pointer for char is not zero-valued on the host machine, the implicit ‘comparisons to zero (0) may introduce undesired behavior, Moreover, even if successful, it introduces machine-dependent behavior and harms portability. Choice 3. The symbol stdin may not be defined on some ANCI C compliant systems, Choice 4 The else causes fwd to contain an errant address, (Ans) Choice § Ifthe call to realloc() fails during any iteration but the first, all memory previously allocated by the loop is leaked. 313. FILE *f= fopen( fileName, “1” ); readData( f ); i 2772) { puts( “End of file was reached” }; ‘Which one of the following can replace the 77? in the code above to determine if the end of a file has been reached? Choice 1 f== EOF[Ans} Choice 2 feof £) Choice 3 eof f) Choice 4 == NULL Choice 5 If 314, Global variables that are declared static are Which one of the following correctly completes the sentence above? Choice 1 Deprecated by Standard C Choice 2 Internal to the current translation unit 238 C PROGRAMS WITH SOLUTIONS Choice 3 Visible toall translation units Choice 4 Read-only subsequent to initialization Choice § Allocated on the heap[Ans] double read_double (FILE * fp) { double d; assert(fp != NULL); feanilfp, “ %lt™, ds return d; } The code above contains a common error. Which one of the following describes it? Choice 1 fScanf{) will fail t match floating-point numbers not preceded by whitespace, Choice 2 ‘The format specifier %If indicates that the corresponding argument should be Jong double rather than double, (Ans) Choice 3 The call to fseanf{) requires a pointer as its last argument Choice 4 The format sp fier %If is recognized by fprintf() but not by fscanfi). Choice § d must be initialized prior to usage, 315. Which one of the following is NOT a valid C identifier? Choice 1__S Choice 2. 1__ [Ans] Choice 3__I Choice 4 Choice 5S 316. According to Standard C, what is the type of an unsuffixed floating-point literal, such as 123.45? Choice 1 long double Choice 2 Unspecified Choice 3 float{Ans Choice 4 double Choice 5 signed float C Dewucawc 239 317. Which one of the following is true for identifiers that begin with an underscore? Choice 1 They are generally treated differently by preprocessors and compilers from other identifiers Choice 2 They are case-insensitive, (Ans) Choice 3 They arc reserved for usage by standards committees, system implementers, and compiler engineers. Choice 4. Applications programmers are encouraged to employ them in their own code in order to mark certain symbols for internal usage. Choice § They are deprecated by Standard C and are permitted only for backward compatibility with older C libraries. 318. Which one of the following is valid for opening a read-only ASCII file? Choice 1 fileOpen (filenm, “r"); Choice 2 fileOpen (flenm, “ra"); Choice 3 fileOpen (filenm, “read” Choice 4 fopen (filenm, “read”) Choice 5 fopen (filenm, “r"):[Ans] 319. fopen( filename, “t”); Referring to the code above, what is the proper definition forthe variable f? Choice 1 FILE f Choice 2 FILE *f[Ans] Choice 3 int f Choice 4 struct FILE f Choice § char *f 320. If there is a need to see output as soon as possible, what fimetion will force the output from the buffer into the output stream? Choice 1 sushi) Choice 2 ovtput((Ans) Choice 3 filush() Choice 4 dump() Choice § writed) 240 C PROGRAMS WITH SOLUTIONS 321. short int x; /* assume x is 16 bits in size * ‘What is the maximum number that can be printed using printf("%édin", x), assuming that xis initialized as shown above? Choice 1127 Choice 2.128 Choice 3 255 Choice 4 32,767 [Ans] Choice 5 65,536 322. void crash (void) ‘ printi(“got here *((char *) 0) = 0; ) ‘The function crash), defined above, triggers a fault in the memory management hardware for many architectures, Which one of the following explains why "got here" may NOT be printed before the crash? Choice 1 The C standard says that dereferencing a null pointer causes undefined behavior. This may explain why printi() apparently fails. Choice 2 If the standard output stream is buffered, the library buffers may not be flushed before the erash occurs. (Ans) Choice 3 printi() always buffers output until a newline character appears in the buffer Since no newline was present in the format string, nothing is printed. Choice 4 There is insufficient information to determine why the output fails to appear, A broader context is required Choice 5 printi() expects more than a single argument, Since only one argument is given, the crash may actually occur inside printf(), which explains why the string is not printed. puts() should be used instead. 323. char * dwarves [] = { “Happy”, “Grumpy” “Sneezy”, C Deuccnc 241 “Bashful”, u How many elements does the array dwarves (declared above) contain? Assume the C compiler employed strictly complies with the requirements of Standard C. Choice 14 Choice 2 S[Ans] Choice 3.6 Choice 47 Choiee $ 8 324, Which one of the following can be used to test arrays of primitive quantities for strict equality under Standard C? Choice 1 qsort0) Choice 2 bemp() [Ans] Choice 3 mememp() Choice 4 strxiim() Choice § bsearch() 328. int debug (const char * fit, ..) { exten FILE * logfile; va_list args; assert(fint); args = va_arg(fint, va_list) return viprint{(logt } The function debug(), defined above, contains an error. Which one of the following describes ie Choice 1 The ellipsis is a throwback from K&R C. In accordance with Standard C, the declaration of args should be moved into the parameter list, and the K&R C macro va_argQ should be deleted from the code. Choice 2 viprinti() does not conform to ISO 9899: 1990, and may not be portable. Choice 3 Library routines that accept argument lists cause a fault on receipt of an empty fimt, ares); list. The argument list must be validated with va_null() before invoking vfprint{O, Choice 4 The argument list args has been improperly initialized. [Ans] 242 326. 327. C PRocRAMS WITH SOLUTIONS Choice 5 Variadie functions are discontinued by Standard C; they are legacy constructs from K&R C, and no longer compile under modem compilers. ‘char *buffer = "0123456789"; char *ptr = buffer; pirt=5; printf “9ésin”, ptr); print “s\n”, butter ‘What will be printed when the sample code above is executed? Choice 1 0123456789 56789 Choice 2 5123456789 5123456789 Choice 3.56789 56789 Choice 4 0123456789 0123456789 Choice 5 56789 0123456789 [Ans] char * get_rightmost (const char * d) ‘ char rightmost [MAXPATHLEN]; const char * p= ds assert(d != NULL); while ("d != 0") ( if¢d="") PaCd= D0) 2dt tip ay 3 memset(rightmost, 0, sizeof(ightmost)); ‘momepy(rightmost,p,stlen(p) + 1); retutn rightmost ) ‘The function get_rightmost(), defined above, contains an error. Which one of the following, describes it? Choice 1 The calls to memset{) and memepy() illegally perform a pointer conversion on rightmost without an appropriate cast, C Desucama 243 Choice 2 The code does not correctly handle the situation where a directory separator ‘7 isthe final character. [Ans] Choice 3 The if condition contains an incorrectly terminated character literal Choice 4 memepy() cams be used safely to copy string data Choice $ The return value of get_rightmost() will be invalid in the caller’s context, 328. What number is equivalent to -4¢3? Choice 1 4000 [Ans] Choice 2 -400 Choice 3 40 Choice 4 004 Choice 5 0004 329. void freeList( struct node *n ) { while(n ) ead } Which one of the following can replace the 7927 for the function above to release the ‘memory allocated to a linked list? Choice 1 n= n->next; free( ns Choice 2 struct node m =n; n= n->next; free( m ); Choice 3 struct node m=n; freon); n= Choice 4 free( n ne>next; [Ans] Choice § struct node m-=n; free( m J; m= n->next; (Ans) next 330. How does variable definition differ from variable declaration? Choice 1 Definition allocates storage for a variable, but declaration only informs the ‘compiler as to the vatiable’s type. Choice 2 Declaration allocates storage for a variable, but definition only informs the compiler as to the vatiable’s type. Choice 3. Variables may be defined many times, but may be declared only once.[Ans] 244 331. 332. C PRocRAMS WITH SOLUTIONS Choice 4 Variable definition must precede variable declaration, Choice § There is no difference in C between variable declaration and variable definition. int x)= (1,2, 4,5}: int; int *ptr =x; for( u= t printi(“%ode”, x{u)) } print “in” yu<5;us+) Which one of the following statements could replace the 772? in the code above to cause the string 1-2-3-10-5- to be printed when the code is executed? Choice 1 *pir +3 ~10; Choice 2 *ptr{ 3 ]= 10; Choice 3 *(pir +3) = 10;[Ans} Choice 4 (epi) 3 ]= 105 Choice § *(ptr{ 3 1)= 10; suum_array() has been ported from FORTRAN. No * logical changes have been made* double sum_array(double df] int n) { register int i; double total=0; assert(d!=NULL); fortimtjic-niit+) total]; return total; ) ‘The function sum_array(), defined above, contains an error. Which one of the following accurately describes it? C Desuccc 245 Choice 1 ‘The range of the loop does not match the bounds of the array d. Choice 2 The loop processes the incorrect number of elements. Choice 3 total is initialized with an integer literal. The two are not compatible in an assignment. [Ans] Choice 4 ‘The code above fails to compile if there are no registers available fori Choice § The formal parameter d should be declared as double * d to allow dynamically allocated arrays as arguments. 333. #inelude void fune() { intx=0; static int y= 0; xe printf “%d ~ Y%din”, x, ¥ )s ) intmaing) { func; funeQs retum 0; ) What will the code above print when it is executed? Choice 11-1 Choice 21-1 Choice 31-1 Choice 41-0 Choice § 1-1 334, int fbonacei (int) { switch (n) 246 336. C ProcRAMS WITH SOLUTIONS { default: retum (fibonacei(n - 1) + fibonacei(n -2)); cease | case 2: } return 1; } ‘The function above has a flaw that may result in a serious error during some invocations, Which one of the following describes the deficiency illustrated above? Choice 1 For some values of n, the environment will almost certainly exhaust its stack space before the calculation completes.[Ans] Choice 2. An error in the algorithm causes unbounded recursion for all values of. Choice 3. break statement should be inserted after each ease, Fall-through is not desirable here. Choice 4 The fibonacci() function includes calls to itself. This isnot directly supported by Standard C due to its unreliability Choice 5 Since the default case is given first, it will be executed before any case ‘matching n. 1 applied (0 a variable, what does the unary “&" operator yield? Choice 1 The variable’s address [Ans] Choice 2 The variable’s right value Choice 3 The variable’s binary form Choice 4 The variable’s value Choice § The variable’s format short int x; * assume x is 16 bits in size * What is the maximum number that can be printed using printt(*%din", x), assuming that x is initialized as shown above? Choice 1127 Choice 2 128 Choice 3255 Choice 4 32,767[Ans} Choice 5 65,536 C Desucanc = 247 337, intx=011 | Ox10; ‘What value will x contain in the sample code above? Choice 13 Choice 2 13 [Ans] Choice 3.19 Choice 4 25 Choice $ 27 338, Which one of the following calls will open the file testtxt for reading by ete? ”) Choice 1 fopent “test. Choice 2 read( “test.txt” ) Choice 3 fileopen( “test.txt”, “1” ): [Ans] Choice 4 fread “testext” ) Choice 5 freopen( “test.txt” ) 339, intm=— 14; intn=6; m<< (0m) & 3; Assuming two's-complement arithmetic, which one of the following correctly represents the values of m, n, and o after the execution of the code above? Choice 1 m==26,n=-7,0=0 Choice 2 2, n=—4,0=—2 (Ans) Choice 3: m=~26,n=-5,0=-2 Choice 4 m=-104,n=-7,0=0 Choice § m=~52,n=-6,0-0 340. How do printii’s format specifiers %e and numbers? differ in their treatment of floating-point Choice 1 %e displays an argument of type double with trailing zeros; %6f never displays trailing zeros. Choice 2 %e displays a double in engincering notation if the number is very small or very large. Otherwise, it behaves like %f and displays the number in decimal notation 248 C PROGRAMS WITH SOLUTIONS Choice 3» always displays an argument of type double in decimal notation. [Ans] always displays an argument of type double in engineering notation; Yt Choice 4 %e expects a corresponding argument of type double; corresponding argument of type float, Choice 5 %e and %f both expect a corresponding argument of type double and format it identically. %e is left over from K&R C; Standard C prefers %f for new code. ot expects a 341. S$Except 1 all choices are O.K.$8 © = getehar(); What is the proper declaration for the variable e in the code above? Choice 1 char *e; Choice 2 unsigned int ¢; Choice 3 inte: Choice 4 unsigned char e; Choice 5 char c;[Ans] 342. Which one of the following will define a function that CANNOT be called from another source file? Choice 1 void function() {..} Choice 2 exten void function() {.. } Choice 3 const void function() { .. } Choice 4 private void function { .. } [Ans] Choice § static void function) { ..} Chapter Ans. Ans. Ans. |. Write aC 5 SAMPLE QUESTIONS Base class has some virtual method and derived class has a method with the same name. If we initialize the base class pointer with derived object, calling of that virtual method will result in which method being called? (a) Base method (6) Derived method. o - For the following C program define AREA(8)(3.14*X"x) main() {Mloatr1=6.25,72-2.5. a-AREA(H); printf(‘in Area of the circle is %f”, a: s-AREA(2); printi(‘in Area of the circle is %f”, a); ) What is the output? Area of the eile is 122.656250 Area of the citele is 19.625000 rogram to find the sum of numbers between 1 and n, Program: maing) { int n, i, s= 0; seanfi(“%od”, &n): sin, i) +i; for Printf (“in sum = %.d", 8); ) 249 250 C PROGRAMS WITH SOLUTIONS 4. voidmainQ) { intd=5; printh(“%ot "ds ) Ans. Undefined 5. voidmain) { intis for(i switch() ‘case 1: printit“%d",)sbreak; { case 2-printi(“Yod”,i;break; case 3-printi(“Yod”,i);break; switeh(i) ease 4sprinti(“%d",i); d Ans. 1234 6. void main) { char *5-"\12345sin" printht"%d"” sizeo's)) } Ans. 6 7. void main() ‘ unsigned i-1; unsigned char k= -1 => k-255;* signed j>-l; * char k= +1 (/* unsigned or signed int k= -1 ini) printf“less”); else ini) Ans. Ans. Ans. SAMPLE QuesTIONS 251 printf(“greater”); else ifti=<) printf(“equal”); ) less void main() { float; j=1000*1000; printi("%4f "4s ) 1, 1000000 2. Overflow 3. Exor 4, None 4 ). How do you declare an array of N pointers to functions returning pointers to functions returning pointers to characters? ‘The first part of this question can be answered in at least three ways: 1. char *(*(*a[N}O0; 2. Build the declaration up incrementally, using typedef: typedef char *pe;_/* pointer to char * typedef pe fpe(); —_/* function returning pointer to char * typedef fpe *pfpe:_/* pointer to above */ typedet pipe fpfped; function returning... * typedef fptpe *pfpfpe; / pointer to. * pffpe a[N]; 1 amay of. */ 3. Use the edecl program, which tums English into C and vice-versa: cedecl> declare as array of pointer to function returning pointer to function retuming pointer to char char *(4(*aL) OO cedecl ean also explain complicated declarations, help with casts, and indicate which set of parentheses the arguments go in (for complicated function definitions, like the one above) Any good book on C should explain how to read these complicated C declarations “inside ‘out” to understand them (“declaration mimics use”) 252 10. 12. Ans. 13. Ans. 14. Ans. 18. C PROGRAMS WITH SOLUTIONS ‘The pointer-to-function declarations in the examples above have not included parameter type information. When the parameters have complicated types, declarations can *really* ‘get messy. (Modem versions of edecl can help here, too.) Astrueture pointer is defined of the type time . With 3 fields min,sec hours having pointers to intergers. ‘Write the way to initialize the 2nd element to 10. In the above question an array of pointers is declared, Write the statement to initialize the 3rd element of the 2 element to 10; int f) void main fs £2); £0.23); } Aint int intk) t printt("%od %od Ye) ) ‘What are the number of syntax errors in the above? None. void main() t inti~ printht-Yodi-ti-); } 56 define one 0 ifdef one printi(“one is defined ”); ifndef one printit“one is not defined" “one is defined” voidmaing { int count=10,*temp sum-0; temp=8count; SAMPLE Questions 253 temp=∑ “temp-count, printf(“%d %d %d count, “temp sum); ) Ans. 202020 16. What is alloca()? Ans. It allocates and frees memory after use‘after getting out of scope. 17. main() print retum i>0 2 main():0; ) Ans, 321 18, char *f000) ‘ char result{100)); strepy(rosult,“anything is good”); return(result); , ‘void main) { char #5 jrfood prints"); ’ Ans. anything is good. 19. voidmaing { char *s()={ “dharma”, hewlett-packard” char * 5 Ps prints"; +**p); jemens”,"ibm"}; 254 Ans. 20. Ans. 21. C ProcRams wiTH SoLUTIONS prine("%s".*p+-+) prinif%s",-"p)s } “arma” (p>add(dharma) &:& (*p)->harma) “arma” (after printing, p->add(hewlett-packard) &&(*p)>harma) “ewlet-packard” Output of the following program is main() {imti-0; forti=0 {switeh() case it cease |: case 5: defaultit—d; break;} printh%d,",i); ) ) (a) 059.1317 () $9,13,17 (©) 1211722 (@ 1621 (©) Syntax error @ What is the ouptut in the following program? main() fohar ©-64; iin32 unsigned int u-=16; ite) {print(“pass! iffe mand) { char sI[]-“Rameo"; char s2[]="Systems”; 182; printi%s"s)) ) Compilation error giving it eannot be an modifiable value! Find the output forthe following C program. Hinclude smain() { char *pl; char *p2; Ans. 32. Ans. 33. Ans. 34. Ans. 35. pl=(char *) malloc(25); p2-(char *) malloe(25); steepy(pl,“Rameo"); strepy(p2,"“Systems”); steeat(p1,p2}; printt"%s" pt); ) RamooSystems Write a funetion in C to ealeulate n! int fact (int k) { in P= 1, sick +4) for (i P=ptis return (P); } Find the output for the following C program. 4H define TRUE 0 some code while(TRUE) { some code ) This won't go into the loop as TRUE is defined as 0 struct list int; struct list *next; head; the struct head.x ~100 Is the above assignment to pointer is correct or wrong ? Wrong ‘What is the output of the following ? itis SAMPLE QUESTIONS 259 260 Ans. 36. Ans. 37. 38. C PROGRAMS WITH SOLUTIONS el; oti print%dis 4 FILE *fpl,*ip2; {pl-topenc“one”, fp2=fopen(“one",w") fpute(‘A’,fp1) fpute(B"fp2) felosettp!) felose(tp2) Find the Error, If Any? no error. But It will over writes on same file ‘What is the output for the following ? Program: w) ‘main { intx= 5; while (x= =1) xoxo! print (*%d\n”, x); } Output: ‘The while loop will not be executed because the condition is false and the value of x will be printed. x=5. Write a C program to find the square root of a given number ‘main { float x; seani{"%f”, 8x); printf("n square root of %.6.2f is %6.2E", x, sqrt(x))s Samrue Questions 261 39. Hdefine MAN(xy) (x)>(9)208:(9) finti=10; 5 ko; IEMAXGH, 149 printed % %od Md); } Ans. 1050 40. voidmaing { int printhYod" +14); , Ans. 56 SHORT QUESTIONS AND ANSWERS Chapter ‘Ans. - What is C language? Ans. The C programming language is a standardized programming language developed in the carly 1970s by Ken Thompson and Dennis Ritchie for use on the UNIX operating system. It has since spread to many other operating systems, and is one of the most widely used programming languages. . What is the output of printt(“%d")? Ans, 1, When we write printf(“%d",x); this means compiler will print the value of x. 2. When we use %d the compiler internally uses it to access the argument in the stack (argument stack). Ideally compiler determines the offset of the data variable depending on the format specification string. Now when we write print("%d".) then compiler first accesses the fop most element in the argument stack of the printf which is %d and depending on the format string it calculated to offset to the actual data variable in the memory which is to be printed. Now when only %d will be present in the printf then compiler will calculate the correct offset (which will be the offet to access the integer variable) but as the actual data object is to be printed is not present at that memory location so it will print what ever will be the contents of that memory location. 3. Some compilers check the format string and will generate an error without the proper ‘number and type of arguments for things like printf...) and seanf..) What is the difference between “calloc(..)" and “malloc(..."? 1. calloc(..) allocates a block of memory for an array of elements of a certain size. By default the block is initialized to 0, The total number of memory allocated will be (aumber_of_clements * size). ‘malloc(.) takes in only a single argument which is the memory required in bytes. malloe(..) allocated bytes of memory and not blocks of memory like eal.) 2. mallloc(..) allocates memory blocks and returns a void pointer to the allocated space, or [NULL if there is insufficient memory available. calloc(..) allocates an array in memory with elements initialized to 0 and returns a pointer to the allocated space, ealloc(..) calls malloc(..) in order to use the C+ _set_new_mode function to set the new handler mode. 262 8 SHORT QUESTIONS AND ANSWERS 263 |. What is the difference between “printf(..)” and “sprintf(..)"? - sprintf(..) writes data to the character array whereas printf...) writes data to the standard ‘output device. How to reduce a final size of executable? ize of the final executable can be reduced using dynamic linking for libraries. Can you fell me how to check whether a linked list is circular? Create two pointers, and set both to the start ofthe list. Update each as follows: while (pointer!) { pointer] = pointerl->next; pointer2 = pointer2->next; if (pointer?) pointer2=pointer2>next; if (pointer == pointer2) { print (“eireular”); ) ) Ifa list is circular, at some point pointer2 will wrap around and be cither at the item just before pointerl, or the item before that. Either way, its either 1 or 2 jumps until they meet /. “union” Data Type What is the output of the following program? Why? Hinelude main() { typedefunion { inta; char {10} float c; } Union; Union xy xa> 50; steepy(x., hello”); xe" 21.50; printf(“Union x : %d %s %f n"x.a.x.b3x.0); print Hl Write out a function that prints out all the permutations of a string. For example, abe would give you abe, acb, bac, bea, cab, cba. {100}; Union y = %d %s %fn" yayby.c); 264 C ProcraMs WITH SOLUTIONS void PrintPermu (char *sBegin, char* sRest) { intiLoop; char cTmp; char eFLetter{1]; char *sNewBegin; char *sCur; intiLen; static int Count; iLen = strlen(sRest); if (Len = 2) Count; print("%d: iCount++; s\n" iCount sBegin, sRest); printhed: %s7%e%e\n"iCount,sBegin sRest{ 1}, sRest[0)); return; } else if Len —= 1) { Counts; printi(“%ed: %s%sin", ‘Count, sBegin, sRest); return; ) else { / swap the frst character of sRest with each of ‘the remaining chars recursively call debug print Sur = (char*)malloetiLen); sNewBegin = (char*)malloc(iLen); for (iLoop = 0; ‘Loop < iLen; iLoop ++) { strepy(sCur, sRests stropy(sNewBegin, sBegin); eTmp = sCurliLooph; sCurfiLoop] = sCur(0]; sCur{0] = eT mp; sprinf(cBLeter, “%e", sCur[0)); strcai(sNewBegin, eFLetter); ‘include main() ‘ char far er = 0x188000000 ; FILE “fp; int offset char oh 5 IFC fp = fopen (* ‘ printf “nUnable to open file”); exit() ; ) {!veads and writes to file for (offset = 0; offset < 160 ; offset) {print (fp, “%e”, peckb (ser, offset }) ; erdat”, “wh” )) == NULL) folose ( fp); if ( (fp = fopen ( "serdat”, { printf (“inUnable to open file” ); exit() 5 ) {I reads and writes to file for ( offset = 0 ; offset < 160 ; offet+) { fcant (fp, print ( ) felose ( fp); ) ‘What is conversion operator? y") = NULL) Yoo", Bech); ch); class can have a public method for specific data type conversions. for example: class Boo { 28. Ans. 26. Ans. SHORT QuESTIONS AND ANSWERS 271 double value; public: Bootint i) ‘operator double() { return value; } % Boo BooObject; double i= BooObject; /! assigning object to variable i of type double, now conversion operator ‘gets called to assign the value. What is the difference between malloc()/free() and new/delete? alloc allocates memory for object in heap but doesn't invoke object's constructor to initiallize the object. new allocates memory and also invokes constructor to initialize the object. ‘malloc() and free) do not support object semantics Does not construct and destruct objects string * ptr= (string *)(malloc (sizeofistring))) ‘Are not sale Does not calculate the size of the objects that it construct Returns a pointer to void int *p= (int *) (malloe(sizeoftint)); int *p = new int; Are not extensible new and delete can be overloaded in a class “delete” first calls the object’ termination routine (ie. its destructor) and then releases the space the object occupied on the heap memory. If an array of objects was created using new, then delete must be told that it is dealing with an array by preceding the name with an empty []- Int_t *my_ints = new Int_s[10]; delete [Jmy_ints What is the difference between “new” and “operator new” ? “operator new” works like malloc. 272 27. Ans. 28. Ans. 29. Ans. C PRocRAMS WITH SOLUTIONS What is difference between template and macro? ‘There is no way for the compiler to verify that the macro parameters are of compatible types. The macro is expanded without any special type checking, If macro parameter has a postincremented variable ( like c++ ), the increment is performed ‘two times, Because macros are expanded by the preprocessor, compiler error messages will refer to the expanded macro, rather than the macro definition itself. Also, the macro will show up in expanded form during debugging. for example: Macro: define ming, j) (i Pmin ¢Fi,7)) { retum i> and << may be used for /O operations because in the header, they are overloaded, 2) Ina stack class itis possible to overload the + operator so that it appends the contents of | cone stack to the contents of another. But the + operator still retains its original meaning, relative to other types of data, What are Templates? C++ Templates allow u to generate families of functions or classes that can operate on @ variety of different data types, freeing you from the need to create a separate function or class for each type, Using templates, u have the convenience of writing a single generic function or class definition, which the compiler automatically translates into a specific version of the function or class, for each of the different data types that your program actually uses. Many data structures and algorithms ean be defined independently of the type of data they work with, You can increase the amount of shared code by separating data-dependent portions from data-independent portions, and templates were introduced to help you do that, ‘What is the difference between dynamic binding and static binding? Dynamic Binding : The address of the fimetions are determined at runtime rather than @ compile time. This is also known as “Late Binding” Static Bini ‘The address of the functions are determined at compile time rather than @ run time. This is also known as “Early Binding”. . What is difference between C/CH? C does not have a class/object concept (C++ provides data abstraction, data encapsulation, Inheritance and Polymorphism. C+ supports all C syntax. In C passing value to a function is “Call by Value" whereas in C++ its “Call by Reference” File extension is cin C while cpp in C-+.(C- but C compiler can not!) compiler compiles the files with c extension In C structures can not have contain functions declarations. In C++ structures are like classes, so declaring functions is legal and allowed, (C++ can have inline/virtual functions for the classes. SHORT QUESTIONS AND ANSWERS 279. t+ is C with Classes hence C++ while in ¢ the closest u can get to an User defined data type is struct and union, Why doesn’t the following code give the desired result? int x = 3000, y= 2000 ; long intz=x* y; Here the multiplication is carried out between two ints x and y, and the result that would ‘overflow would be truncated before being assigned tothe variable z of type long int. However, to get the correct output, we should use an explicit cast to force long arithmetic as shown, below: long int z= (long int) x * y; Note that (ong int (x * y ) would not give the desired effect. . Why doesn’t the following statement work? Ans. cchar str{ ] = “Hello” ; streat ( str,” ) 5 ‘The string function strcat{ ) concatenates strings and not a character. The basic difference between a string and a character is that a string isa collection of characters, represented by an array of characters whereas a characteris a single character. To make the above statement ‘work writes the statement as shown below: slrcat (str, I") 5 . How do I know how many elements an array ean hold? Ans. The amount of memory an array can consume depends on the data type of an array, In DOS, environment, the amount of memory an array can consume depends on the current memory ‘model (ce. Tiny, Small, Large, Huge, ete.). In general an array cannot consume more than 64 Kb, Consider following program, which shows the maximum number of clements an array ‘of type int, float and char can have in case of Small memory model. main() { intif32767) ; float 1116383] ; ‘char s[65535] ; } { QUESTIONS Chapter 12. 13. 14, 15. 16. 17. 18. 19. 20. 21. 22. 23. 24, What is a compiler? How is a C program run? How is a C program compiled usually? Are upper and lower case equivalent in C? What the two different kinds of error which can be in a program? Write a command to print out the message “Wow big deal”. Write a command to print out the number 22. Write two commands to print out “The 3 Wise Men” two different ways, |. Why are there only a few reserved command words in C? ). What is an operating system for? . What is a pseudo-device name? If you had a C source program which you wanted to call ‘accounts’ what name would you save it under? ‘What would be the name of the file produced by the compiler of the program in 3? How would this program be run? How is a library fle incorporated into a C program? Name the most common library file in C. Is it possible to define new functions with the same names as standard library functions?” ‘What is another name for a library file? What is a block? ‘Name the six basic things which make up a C program, Does a C program start at the beginning? (Where is the beginning?) ‘What happens when a program comes to a } character? What does this character signify? ‘What vital piece of punctuation goes at the end of every simple C statement? ‘What happens if a comment is not ended? That is if the programmer types /* . to start but forgets the ..*/ to close? 280 Questions 281 28, Write a fmetion which takes two values @ and b and retums the value of (a*b). 26. Is there anything wrong with a function which returns no value? 27. What happens if function returns a value but it is not assigned to anything? 28, What happens if function is assigned to an object but that function returns no value? 29. How can a function be made to quit carly? 30, What isan identifier? 31. Say which of the following are valid C identifiers 1. Ralgh23 2. BOshillings 32. Write a statement to declare two integers called i and j 33. What is the difference between the types £Loat. and double? 34, What is the difference between the types in andunsigned int? 35, Write a statement which assigns the value 67 to the integer variable “I 36. What type does a C function retum by default? 37. If we want to declare @ function to retum Long =. places. Where are these? . it must be done in, at least, two 38, Writea statement, using the cast operator, to print out the integer part of the number 23.1256, 39. Is it possible to have an automatic global variable? 40. Name two ways that values and results can be handed back from a funetion, 41, Where are parameters declared? 42. Can a function be used directly as a value parameter? 43. Does it mean anything to use a fumetion directly as a variable parameter? 44. What do the symbols * and & mean, when they are placed in front of an identifier? 45. Do actual and formal parameters need to have the same names? 46. Define a macro called “birthda birthday falls 47. Write an instruction to the preprocessor to include to maths library math which describes the day of the month upon which your 48. A macro is always a number. True or false? 49. A macro is always a constant. True or false? 50. What isa pointer? 51. How is a variable declared to be a pointer? 282 52. 53. 56, Investigate what happens when you type the wrong conversion spi 87. 4. Why is itincorrectto declare: float. *number = 2 C PROGRAMS WITH SOLUTIONS What data types can pointers “point to"? ‘Write a statement which converts @ pointer to a character into a pointer to a double type. (This is not as pointless as it seems. Its useful in dealing with unions and memory allocation functions.) ‘Write a program which simply prints out: 6 .236+00. cifier in a program. e.g. ty printing an integer with © £ ora floating point number with Sc. This is bound to go wrong, = but how will it go wrong? ‘What is wrong with the following statements? 1. peinté (x); 2, printé ("td"); 3. printé (0; 4, printf ("Number = 84"); Hint : if you don't know, try them in a program! 58. What is a white space character? 60. 61. 2. 63. 64, 68. 66. 67. 68. 69. 70. nL. 2 2B. 4. Write a program which fetches two integers from the user and multiplies them together, Print out the answer. Try to make the input as safe as possible, Write a program which just echoes all the input to the output. Write a program which strips spaces out of the input and replaces them with a single newline character, scanf always takes pointer arguments. True or false? ‘What is an operand? Write a statement which prints out the remainder of $ divided by 2. divided by 2 to a variable called ‘Write a short statement which assigns the remainder of Write a statement which subtracts -5 from 10, Write in C: if 1 is not equal to 23, print out “Thank goodness for mathematics!” How many kinds of loop does C offer, and what are they? When is the condition tested in each of the loops? Which of the loops is always executed once? ‘Write a program which copies all input to output line by line. Write a program to get 10 numbers from the user and add them together. Given any array, how would you find a pointer to the start of i? How do you pass an array as a parameter? When the parameter is received by a function does C allocate space for a local variable and copy the whole array to the new location? Questions 283 75. Write a statement which declares an array of type double which measures 4 by S. What ‘numbers can be writen in the indicies of the array? 76. What are the two main ways of declaring strings in a program? 77. How would you declare a static array of strings? 78, Write a program which gets a number between 0 and 9 and prints out a different message for cach number. Use a pre-initialized array to store the strings. 79. What type of data is rotumed from mathematical functions? 80. All calculations are performed using long variables. True or false? 81. What information is retumed by strlen ()? 82. What action is performed by streat ()? 83. Name five kinds of error which can occur in @ mathematical function, 84. Which operators can be hidden inside other statements? 85. Give a reason why you would not want to do this in every possible case, 86, Is 21LE a reserved word? If'so why is it in upper case? 87. Write a statement which declares a file pointer called fp. 88, Enumerated data arc given values by the compiler so that it can do arithmetic with them, ‘True or false? 89. Does void do anything which C cannot already do without this type? 90. What type might a timer device be declared if it we 91. Write a statement which declares a new type “real” to be like the usual type “double” 92. Variables declared const. can be of any type. True or false? to be called by a variable name? 93. What distinguishes a bt pattern from an ordinary variable? Can any variable be abit pattern? 94, What is the difference between an inclusive OR operation and an exclusive OR operation? 98. Ifyou saw the following function call in a program, could you guess what its parameter was? 96. OpenWindow (BORDER | GADGETS | MOUSECONTROL | SIZING); 97. What is the difference between call by value and call by reference? 98. Find out what the denary (decimal) values of the following operations are: L762 2161 3.1963 1567 5.196783 ‘Try to explain the results, (Hint: draw out the numbers as binary patterns, using the program listed) 99. Find out what the denary (decimal) values of the following operations are: Lii2 211213 284 100. 101. 102. 103. 104, 10s. 106. 107. 108. 109. 10. im, 2. 13. 4. 1s. 116. 7. 1s. 19. 120. 12. 122. 123. C PROGRAMS WITH SOLUTIONS Find out the values of: Lis (1 2. 23 & (-23) 3. 2012 & ( 2) (Hint: write a short program to work them out, Use short type variables forall the numbers). ‘What are the following? 1. Filename 2. Fill pointer 3. File handle What is the difference between high and low level filing?” Write a statement which opens a high level file for reading, ‘Write a statement which opens a low level file for writing. Write a program which checks for illegal characters in text files. Valid characters are ASCII codes 10,13,and 32..126. Anything else is illegal for programs. ‘What statement performs formatted writing to text files? Print out all the header files on your system so that you can see what is defined where! What is the difference between a structure and a union? ‘What is a member? Ifx isa variabl how would you find out the value of a member called men. Ifptr is a pointer to a structure, how would you find out the value of a member called mem A union is a group of variables in a single package. True or false? ‘What is a structure diagram? How are data linked together to make a data structure? Every separate struct type in @ data structure has its own variable name. True or false? How are the members of structures accessed in a data structure? Write a statement which creates a new structure of type “struct Binary'Tree” and finds its address. Store that address in a variable which is declared as follows: struct BinaryTree *ptr; ‘What happens if the condition in a while loop is intially false? What is a null sting? Write a small program which makes a linked list, three structures long and assigns all their data to be zero. Can you automate this program with a loop? Can you make it work for any number of structures? ‘What is the output of printf(“%d")? What will happen if I say delete this? Differentiate between “C structure” and “ CoH structure”, Questions 285 124, Diffrentiate between a “assignment operator” and a “copy constructor". 128, What is the difference between “overloading” and “overridding”? 126. Explain the need for “Virtual Destructor”, 127. Can we have “Virtual Constructors”? 128. What are the different types of polymorphism? 129, What are Virtual Functions? How to implement virtual functions in 130, What are the different types of Storage classes? 131, What is Namespace? 132. What are the types of STL containers? 133. Differentiate between “vector” and “array”. 134, How to write a program such that it will delete itself after exectution? 138, Can we generate a C+ source code fiom the binary file? 136. What are inline funetions? 137. ‘Talk sometiming about profiling, 138, How many lines of code you have written for a single program? 139, What is “strstream” ? 140. How to write Multithreaded applications using C++? 141. Explain “passing by value”, “passing by pointer” and “passing by reference”. oui 142. Write any small program that will compile in “C” but notin 143. Have you heard of “mutable” keyword? 144, What is a “RTT”? 145. Is there something that I can do in C and not in C+? 146. Why preincrement operator is faster than postinerement? 147. What is the difference between “calloc” and “malloc” 148, What will happen if I allocate memory using “new” and fice it using “free” or allocate sing “alloc” and free it using “delete”? 149. What is Memory Alignment? 150. Explain working of printf 151. Differentiate between “printf” and “sprint?” 152. What is “map” in STL? 153. When shall I use Multiple Inheritance? 154, What are the techniques you use for debugging? 158, How to reduce a final size of executable? 156. Give 2 examples of a code optimization. 157. Is it possible to use multiple else with if statement? 286 158, 159, 160. 161. 162. 163. 164, 168. 166. 167. 168, 169. 170. im. 172. 173. 174. 178, 176. 177. 178, 179. 180. 181. 182. C PROGRAMS WITH SOLUTIONS Is it possible to use multiple default statements in switch () statement? ‘Why goto statement is avoided? ‘What are the limitations of switch() case statement? Can we put default statement anywhere in the switch () case structure? What happens iff you create a loop that never ends? Is it possible to ereate a for loop that is never executed? ‘What is a loop? Why itis necessary in the program? Is it possible to nest while loop within for loops? Is it possible to use multiple while statement with do statement? What are the values of NULL and !NULL? ‘What is the difference between (!0) and (10)? ‘Write the definition ofa function, How do functions help to reduce the program size? Differentiate between library and the user defined functions. How does a function work? Explain How arguments are passes and results are returned? List any five library functions and illustrate them with suitable examples. What are actual and formal argumnets? What are the uses of return statements? What does it mean if there is no return statement in the function? ‘What are void functions? ‘What is global pointer? ‘What is recursion? Explain its advantages, Explain types of recursions. Is it possible to call library functions recursively?

You might also like