0% found this document useful (0 votes)
29 views241 pages

C Notes

Uploaded by

Rahul Raj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
29 views241 pages

C Notes

Uploaded by

Rahul Raj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 241
SUMMARY sizeof (short) E t}woan) oot double ‘C\Users\aspe\Downoads\C programs of dennis itchi\floatarithmatc axe 2 int m int v print ("sd 7 float 10 float ia 13 Logs & others Covessods >) Search resuts x) Acie x Ould og > # BSiathere > float doublese ~ foot xithmetice ‘C\Users\josp”\Downloads\C programs of dennis ritchi\float double.e Logs 8 others ‘7 code:odks x) Search reuks =) Fcox x) OBuld op | ¢ Build messageQ1: what is the output of the following C program fragment: #include int main( print » printf » "Hello World!")); return 3 Prenat bred mune Kenko ce oi STROMA aR MCU RULE seta ld RRMA oc melon kel eRe Le Tes 100 Ra eet 12 and this printf function printsw 8 Siathere > questions anewers sete ‘CAUsers\aspADownlo, answers-ete return Logs 8 thes Coesiods >) Search esuts x] 2 Gne_» © Bul og fe: coo saxo RCSA LCM EMS) Cre Rod LOQ4: Which of the following statement/statements is/are correct corresponding to the definition of integer : Se ny MMOH MW Aelk Kec Sey MC antec tal unsigned i; ROM elec longi; POR MVAectecnc ag long int i; long long i; Crete Trae (s(t To UyQS: What does the following program fragment prints? main() { garbage i ss) Integer value depends from iiteCoaT i Rcomaale a9 NeTaT Kel mU-Ke olen} -3 in 2s complement representation: Se Rela Maid 3 = 00000000 00000000 00000000 00000011 a Keele) ea MUM °°) Step 2: Add 1 to the result. It will give 1111111 11111111 integer value that depends)3 (on my computer) Sree a omnes#include int main( printf ("%d return @; t int fun() { } printf ( Seto ol-Mel mia Zell) NLT main0 function only. Therefore fool to mainQ function. Trying to access variable ‘var’ outside main( function err R UR CUCL oa) scope is within that functionet aaee ana) Pete Ver ane) internal ilead eto Teall block are not ears outer block, Basic PRINCIPLE OF SCOPING paneer UES er-lacelll elm ele eee nicole eee this block is not visible to Cased CUE So net cee Pea eon outside to SUD lrg main() { var = 3; var = 4; printf("%d\n", var); printf("%d", var); a; main() { var = 3; { var = 4; print#("%d\n", var); y printf("%d", var); e; you are not redefining within same block#include int fun(); This variable is outside of all functions. Therefore calleda variable int main() { one return @; (orn ea) fun() printf ; It will access the GLOBAL variable. of global variable.pean ane Also called ited #define (NAME )value Bolo do) fll Kole -1o) a Urol meen) ole Lot o1.0 (MLR 1, stdio.h> 3.14159 3.14159 int main() { printf( )3 eR) Press any key to continue. as well as easy to write.TAKEAWAYS We can use macros like functions. #include #define add(x, y) x+y int main() { printf("addition of two numbers: %d", add(4, 3)); return @; 7 addition of two numbers: 7TAKEAWAYS @) WV eKeto MW ALM RAUL) cM Aa AY greater(x, y) if(x > y) \ printf("%d is greater than %d", x, y)3 \ else \ printf("%d is lesser than %d", x, y)} main() { greater(5, 6); as the values to x and yTAKEAWAYS 6) First expansion then evaluation. #include #define add(x, y) x+y int main() { printf("result of expre * ’ add(4, 3)) return @; Cece) r eeeTAKEAWAYS Some predefined macros like __DATE__, ——TIME__ can print current date and time. #include int main() { printf ("Dat printf ("Tim return 0; OK friends,WW conste - Codelocks 1601 Fla Edt View Search Project Sul Debug Fortian Smith Took Tole+ Plugins Dowylocks Settings Hap eagles xealaaiorsoa gerecccce us| em lo slh mem Bathee [conte = T tinctude Ant main() a prince ("td", var): 8 Ce ee (ewe RVR rea -e-Q1: What is the output of the following C program? ee Ome Ore Cyc etsirg rea a) print an octal valueQ2: What is the output of the following C program? #include Pn errs #define STRING "%s\n" b) Me ome te Nese #define NESO “Welcome to Neso Academy!" ce ¢) Garbage value int main() { a oleola Rode) printf(STRING, NESO); Academy! return 0; + rintf(STRING, NESO); printf("%s\n", "Welcome to Neso Academy!"); They are one and the same option d and not option b.Ivalue (left value) : simply means an object that has an identifiable location Cuma -aoln Amare are Kola Kels (0 ft) SNe ee aa lua am el MR ened cher cltl lvalue must be a variable because they have the (etel fell NaC Celt-min-Xe (ohio Ave Reel aha Toe ean Ao kee) oo CR RLS 8 rvalve (right value) : simply means an object that has no identifiable Tercera an rhe oedema tren sia Cer cera ole ~ Expressions lik-Eypregsions like (a¥'b) OStant valve. TU RI oomShort circuit in case of &&: simply means if there is a condition CT Ana oR Ra aod e oR UNO el Ral aR mo Lal} [oolaTe (eo Um ULM one of Rel elo com e POEL w yl m elm UySame ce aoe komme au Mae ee Rolie (ea) CIR etes aes URC Samana ces Reais [ooTaTe (reo Um ULM ode ot Reet 08 ude main() { int a int incr; iner = (a > b) || (b++)5 » incr);DY iaiai ais tain [ol] AWA] tN A S] NN ec] (o7 (0) aia hela) does x = 1, y = 2; //x = 1(00@@ 0001), y = 2(0000 0010) (x8y) //1&2 = @(@00@ 9000) printf("Result of x&y is 1"); (x&ay) printf("Result of x8&y is 1"); //18&2 = TRUE && TRUE = TRUE = 1 a Result of x&&y is 1.IMPORTANT POINTS 2.) Right shifting is equivalent to division by grightOperand VCH] Teese Output: 1 [3 / 2°] Vel Nea Crh ea a 2] MMi cc-a(e)e RCV AClIUe 16ASSIGNMENT OPERATOR Neo ete tesa nls ee nn ake eases Cer CRC Uc mee ee eel Link of video provided in the , ; ~ description This operator copies R-value to L-value Here the variable is L-valueC7 i 3 3 = 5 3 FS) ES Cy Bs o = 3 ro cI A ce = INTRODUCTION TO CONDITIONAL OPERATOR es Look and feel: char result; char result; Pala er Pla er if (marks > 33) result = (marks > 33) ? ‘p? : ea , CS i ieee } behavior of if-else construct.Quick FACTS CHECKLIST —— Conditional operator is the only ternary operator available in the list of operators in C language Asin |Expression ? Expression2 : Expression 3], expression! is the boolean expression. If we simply write @ instead of some erect eee Rue auch eect espe Cae Relea teice m ocray aed Travan result =@?2:1 rlComMaA (, ) OPERATOR — Comma operator can be used as an “operator”. int a = (3, 4, 8); 6 2) printf (“%d”, a); Comma operator returns the |rightmost |operand in the expression and it simply evaluates the rest of Se Ieee me UCTen ais case operands and finally reject them.oT Ta Mel eee UT RRO eee CURE RRS SNS Ce eee sae ag PO Sauna ee uch es ms tae This value will be returned to var after evaluating See aa a the first operand pan LCL dG se Tae a) A 2 printf (“%d”, var); SS \ It will simply not meats rejected. First evaluated and then rejected And finally we will print this‘Ee ComMMA (, ) OPERATOR ne Comma operator is having least precedence among all the operators available in C language. ca int a; pa rome) == | © Bo 4h Ge Pua AMAA ODE Othe)ComMMaA (, ) OPERATOR i Comma operator is having least precedence among all the operators available in C language. ee ee int a = 3, 4, B (elie Teena ee aE int a = 3, 4, 83 Peco Mar dcx) Melle eereltel ts int a = 3; int 4; int 8; Ertsst Tele) (ss aNComMMaA (, ) OPERATOR a Comma operator is having least precedence among all the operators available in C language. eee ae Frac a Cn PDB printf (“%d”, a); Stade Cae e Cieree each acd 5 baal Foresters Cuchi oie ieee) other operatorASSOCIATIVITY OF OPERATORS Ooty Sa ee Deere Mak ken eric M al acect cae Riel eae eee Someta ace keke ara ume ll ee tee ies ere Need cue 1) 7 AC 3 a Se ele fold Left to right: (10 /2)*5 = ( CMA ld Right to left: ot ee} And this one is not correct. Okay.PRECEDENCE AND ASSOCIATIVITY TABLE CATEGORY OPERATORS EN ra NVR Prue yD Teed (0 0 eran ree Ca Unary er rom tcal Cras as Multiplicative ices PU resnT ceed Chee Gad ieee POETS icyy Tree Ca enc a ena ee a CeCe ID) cota Coes Tree Ta Cae iamet ete van) ste renee Cia pene Cie elit hater Ie Right to left Assignment Stila ae ol aac eetOR accrues C nee [cl ee Prana =fun(); Ceca = operator is having less precedence as compared to () therefore, () belongs to fun and fun will be treated as a function. int var =(fun()); Ifsuppose = operator is having greater precedence then, fun will POR CIeE erin R icc eae: el variable, int (var =fun)();Cl ola eet) 11 Eg They are used to access members of structures. ATR el Xe LoL M Uo L CMR ACO 61 8 Postfix Increment/Decrement (++, --) Be Aoi mecca era eee eimai ecu ca Es Associativity of Postfix is also different from Prefix. Associativity of postfix operators is from left to right and that of prefix operators is from right to left. ’ is from left to right and that of fey ae) eM MCN ETe MCN (1aee ae ST Tan EFtTO) Ta c@} F a tad to rae ort ane Eee O ee UelOr h Pisa Cane fata ae int fun2() fee et sdar CCL Resale } Tonner ke) seh taed fun1() or fun2()? Itis not defined whether fun10 will be called first or whether fun20 will be called. Behaviour is undefined and. esc ee ca NOTE: Here associativity will not come into picture as we have just one operator and which function will be called first is undefined. Associativity will only work when we have more than one Cerrar gies ’ aNC standard is the language specification which is adopted by all C compilers across the globe. Te a SE ge ras ; Citis the latest revised version of C According to C99 standard: rele eleeRet tse A OE The sizeof operator yields the size (in bytes) of its CI a RM CM eM EC u terete marl Ts Coa ie at PEER (setae deel ey oy Tela operand. If the type of the operand is a variable length array type, then the operand is evaluated; Seo ae operand is not evaluated and the result is an intege! oleae aha We will talk about Therefore, i++ inside sizeof is not evaluated yoriable length y arrays later in this, course.Rigut SOLUTION ree Rey Cree ae sane d = b-- && --a; i A, Erma aT a printf (“%d %d %d %d”, d, c, b, a);What is the output of the following C program fragment? Saar] is int b = 1; eer res int d = b¥- && --a; printf(“%d %d %d %d”, d, c, b, a);ALE -l l(t Mehl Eure e (=| @) er) { t PIS eo StisdGe are ils=8 ile=g pa reeuee) | Cie ome sa re ea)ease Used to terminate from the loop Example: WAP to allow user to enter integers until he/she neler MM )- =) 5 10 15 20 int main() af int i for(i=0; i= @) aera tS { coo tls h printf (“Neso”) ; Therefore, the correct option is option d).What is the output of the following C program fragment? Assuming size of unsigned int is 4 bytes. #include int main() { Pesta eae eee Prete teen ea) stad a eee Pet Range of unsigned int (4 bytes) @ to 4294967295 When i reaches 4295967295, then Pete Me gee ames aeee oe tas Perea) ee mat Ura Ce TES therefore we come outside of the while loop. ae Mo TL aoa at ae hot) will contain 1 because of post dacs Cyr eos eee he printed on the screen. And due to rey an SURn-2 n-1 n n+1 n+2 if(j >= n-(4-1) && j |O Workspace 2 3 | int fact (int n) 4 jar 5 if(n == 1) 6 return 1; 7 else o 8 return n*fact (n-1); 9h) 10 a1 | int main() 12 far 13 int nj 14 print£("Enter the number: "); 15 scanf("d", &n); 16 print£("Factorial of a number td is $d", n, fact (n))7 a7 |) 18ney @ Divide the problem into smaller sub-problems. fe WRatehe r lad C) Fact(1) = 1 Fact(2) =2*1 = 2 * Fact(1) Fact(3) =3*2*41 = 3 * Fact(2) Fact(4) =4*3%*2*1 = 4 * Fact(3) Fact(n) = n * Fact(n-1) + i eeeRR MCs acs >) Specify the base condition to stop the recursion. fe WRatehe lad) Fact(1) = Fact(2) = 2*1 = 2 * Fact(1) Fact(3) = 3*2*41 = 3 * Fact(2) Fact(4) =4*3%*2*1 = 4 * Fact(3) Base condition is the one which doesn't require to call the same function again and it helps in stopping the recursion. el ee edoS lo) ig-vei mx =tal]eci[e)a) Sec PS Mee n exe eRe lic am elmo] RU oa aero Ne (Tea Sete Molde eam cco elo) fun()y{ TN all fun(); alsIndirect recursion A function (let say fun) is called indirect recursive if it calls another function (let say fun2) and then fun2 calls fun directly or indirectly. Structure of Indirect recursion: fun() { S funy) { Tol mal els fun2()3 ALO Fs . Tol ale elConsider the following recursive C function: void get(int n) { Rezarse mac aCe Perey Peseta aa If get(6) function is being called in main0 then how many times will the get0 function rman lsicieaccutiaehrohiraarela Oks (A) 15 (8) 25 (©) 35 (0) 45 [GATE 2015 - 2 Marks] . BNvoid get(int n) { Fears sa get(n-1); get(n-3); PO ae get(®) get (6) get(5) get(3) +6 calls get(4) get(2) +4 calls ace) Merce) ene get(2) get(@) get(1) get(-1) get (-2) All vere Be ’Determine, how many number of times the star will be printed on the screen: void fun1(int n) aed it ee y fun1(3) if (n > 1) for(i-03 i 1) count(n-1); sie, RD main() tT DFWhat will be the output of the following C program? void count(int n) ED} if LD) static int d = 1; ct printf("%d ", n); d) printf("%d ", d); ren PCM O Cree printf("%d ", d); Peta en main() come) count (3) ote TD FyWHAT is DATA STRUCTURE? Deen Ah enc mene ae ht Eire atel- ick Ie Merete erat Coeur kre ak Chat Celi Vr tee For Example: Array is a data structure which you can visualize as follows: w Imagine an array as a large chunk of memory divided into smaller block of memory and each block is capable of storing a data value of some type.int arr[10] = {1, ®, @, @, ®, 2, 3, ®, @, @}5 We want: - in position 0 - 2inpositionS - 3inposition6 int arr[1e] = {[@] = eae ay \ Marre) coda oLloM Reel so Kelclle sleek initialization. And each number in the square brackets is said to be a designator.FINALLY, NO ONE CAN STOP YOU FROM DOING THIS: int a[] = {1, 7, 5, [5] = 90, 6, [8] = 4}; Ea PECRT erence Cue UN RaaneT Leak si Cee enn related vee oie eenWB untied. Codelocks 1601 Fle Edit View Search Project Build Debug Fortran wiSmith Tools Tools+ Plugins DowyBlocks Settings Help [gGBM\e>/sealagiorson 1 finchude- 2 3 aint main’) { oP ee seen tior = cons s | iw € | prinee "enter the nunbe a | Beang(eas, ans 3 || BE| tne remy 10 4 wnttettbo) a fem = W410) 2 Eg(scentrem) == 1) B break rr confer 13 we wie ze} rf ie | sea 0) 3 rine ("Yes") 20 | aise 2 ee) 22 | return oF 2 |)rao Melted size of whole array Pee ee Soar Brom y ae eas wv sizeof (name_of_arr)/sizeof(name_of_arr[@])DEFINITION AND SYNTAX Multidimensional arrays can be defined as an array of arrays General form of declaring N-dimensional array is as follows: data_type name_of_array[size1][size2]...[sizeN]; For example: Th aes o A SCL Tae] a them in details eure aeclaa) ray race Aa es a Pe BNBSUS Cea OM ES 1g Mo Rg (MAL aa Loe) Puro (New Program) pra peste ee Cue Cae Te scanf("%d", &n); i Tas Pe rsa @ ese bana for(i=®; icn; i++) fi N VARIABLE LENGTH ARRAY scanf("%d ", &a[i]); SI y printf("Elements in reverse order are: \n"); for(isn-1; i=; i--) 7 y aT USS eor- Tne cello) length at the time of execution. printf("%d “, a[i]);POINTS TO BE NOTED Variable length arrays cannot have static storage duration. Variable Length Array does not have the initializer. It is not the case that you are specifying the length at the time of executionIMPORTANT POINTS Sg Pointer is a special variable that is capable of storing some address. p ad ECA eae huCKiGa aCioeaace| a Pp aI P In the next lecture we'll start with how to declare pointers.int x = 5; ST ra a ptr = &; address of operator Address of x is 1000. With the help of this statement we can assign this address to this pointer variable.aera BU al ard is equivalent to ptr = &; Therefore we can write these two lines in one single line.Neltetake crear are cae een eg nk Cuca ue ever bree Ae erage ema teeta sey Ce 3 int j 5 Pla ptr printé(“%d”, *ptr); VALUE OF rere MECC RU MeN Ril VoePerce ie SRea CRN tat ead eich any ac Peecntacs ap are int *ptr = ax; that is 1000 and with the help of this dereference operator or indirection operator or value of operator,ON] =a Ye) sia Assigning valve to an uninitialized pointer is dangerous. pa . Sees ras rent} Usually, Se ea) ores Lg Perna eee illegal memory ee 2) We the users have no rights to access the location.aC int *p, *q3 oo) q = Ps printf (“%d %d”, *p, *q); | Ourpur: 10 10 Therefore output of this program is 10 10. But please note thatNote: q = p is not same as *q = *p i = 10; il a Ps* minMax.c > void minMax(int arr[], int len, int *min, int *max) { ‘min ‘max = arr(0]; ty int for(i=lr iclen; i++) f af(arr[i] > *max) ‘max = arr[i]? ig(arr(i]

You might also like