You are on page 1of 172

DECISION MAKING AND BRANCHING

Introduction: C Language must be able to perform different sets of actions depending on the circumstances. A C program is a set of statements which are normally executed sequentially n the order in which they appear. This happens when no options or no repetitions of certain calculations are necessary. However,in practice, we have a number of situations where we may have to change the order of execution of statements based on certain conditions,repeat a group of statements until certain specified conditions are met. This involves a ind of decision ma ing to see whether a particular condition has occurred or not and then direct the computer to execute certain statements accordingly. #. (. ). !. C has ! decision ma ing instructions, They are" $f %&lse 'tatement 'witch 'tatement Conditional *perator 'tatement +oto 'tatement.

The IF Statement: The $, 'tatement is a powerful decision ma ing statement and is used to control the flow of execution of statements. The General form of IF statement is loo if-This condition is true. execute this statement/ The eyword 0$,0 tells the compiler that what follows is a decision control instruction.The condition following the eyword 0$f0 is always enclosed within a pair of 1arenthesis. $t allows the computer to evaluate the expression first and then depending on whether the value of the expression -relation or condition. is 0T23&0 -non%4ero. or ,AL'& -4ero.,it transfers the control to a particular statement. This point of program has two paths to follow one for the T23& condition and other is for ,AL'& condition. As a general rule, we express a condition using 0C0 relational operators, the following table shows how they are evaluated" Hierarchy of operators" *perator 5 7,8,9 ;, % <=,<>,=> >>,5> Type Logical 6*T Arithmetic and :odulus Arithmetic 2elational 2elational li e this"

?? AA > Demonstration of "IF" statement Example:1 main-. B

Logical A6@ Logical *2 Assignment

int num/ printf-C&nter a number less than #DC./ scanf-C9dC,?num./ if-num <> #D. printf-C How nice you areC./

E Description: *n execution of this program, if you type a number less than or equal to #D, you get a message on the screen through printf-.. $f you type some other number the program doesn0t do anything.

Demonstration Of If Statment
Example:1 main-. B int num/ printf-C&nter a number lessthan #DC./ scanf-C9dC,?num./ if-num<>#D. printf-C How nice you areC./ E Description: *n execution of this program, if you type a number less than or equal to #D, you get a message on the screen through printf-.. $f you type some other number the program doesn0t do anything. To ma e you comfortable with the decision control instruction one more example has been given below" Example:2 Fhile purchasing certain items,a discount of #D9 is offered if the quantity purchased is more than #DDD. $f quantity and price per item are input through the eyboard , while a program to calculate the total expenses. main-. B int qty,dis>D/

float rate,tot/ printf-C&nter quantity and rateC./ scanf-C9d9fC,?qty,?rate./ if-qty=#DDD. dis>#D/ tot>-qty7rate.%-qty7rate7dis8#DD./ printf-Ctotal &xpenses > 2s.9fC,tot./ E Here is some sample interaction with the program" &nter quantity and rate #(DD #G.GD Total expenses > 2s #HI!D.DDDDDD (DD #G.GD

&nter quantity and rate

Total expenses > 2s )#DD.DDDDD Description: $n the first run of the program, the condition evaluates to true, as #(DD -value of qty. is greater than #DDD. Therefore, the variable dis, which was earlier set to D,now gets a new value #D. using this new values total expenses are calculated and printed. $s the statement dis>D necessary J The answer is K&', since in C, a variable if not specifically initiali4ed contains some unpredic table values- garbage value.. Fe can even use Arithmetic &xpressions in the C$,C statement. ,or example all the following C$,C statements are valid. if-);(9G. printf-CThis wor sC./ if-a>#D. printf-C&ven this wor sC./ if-%G. printf-C'urprisingly even this also wor sC./

6ote That in C a non%4ero value is considered to be true, where as a 0D0 is considered to be ,AL'&.$n the first C$,C , the expression evaluates to G and since G is a non%4ero,it is considered to be T23&. Hence the printf-. gets executed $n the second C$,C , #D gets assigned to a so the if is now reduced to if-a. or if-#D. 'ince #D is a non%4ero, it is T23& hence again printf-. goes to wor . $n the third C$,C, %G is a non%4ero number, hence T23&. 'o again printf-. goes to wor . $n place of %G even if a

float li e ).#! were used it would be considered to be T23&.'o the issue is not whether the number is integer or float, or whether the number is positive or negative. $ssue is whether it is 4ero or non%4ero.

Multiple Statments With In If


$t may so happen that in program we want more than one statement to be execute if the expression following $, is satisfied.$f such multiple statements are to be execute then they must be placed within a pair of braces as illustrated in the following example. Example:3 87 calculation of Lonus78 main-. B int bonus, cy, yoi,yrMofMser/ printf-C&nter current Kear and Kear of NoiningC./ scanf-9d9dC,?cy,?yoi./ yrMofMser>cy%yoi/ if-yrMofMser=). B bonus>(GDD/ printf-CLomus>2s. 9dC,binus./ E E *bserve that here the two statements to be executed on satisfaction of the condition have been enclosed within a pair of braces. $f a pair of braces is not used then the C compiler assumes that the programmer wants only the immediately next statement after the if to be execute on satisfaction of the condition. $n the other words we can say that the default scope of the $, statement is the immediately next statement after it. The IF-E SE Statement: if. . .else statement is an extension of the simple $, statement. The !eneral form is: if-test condition. B True%Lloc E else B ,alse%Lloc E statement %x/ statement-s. statement-s.

"oints to #e remem#ered: #. The group of statements after the $, up to and not including the &L'& is called an C$, LL*COC. 'imilarly, the statements after the &L'& form the C&L'& LL*COC. (. 6otice that the &L'& is written exactly below the $,. The statements in the $, bloc and those in the &L'& bloc have been indented to the right. ). Had there been only one statement to be executed in the $, bloc and only one statement in the &L'& bloc we would have dropped the pair of Lraces. !. As with the $f statement, the default scope of &L'& is also the statement immediately after the &L'&. to override this default scope a pair of braces must be used. Let us consider an example of counting the number of boys and girls in a class. Fe can use code # for boys and ( for girls. % % % % % % % % % % % % % % %

% % % % % % % % % % % % % % % % if-code>>#. boy>boy;#/ if-code>>(. girl>girl;#/ % % % % % % % % % % % % % % %

% % % % % % % % % % % % % % % % Example:$ main-. B int a>)DD,b>#D,c>(D/ if-5-a=>!DD.. b>)DD/ c>(DD/ printf-Cb>9d c>9dC,b,c./ E *3T13T" b>)DD c>(DD

&xplanation" The condition -a=>!DD. evaluates to ,AL'& since a is neither equal to nor greater than !DD. The condition is therefore replaced by 0D0.Lut the 6*T operator -5. negates the result of this condition. This means it reverses the result of the condition -D. to #. Thus the $f gets reduced to,

if-#. b>)DD/ obviously, b>)DD would get executed, followed by c>(DD, hence the output. Example:% main-. B if-5).#!. printf-Crama is a good boyC./ else printf-C2ama and Orishna are friendsC./ E *3T13T" 2ama and Orishna are friends &xplanation" ).#! being a positive number, is a truth value, and on negating it using the 5 operator it results into a 0D0.thus the result of the condition is ,AL'&, hence the second printf-. is executed. Example:& main-. B float a>#(.(G, b>#).HG/ if-a>b. printf-Ca and b are equalC./ else printf-Ca and b are not equalC./ E *3T13T" a and b are equal &xplanation" To begin with a and b are not equal. The catch here is the assignment operator used in the if statement. it simply assigns the value of b to a, and hence the condition becomes, if-#).HG. The condition evaluates since the value is a non%4ero value,so the printf-. may evaluate, Hence the

result.

Forms Of If
#. if-condition. do this/ (.if-condition. B do this/ and this/ E ). if-condition. do this/ else do this/ !. if-condition. B do this/ and this/ E else B do this/ and this/ E G. if-condition. do this/ else B if-condition. do this/ else B do this/ and this/ E E H.if-condition. B if-condition. do this/ else B do this/ and this/ E E else do this/

Nested - IF
&xample"I 87Puic @emo of 6&'T&@ if%else78

main-. B int i/ printf-C&nter either # or (C./ scanf-C9dC,?$./ if-i>>#. printf-CKou would go to HeavenC./ else B if-i>>(. printf-CHell was created with you in mindC./ else printf-CHow about mother earthC./ E $n the above program an $,%&L'& occurs within the &L'& bloc of the first $, state ment.'imilarly,in some other programs an $,%&L'& may occur in the $, bloc as well. There is no limit on how deeply the $,0' and &L'&0' can be nested. Example:' 87 calculation of +ross 'alary78 main-. B float bs,gs,da,hra/ 1rintf-C&nter basic salaryC./ scanf-C9fC,?bs./ if-bs<#GDD. B hra>bs7#D8#DD/ da>bs7QD8#DD/ E else B hra>GDD/ da>bs7QR8#DD/ E gs>bs;hra;da/ printf-Cgross salary>2s 9fC,gs./ E Example:( main-. B int a>GDD,b,c/ if-a=>!DD. b>)DD/ c>(DD/ printf-CSn9d9dC,b,c./

E *3T13T" )DD (DD Example:1) main-. B int x>#D,y>(D/ if-x>>y./ printf-Sn 9d9dC,x,y./ E *3T13T" #D (D

&xplanation" The semi%colon -/. at the end of $, statement terminates , $, functionally, so x and y values are get printed. Example:11 main-. B int x>),y>G/ if-x>>). printf-C9dC,x./ else/ printf-C9dC,y./ E *3T13T" Example:12 main-. B char str#TU>CHelloC/ char str( TU>CHelloC/ if-str#>>str(. printf-C&qualC./ else printf-C3nequalC./ E *3T13T" 3nequal )

&xplanation" Ly using C>>C operator we cann0t campare two strings,we must use strcmp-. to compare strings.'o the else is executed. Example:13 main-. B int i>#D,N>!D/ if--N%$.9#D. printf-C:an sees your actions. . . C./ else printf-C+od sees your motives. . . C./ E

*3T13T"

+od sees your motives. . .

&xplanation" This is quite straight%forward. -N%$.9#D,on substituting the values of N and $, become -!D%#D.9#D.that is )D9#D, which gives the remainder as D. thus the condition would now become,'ince D is treated as falsely in c,the control reaches the second printf-. which prints output. Example:1$ main-. B float a>D.I/ if-a<D.I. printf-C'tonedC./ else printf-CAveragedC./ E *3T13T" 'toned. &xplanation" The output is very surprising5 D.I is never less than D.I, so the condition should evaluate to ,AL'&.Lut that doesn0t happen, 2eason is ,when D.I is stored in a, due to precision considerations, it is stored as something less than D.I.naturally, when value stored in a is compared with D.I, the condition evaluates to T23& and 'toned gets printed. Two get rid of the problem there are ( solutions. -a. declare A as a long @ouble as shown below" long double a/ -b. Typecast D.I to a ,loat while comparing as shown below" if-a<-float.D.I. Typecasting means converting to the specified data type. Example:1% main-. B int i>!DD7!DD8!DD/ if-i>>!DD. printf-CHaiC./ else printf-CHelloC./ E

*3T13T"

Hello.

&xplanation" The answer is Kes. Thus, the statement int i>!DD7!DD8!DD is quite alright.Lut on evaluating the expression it doesn0t turnout to be !DD. 2eason is, when !DD7!DD is done we don0t get #HDDDD because #HDDDD falls outside the integer range -%)(IHR to ;)(IHI..Fhenever a number exceeds )(IHI,it goes to the negative side and pic s up the appropriate number. 'o if results ,AL'&, that0s why the result. Example:1& main-. B int x>)/ float y>).D/ if-x>>y. printf-CSn x and y are equalC./ else printf-CSn x and y are not equalC./ E *3T13T" x and y are not equal

&xplanation" Lecause, here data types of two variables are different, so,else part get executed. Example:1* main-. B int i>HG/ char N>0A0/ if-i>>N. printf-CC is FowC./ else printf-CC is a headacheC./ E *3T13T" C is Fow

&xplanation" Here , the A'C$ value of character 0A0is HG. Fhile comparing it ta es A as HG, that0s why if part is executed. Example:1' main-. B float a>#(.(G, b>#(.G(/ if-a>b. printf-Sn a and b are equalC./

E *3T13T" a and b are equal

&xplanation" Here in $, we are not comparing the values, but it is an assignment, 'o, $, value is non%4ero,so the output results. Example:1( main-. B int x>)D,y>!D/ if-x>>y. printf-CSn x is equal to yC./ else if-x=y. printf-CSn x is greater than yC./ else if-x< y. printf-CSn x is less than yC./ E *3T13T" x is less than y

&xplanation" $t compares in first $, whether x and y are equal or not,the comparison results ,AL'&,so the control comes to next $, it also fails.,inally the condition satisfied, thus the output. Example:2) main-. B int x>#D/ if-x=>(. then printf-CSn 9dC,x./ E *3T13T" #D

&xplanation" $t chec s for the condition, it results T23& then printf-. get executed.

Examples Of If-Else
Example:* main-. B int i>HG/ char N>0A0/ if-i>>N. printf-CC is FowC./ else printf-CC is a headacheC./ E

Example:(

main-. B int a>GDD,b,c/ if-a=>!DD. b>)DD/ c>(DD/ printf-CSn9d9dC,b,c./ E *3T13T" )DD (DD Example:1) main-. B int x>#D,y>(D/ if-x>>y./ printf-Sn 9d9dC,x,y./ E #D (D

*3T13T"

&xplanation" The semi%colon -/. at the end of $, statement terminates, $, functionally, so x and y values are get printed. Example:11 main-. B int x>),y>G/ if-x>>). printf-C9dC,x./ else/ printf-C9dC,y./ E *3T13T" Example:12 main-. B char str#TU>CHelloC/ char str( TU>CHelloC/ if-str#>>str(. printf-C&qualC./ else printf-C3nequalC./ E *3T13T" 3nequal )

&xplanation" Ly using C>>C operator we cann0t campare two strings,we must use strcmp-. to compare strings. 'o the else is executed. Example:13 main-. B int i>#D,N>!D/

if--N%$.9#D. printf-C:an sees your actions. . . . . . . . . C./ else printf-C+od sees your motives . . . . . . . C./ E *3T13T" +od sees your motives . . . . . . .

&xplanation" This is quite straight%forward.-N%$.9#D, on substituting the values of N and $, become -!D%#D.9#D. that is )D9#D, which gives the remainder as D. thus the condition would now become, 'ince D is treated ad falsely in c, the control reaches the second printf-. which prints output. Example:1$ main-. B float a>D.I/ if-a<D.I. printf-C'tonedC./ else printf-CAveragedC./ E *3T13T" 'toned.

&xplanation" The output is very surprising5 D.I is never less than D.I, so the condition Dshould evaluate to ,AL'&.Lut that doesn0t happen, 2eason is ,when D.I is stored in a, due to precision considerations, it is stored as something less than D.I. naturally,when value stored in a is compared with D.I, the condition evaluates to T23& and 'toned gets printed. Two get rid of the problem there are ( solutions. -a. declare A as a long @ouble as shown below" long double a/ -b. Typecast D.I to a ,loat while comparing as shown below" if-a<-float.D.I. Typecasting means converting to the specified data type. Example:1% main-. B int i>!DD7!DD8!DD/ if-i>>!DD. printf-CHaiC./ else printf-CHelloC./ E *3T13T" Hello.

&xplanation" The answer is Kes. Thus, the statement int i>!DD7!DD8!DD is quite alright.Lut on evaluating the expression it doesn0t turnout to be !DD. 2eason is,

when !DD7!DD is done we don0t get #HDDDD because #HDDDD falls outside the integer range -%)(IHR to ;)(IHI.. Fhenever a number exceeds )(IHI,it goes to the negative side and pic s up the appropriate number. 'o if results ,AL'&, that0s why the result. Example:1& main-. B int x>)/ float y>).D/ if-x>>y. printf-CSn x and y are equalC./ else printf-CSn x and y are not equalC./ E *3T13T" x and y are not equal &xplanation" Lecause, here data types of two variables are different, so,else part get executed. Example:1* main-. B int i>HG/ char N>0A0/ if-i>>N. printf-CC is FowC./ else printf-CC is a headacheC./ E C is Fow

*3T13T"

&xplanation" Here , the A'C$ value of character 0A0 is HG. Fhile comparing it ta es A as HG, that0s why if part is executed. Example:1' main-. B float a>#(.(G, b>#(.G(/ if-a>b. printf-Sn a and b are equalC./ E *3T13T" a and b are equal

&xplanation" Here in $, we are not comparing the values, but it is an assignment, 'o, $, value is non%4ero , so the output results. Example:1( main-. B int x>)D,y>!D/ if-x>>y.

printf-CSn x is equal to yC./ else if-x=y. printf-CSn x is greater than yC./ else if-xExample:2) main-. B int x>#D/ if-x=>(. then printf-CSn 9dC,x./ E *3T13T" #D

&xplanation" $t chec s for the condition, it results T23& then printf-. get executed.

Use Of Logical Operators


C allows usage of three logical operators, namely ?? , AA and 5 These are to be read as 0A6@0 ,0 *20 and 06*T0 respectively.??, AA allows two or more conditions to be combined in an $, statement. Let us see how they are used in a program. Example:21 main-. B int m#,m(,m),m!,mG,per/ printf-C&nter mar s n five subNectsC./ scanf-C9d9d9d9d9dC,?ma,?m(,?m),?m!,?mG./ per>-m#;m(;m);m!;mG.8G/ if-per=>HD. printf-C,irst @ivisionC./ if--per=>GD.??-per<HD.. printf-C'econd @ivisionC./ if--per=>!D.??-per<GD.. printf-CThird @ivision./ if-per<!D. printf-CfailC./ E +d,anta!es of this operators: #. The matching of the $,0s with their corresponding &L'&' gets avoided, since there are no &L'&' in this program. (.$n spite of using several conditions, the program doesn0t creep to the right. The else if -lause: $n this case every &L'& is associated with its previous $f. The last &L'& goes to wor only if all the conditions fail. &ven in else if ladder the last &L'& is optional. 6ote That the &L'& $, cause is nothing different. $t is Nust a way of rearranging the else with if that follows it. This would be evident if you loo at the

following code" if-i>>(. A printf-CFith you5.........C./ A else A B A if-N>>(. A printf-C...... All the timeC./A E Example:22 if-i>>(. printf-CFith you.....C./ else if-N>>(. printf-C.....All the timeC./

87 &lse if ladder demo78 main-. B int m#,m(,m),m!,mG,per/ printf-C&nter mar s n five subNectsC./ scanf-C9d9d9d9d9dC,?ma,?m(,?m),?m!,?mG./ per-m#;m(;m);m!;mG.8G/ if-per=>HD. printf-C,irst @ivisionC./ else if-per=>GD. printf-C'econd @ivisionC./ else if-per=>!D. printf-CThird @ivisionC./ else printf-C,ailC./ E

&xample"() main-. B char gender,ms/ int age/ printf-C&nter age,gender,:arital 'tatusC./ scanf-C9d9c9cC,?age,?gender,?ms./ if--ms>>0:0.AA-ms>>030??gndeer>>0:0??age=)D. AA-ms>>030??gender>>0,0??age=(G.. printf-Cdriver is insuredC./ else printf-Cdriver is not insuredC./ E &xplanation" #. The driver will be insured only if one of the conditions enclosed in parenthesis evaluates to T23&. (. ,or the second pair of parenthesis to evaluate to T23&, each condition in the parenthes is separated by 0??0 must evaluate to T23&. ). &ven if one of the conditions in the second parenthesis evaluates to ,AL'&, then the whole of the second parenthesis evaluates to ,AL'&.

More Examples on Logical Operators


Example:2$ main-. B

E *3T13T"

int i>!,4>#(/ if-i>>!AA4=GD. printf-C@ean of 'tudent affairsC./ else printf-C@osaC./

@ean of 'tudent affairs

&xplanation" Logical *2-AA. operator in the $, evaluates to T23&.That0s why the output results. Example:2% main-. B int i>!,N>%#, >D,w,x,y,4/ w>iAANAA / x>i??N?? / y>iAAN?? / 4>i??NAA / printf-CSn w>9d V>9d y>9d 4>9dC,w,x,y,4./ E *3T13T" #D#D Example:2& main-. B int i>G,N>)D, >G/ if-iExample:2* main-. B int i>!,N>%#, >D,y,4/ y>i;G??N;#AA ;(/ 4>i;G;;N;#?? ;(/ printf-CSn y>9d 4>9dC,y,4./ E *3T13T" Example:2' main-. B int p>RD,q>(D/ if-p>>G??q=G. printf-CSn Fhy not CC./ else printf-CSn @efinitely C5C./ E *3T13T" @efinitely C5 # #.

Example:2( main-. B int x>(D,y>!D,4>!G/ if-x=y??x=4.

E *3T13T" W is big.

printf-CV ia bigC./ else if-y=x??y=4. printf-CK is bigC./ else if-4=x??4=y. printf-CW is bigC./

he NO !"# Operators
'o far we have used only the logical operators ?? and AA. Third operator is the 6ot operator, written as 5. This operator reverses the result of the expression it operates on. ,or example,if the expression evaluates to a non%4ero value, then applying 5operator to it results into a 0D0. Xice versa, if the expression evaluates to 4ero then applying 5 operator to it ma es it #,a non%4ero value. The result -after applying 5. D or # is considered to be ,AL'& or T23& respectively. value. The final are Here is an example of the 06*T0 operator applied to a relational expression.5-y>#D.. The 6*T operator is often used to reverse the logical value of a single variable, as in the expression if-5flag. This s another way of saying @oes the 6*T operator sound confusingJ Avoid it if you want, as the same thing can be achieved without using 6*T operator. Example:3) main-. B int i>%#,N>#, ,l/ >5i??N/ l>5iAAN/ printf-C9d9dC,$,N./ E *3T13T" D #

Example:31 main-. B int x>#D,y>G,p,q/ p>x=Q/ q>x=)??y5>)/ printf-Cp>9d q>9dC,p,q./ E *3T13T" p># q>#

&xplanation" 'ince x is greater than Q, the condition evaluates to T23&, the result of the test is treated as $ otherwise it is treated as D.Hence p contains value #. q>x=)??y5>), The first condition evaluates to T23&, hence is replaced by #.'imilarly,second condition also

evaluates to T23& and is replaced by #.'ince the conditions are combined using ?? and since both are T23&, the result of the entire expression becomes #,which is assigned to q. Example:32 main-. B int a>)D,b>!D,x/ x>-a5>#D.??-b>GD./ printf-Cx>9C,x./ E *3T13T" x>#

&xplanation" a5>#D evaluates to T23& and is replaced by #, b>GD uses an assignment->., hence GD is assigned to b. Therefore the condition becomes, x>#??GD 'ince # and GD both are T23& values , x value is 0#0 Example:33 main-. B int a>)DD,b>#D,c>(D/ if-5-a=>!DD. b>)DD/ c>(DD/ printf-Cb>9d c>9dC,b,c./ E *3T13T" b>)DD c>(DD

&xplanation" The condition -a=>!DD. evaluates to ,AL'& since a is neither equal to nor greater than !DD.The condition is therefore-5. negates the result of this condition. This means it reverses the result of condition D to #= thus the $, gets reduced to, if-#. b>)DD/ obviously, b>)DD would get executed, followed by c>(DD, hence the output. Example:3$ main-. B int x>#D,y>#DD9QD/ if-x5>y. printf-Cx>9 y>9dC,x,y./ E *3T13T" x>#D y>#D

&xplanation" Contrary to usual belief, the statement y>#DD8QD is perfectly acceptable. 'o the output results. Example:3%

main-. B int x>#D,y>%(D/ x>5x/ y>5y/ printf-Cx>9d y>9dC,x,y." E *3T13T" x>D y>D

$ase $ontrol Structure!SWI $%#


Introduction: $n real life we are often faced with situations where we are required to ma e a choice between a number of alternatives rather than only one or two. 'erious C programming is same, the choice we are as ed to ma e is more complicated than merely selecting between two alter natives. C provides a special control statement that allows us to handle such cases effectively/ rather than using a series of $, statements. Decisions .sin! S/itch: The control statement that allows us to ma e a decision from the numbers of choices is called a 'F$TCH, or more correctly a 'witch%Case%@efault, 'ince these ) eywords go together to ma e up the control statement.They most often appear as ,ollows" s/itch-inter expression. B case constant #" case constant (" case constant )" default: E

do this/ do this/ do this/ do this/

The integer expression following the eyword 'F$TCH is any C expression that will yield an integer constant li e #,( or ), or an expression that evaluates to an integer. The eyword case is followed by an integer or a character constant. "rocess of Execution: Fhen we run the program containing the switch, first the integer expression following the eyword switch is evaluated. The value it gives is then matched ,one by one, against the constant values that follow the case statements. Fhen a match is found, the program executes the statements following that case, and all subsequent case and default statements. $f no match is found with any of the case statements, default is executed. Example:$* main-. B

int i>#/ switch-i. B case #" printf-C$ am in case#C./ case (" case )" default " E *3T13T" E The output of this program would be" printf-CThis is second oneC./ printf-CThis is third caseC./ printf-Cyour are in defaultC./

$ am in case# This is second one This is third case your are in default The output is definitely not what we expected. Fe didn0t expect (nd,)rd and default cases print output.$f you want only case ( should get executed,it is up to you to get out of the switch then and there by using a Lrea statement. 6ote that there is no need for a brea statement after the default,since the control comes out of the switch anyway. Example:$' main-. B int i>(/ switch-i. B case #" printf-C$ am brea / case (" printf-CThis brea / case )" printf-CThis brea / default" printf-Cyour E

in case#C./ is second oneC./ is third caseC./ are in defaultC./

E *3T13T"

This is second one

Example:%3 main-. B char suite>)/ switch-suite. B case #" case (" default" printf-CSn @iamondC./ printf-CSn 'padeC./

E *3T13T"

printf-CSn HeartC./ E printf-CSn $ thought one wears a suiteC./

Heart $ thought one wears a suite Example:%$ main-. B int c>)/ switch-c. B case 0v0 " case )" case #(" default"

printf-CThis is v caseC./ brea / printf-C $am in a Third caseC./ brea / printf-CThis is #( th caseC./ brea / printf-C@efault caseJC./ brea /

E E *3T13T"$ am in a Third case. Example:%% main-. B int ,N>(/ switch- >N;#. B case D" case #" case (" default" E *3T13T" Lye Example:%& main-. B int i>D/ switch-i. B case D"printf-CSn Customers are diceyC./ case #"printf-CSn :ar ets are prieryC./ E

printf-CSn HaiC./ printf-CSn HelloC./ printf-CSn Hai #C./ printf-CSn LyeC./

case ("printf-CSn $nvestors are moodyC./ case )"printf-CSn &mployees are la4yC./ E *3T13T" E Customers are dicey :ar ets are priery $nvestors are moody &mployees are la4y

&xplanation" Here case is not having brea that0s why all the statements preceded by required cases are also executed. Example:%* main-. B int / float N>(.D/ switch- >N;#. B case )" printf-CSn TrappedC./ brea / default" E E *3T13T" Example:%' main-. B int i>!/ switch-i. B default" printf-CSn A mouse is an Alphabet built by YapaneeseC./ case #" printf-CSn Lreeding rabbits is a raising experienceC./ brea / printf-C,riction is a dragC./ brea / printf-CSn $f pratice ma es perfect, then noboby0s perfectC./ E *3T13T" A mouse is an Alphabet built by Yapanese Lreeding rabbits is a raising experience Example:%( main-. E Caught5 printf-CSn Caught5C./

case (" case )"

int i>!,N>(/ switch-i. B case #" printf-CSn To err is human,to forgive is against company policyC./ brea / case N" printf-CSn $f you have nothing to do, don0t do it hereC./ brea / E

E *3T13T" constant expression required in the second case, we can not use N. Example:&) main-. B int i>#/ switch-i. B case #" printf-CSn 2adio Active cats have #R half%livesC./ brea / case #7(;!" printf-CLottle for rent%inquire withinC./ brea / E E *3T13T" 2adio Active cats have #R half%lives

&xplanation" 6o error in this program. Constant expression li e #7(;! are acceptable in cases of a switch. Example:&1 main-. B int a >#D/ switch-a. B E printf-CSn 1rogrammers never die, They Nust get lost in the processingC./ E &xplanation" Though never required, there can exist a switch which has no cases. *3T13T" 1rogrammers processing Example:&2 main-. never die, They Nust get lost in the

int i>#/ switch-i. B printf-ChelloC./ case #" printf-C Sn $ndividualists unite5C./ brea / case (" printf-CSn :oney is the root of all wealthC./ brea / E

&xplanation" Though there is no error, irrespective of the value of i the first printf-. can never get executed . $n other words, all statements in a switch have to belong to same case or the other

ips &nd raps


A few useful tips about usage of switch and a few pitfalls to be avoided. -a. The earlier program that used switch may give you the wrong impression that you can use only cases arranged in asending order #,(,) and default.Kou can n fact put the cases in any order you please. Example:$( main-. B int i>(/ switch-i. B case #(#" printf-C$am in case#(#C./ brea / case I" case ((" default " E E printf-CThis is seventh caseC./ brea / printf-CThis is (( nd caseC./ brea / printf-Cyour are in defaultC./

*3T13T" This is (( nd case -b. Kou are also allowed to use char values in case and switch as follows" Example:%) main-. B

char c>0x0/ switch-i. B case 0v0"printf-C$am in case vC./ brea / case 0a0"printf-CThis is case aC./ brea / case 0x0"printf-CThis is x caseC./ brea / default "printf-Cyour are in defaultC./ E

*3T13T" This is x case $n fact here when we use 0v0,0x0,0a0 they are actually replaced by Asc$$ values-##R,#(D,QI. of these character constants. -c.At times we may want to execute a common statements for multiple cases. How this can be done is shown below" Example:%1 main-. B char ch/ printf-C&nter any of the alphabet a,b,cC./ scanf-C9cC,?ch./ switch-i. B case 0a0" case 0A0" printf-Ca is in asharC./ brea / case 0b0" case 0L0" printf-Cb is in brainC./ brea / case 0c0" case 0C0" printf-Cc is in coo ieC./ brea / default" printf-CFith you new what are habetC./ E E Here we ma e use of the fact, that once a case is satisfied the control falls through the case till it doesn0t encounter brea .&ven if there are multiple statements to be executed in each case there is no need to enclose them within a pair of braces-3nli e if, and else.. -e.&very statement in a switch must belong to some case or the other, if it doesn0t belongs to nay case it never going to execute. Example:%2 main-. set is

int i,N/ printf-C&nter value of iC./ scanf-C9dC,?i./ switch-i. printf-CHelloC./ case #" N>#D/ brea / case (" N>(D/ brea /

E E

-f.$f we have no default case, then the program simply falls through the entire switch and continues with the next instruct ions -if any. that follows the closing brace of switch. -g. $s switch a replacement for ifJ Kes and 6o. Kes, because it offers a better way of writing programs as compared to $,, and 6o, Lecause in certain situations we are left with no choices but to use if. The disadvantage of switch is that one can not have a case in a switch which loo s li e" case i<>(D/ All that we can have after the case is an int constant or a char constant or an expression that evaluates to one of these constants. &ven a float is not allowed. The advantage of switch over if is that it leads to a more structured program and the level of indentation is manageable more if so there are multiple statements within each case of a switch. -h. Fe can chec the value of any expression in a switch. Thus the following switch statements are legal. switch-i;N7 . switch-();!G9!7 . switch-aI.

&xpressions can be also be used in cases provided ey are constant expressions. Thus case );I is correct, However case a;b is incorrect. -i.The brea statement when used in a switch ta es the control outside the switch, However use of continue will not ta e the control to the beginning of the switch as one is li ely to believe. -N.$n principle , a switch may occur within another,but in practice it is rarely done. 'uch statements would be called nested switch statements. - .The switch statements in very useful while writing menu driven programs. This aspect of switch is discussed. S0IT-1 ,ersus IF-E SE ladder

There are some things that you simply can not do with a switch. They are" #.A float expression can not be tested using a switch. (.Cases can never have variable expressions-,or example it s wrong to say case a;)". ).:ultiple cases can not use same expressions. ,or example below form is illegal" switch-a. B case )" % % % % % % % case #;(" % % % % % % % E

he $onditional Operators
The Conditional operator J and " are sometimes called ternary operators since they ta e three arguments. $nfact,they form a ind of foreshortened $,%Then%&L'&. Their !eneral form is: expression#Jexpression("expression) This expression" Cif expression# is T23& - that is, if its value is non%4ero., then the value returned will be expression(, otherwise the value returned will be expression)C. examples" Let us understand this with the help of a few

-a. Example:3* int x,y/ scanf-C9dC,?x./ y>-x=GJ)"!./ This statement will store ) in y if x is greater than G, otherwise it will store ! in y. The equivalent $f statement will if-x=G. y>)/ else y>!/ -b.Example:3' char a/ int y/ scanf-C9cC,?a./ y>-a=>HG??a<>QDJ#"D./ Here # would be assigned to y if a =>HG ?? a<>QD evaluates to T23&,otherwise would be assigned. be,

The following points may be noted about the conditional operators" -a. $t0s not necessary that the conditional operators should be used only in arithmetic statements.This is illustrated in the following examples"

Example: 3( int i/ scanf-C9dC,?$./ -i>>#Jprntf-CAmitC."printf-CAll and 'undryC./ Example:$) char a>040/ printf-C9cC,-a=>0a0Ja"0#0../ -b. The conditional operators can be nested as shown below" int big,a,b,c/ big>-a=bJ-a=cJ)"!."-b=cJH"R../ Chec out the following conditional expression This will give you an error0 Lvalue required0 statement in the" part within a pair of parenthesis. This is shown below/ a=bJg>a"-g>b./ $n absence of parenthesis the compiler believes that b is being assigned to the result of the expression to the left of the second>. Hence it reports an error. Example:$1 main-. B int x>),y>!,4>!/ printf-Cans>9dC,4=>y??y=>xJ#"D./ E *3T13T" ans>#

&xplanation" Let us isolate the condition for closer examination. 4=>y??y=>x $f we are place the variable with their value the condition becomes,!=>!??!=>) 'ince both the conditions are T23& and they have been combine using ??, the whole thing evaluates to T23&. This is deduced from the fact that truth??truth yields truth. printf-Cans>9dC,truthJ#"D./ Hence ans># gets printed.

More examples On $onditional Operators

Example:$2 main-. B int x>),y>!,4>!/ printf-Cans>9dC,-4=>y=>xJ#DD"(DD../ E ans>(DD

*3T13T" &xplanation"

The expression is -4=>y=>xJ#DD"(DD. first W is compared to y and the result of the condition is compared with x. 'ince 4 and y are equal, the first condition is satisfied and is replaced by #. Thus the condition is now reduced to, -#=>xJ#DD"(DD. 'ince # is neither greater than nor equal to value of x, the condition fails and the output results. Example:$3 main-. B int i>%!,N,num>#D/ N>i9%)/ N>-NJD"num7num./ printf-CN>9dC,N./ E *3T13T" N>D

&xplanation"The statement is N>i9%), on substituting the value of $, t becomes, N>%!9%) 3sual arithmetic would have prompted us to cancel the minus signs from numerator and denominator and then perform the division. Lut not c. $n C first division is carried out assuming that there are no signs and then sign of numerator is assigned to reminder. Thus the output results. Example:$$ main-. B int >#(,n>)D/ >- =G??n>!J#DD"(DD./ printf-C >9dC, ./ E *3T13T" &rror message" Lvalue required in function main.

&xplanation" ,irst let us understand the meaning of the word Lvalue An Lvalue is any variable whose value can change - have a new value assigned to it.. An rvalue is a variable whose value can not change. T$1" The easient way to differentiate between the two is to remember that an rvalue goes to the right of the assignment operator,and an Lvalue to theleft. $n the above problem

>- =G??n>!J#DD"(DD./ +o to precedence table, 0??0 enNoys a higher priority compared to the assignment operator>. Hence the condition becomes - =G??n.>! 6aturally , this can not be evaluated since the compiler will not now to which variable ! should be assigned.$n otherwords,there is no Lvalue to which ! can be assigned. Hence Example:$% main-. B int c>D,d>G,e>#D,a/ a>c=#Jd=#AAe=#J#DD"(DD")DD/ printf-Ca>9dC,a./ E *3T13T" a>)DD the error message occurred.

&xplanation" c=# fails since value of c is D, and the control reaches )DD which is assigned to a. $t would become easier to understand the statement f we parenthesi4e the expression as shown below" a>-c=#J-d=#AAe=#J#DD"(DD.")DD./ 6*T&" The conditional operator can be 6ested. $s this program results errorJ main-. B int a>#D,b>#D/ printf-Cans>9dC,a=bJa7a"b8b./ E *3T13T" ans ># &xplanation" 6o, this doesn0t give an error message. 'ince we may use any other operators within printf-..'ince the condition a=b fails, the statement after ",that is b8b is evaluated and its result is printed by printf-..

Example:$&

'O O Statment
This Oeyword is used when we want to transfer the control to some point in the program which is not in the normal, step by step sequence of a program. $t ta es control from one place to another unconditi onally, 'o a different path for the execution of a program to set up. The following program illustrates the use of a +*T*. Example:&3

main-. B printf-CHope is hoping against hope. . . . . . C./ goto here/ printf-C&ven it seems hopelessC./ hope-./ exit-D./ E *3T13T" Hope is hoping against hope. . . . . . &xplanation" The second part of the message will not get printed, as due to goto, control s ips to the label hope and execution is terminated due to exit-D. present here.After hope, those would have got executed. Though goto seems to be handing over to us a magic word for placing control where are please, we would do well to empty combinations of $,, ,or,while and switch instead.This is because goto ma es the program less reada ble and hard to debug. Lesides,once the control is given to goto, there no telling how the program would behave, as is illustrated. Example:&$ main-. B int i/ for-i>#/i<>G/i;;. B if-i7i=>#(#. goto there/ else printf-C9dC,i./ E there" printf-CSn 6o more E *3T13T" Example:&% main-. B int i,N/ for-N>#/N<>#D/N;;. B for-i>#/i<>#D/i;;. B if-N<#D. goto out/ printf-C:urphyZs first lawC./ E printf-C$f the price of the 1C is a dreamC./ E printf-C@ream about a nightmareC./ E # ( ) ! G

murphys lawsC./

*3T13T"

@ream about a nightmare out of the loop using gotoJ

&xplanation"Can we abruptly brea

K&'. $n fact goto can ta e the control anywhere in the program.Here, first time through the loop itself the condition is satisfied,and goto ta es the control directly to the label out, where the printf-. gets executed. Example:&& B main-. int i, >#/ here" if- =(. goto out/ there" for-i>#/i<>G/i;;. printf-C9dC,i./ ;;/ goto there/ out" / E *3T13T" #()!G #()!G #()!G #()!G

Example:&* main-. B int i>#/ switch-i. B case #" goto label/ label" case (" printf-C He loo s li e a 'aint. . . . . C./ brea / E printf-CSn 'aint Lernard5C./ E *3T13T"He loo s li e a 'aint. . . . . 'aint Lernard5 . &xplanation" 'ince i is #, case # is executed, which ta es control to label.*nce the control is here, contrary to what one might expect, case ( gets executed,as is clear from the output. Legally spea ing, case( should have got executed only for value of i equal to (. Lut goto overrules this,and whatever follows goto, it ta es as the law.

Loop Control Statments


The control statements of a language specify the order in which computations are performed.In general C consider braces { and } is used to group declerations and statements together into compound statements or block ,so that they are Considered as single statement. Functionality of looping can be achieved in C using loop control statements like

WHILE
'yntax" while-test%condtion. The test%condition is evaluated if it is non%4ero statement is executed and test%condition is re%evaluated. This cycle continues until test%condition become 4ero at which point execution resumes after . The for statement for-expr#/ expr(/ expr). CstatementC is equivalent to expr#/ while-expr(. B Cstatement C expr)/ E The while is an entry%controlled loop.The test% condition is evaluated and if condition is true then the body of the loop is executed.After execution of body the process is repeated until the test condition becomes false and the control is transferred out of the loop.$f the body of the loop contains one or more statements then only braces are required otherwise for a single statement following while, braces can be dropped. Example: 1rogram to find a sum of square of #D numbers using whileJ [ include Cstdio.hC main- . B int n>#, sum>D/ while-n<>#D. B sum>sum;n7n/ n>n;#/ E printf-Csum >9d 8nC,sum./ E

DO-WHILE

The while loop we studied Nust before ma es a test condition before loop executed. Therefore the body of loop may not be executed at all if the condition is not satisfied at the first attempt.*n same occasions it might be necessary to execute body of the loop before test is performed 'uch conditions can be handled using do statement.This ta es the form do B body of the loop. Ewhile-test%condition. Here the test%condition in the while statement is evaluated at the end of the loop is executed once if the test cndition is wrong.,or first attempt otherwise the program continues to evaluate the body of as long as condition is true. The do%while is an exit control loop.there fore the body of the loop is executed at least once. Example: 1rogram to find sum of n numbers. [include main- . B i>#/ sum>D/ do B sum>sum;i/ i>i;#/ E while-sum<!D AA i<#D./ printf -C9d9dSnC,i,sum./ E The loop will be executed as long as one of the two relations is true.

FOR LOOP
The for loop is anotheer entry controlled loop that provides a more concise loop control structure.The general form of the loop is" for-initiali4ation/ test%condition /increment. B body of the loop E The execution of the for statement is as follows" #.$nitali4ation of the control variables is done first,using assignments statements such as i># and count>D.The variable

i and count are

nown as loop%control.

(. The value of the control variable is tested using the test%condition.The test%condition is a relational expression such as -i<#D.that determines when the loop will exit.$f the condition is true,the body of loop is executed otherwise the loop is terminated and the execution continues with the statement that immediately follows the loop. ). Fhen the body of the loop is executed,the control is transferred bac to the for statement after evaluating the last statement in the loop.6ow,the control variable increme nted using an assignment statement such as i>i;# and the new value of the control variable is again tested to see whether it satisfies the loop condition.$f the condition is satisfied, the body of the loop is again executed.The process continues until the value of the control variables fails to satisfy the test condition. Example: 1rogram to find sum of 0n0 numbers [include Cstdio.hC void main-. B int i,n,sum>D/ printf-C&nter the value of n SnC./ scanf-C9dC, ?n./ for-i>D/i < n/i;;. sum;>i/ printf-C'um of 9d numbers>9dC,n,sum./ E output" &nter the value of n #D 'um of #D numbers>GG Here the 0i0 is initali4ed to 4ero,which is again incremented until it is less than n,which is tested within the loop.

Ob e!t"#e $%pe &'est"ons

#.for-/ /. leads to a.non%4ero loop b.4ero loop Ans" C (.1oint out the error if any main-. B int i>#/ for-//. B

c.$nfinite loop

d.none

E E a.the condition in the for loop is a must b.the two semicolons should be dropped c.the for loop should be replaced by while loop d.no error Ans"@ ).1oint out the error if any main-. B int i>#/ while-. B printf-C9dC,i;;. if-i=#D. brea / E E a.the condition in the for loop is a must b.the two semicolons should be dropped c.the for loop should be replaced by while loop d.no error Ans" A !.1oint out the error if any main-. B int i>#/ while-i(. goto here/ E E fun-. B here"printf-CSn it wor sC./ E Ans"goto cannot ta e the control of a different function.

printf-C9dC,i;;. if-#D. brea /

anaging Input ! "utput Functions

Intro('!t"on
2eading, processing and writing of data are the three essential functions of a computer 1rogram.:ost programs ta e some data as input and display the processed data often nown as information or results.There are two methods of providing data to the program data to the programvariables.*ne method is to assign values to variables through the assignment state ments such as x>G, a>D and so on. Another method to use the input function scanf which can read data from a terminal. ,or outputting results the function printf which sends results out

to a terminal is used.0C0 does not have any built%in input and output statements as part of its syntax .All input and output operations are carried out through function calls such as printf and scanf.There exits several functions that have more or less become standard for input and output operation in C. These functions are collectively nown as i8o library. &ach program that uses a standard input8output function must contain the statement, at the beginning. [include0stdio.h0 The filename stdio.h is an input%output eader file. The instruction[include0stdio.h0tells the compiler to search for a file named stdio.h and place its contents at this point in the program. when it is compiled thecontents of the header file become part of the source code.

Rea("n) A C*ara!ter
The simplest of all input and output operations is reading a character from the standard input unit and writing it to the output unit. 2eading a character can be done by the function 0getchar0. The getchar ta e the form" variableMname>getchar-./ variableMname a valid c name that has been declared as char type. Fhen encountered,the computer waits until a ey is pressed and then assign this character as a value to getchar function. &xample" 1rogram" char name/ name>getchar-./ 87 2eading a character from terminal78

[include0stdio.h0 main-. B char answer/ printf-C would u li e to now my nameJSn C./ printf-C type y for yes and n for no" C./ answer>get char-./ if-answer>>0y0 AA answer>>0K0. printf-CSnSn my name is busy bee Sn C./ else printf-C SnSn u are good for nothing Sn C./ E *utput" would u li e to now my nameJ type y for yes and n for no"y my name is busy bee

Along with the getchar-. function,there are two functions which receive a character typed from the eyboard and tests whether it is a letter or digit and print out a message accordingly. They are" isalpha-character.

isdigit-character. The function isalpha a value non%4ero-true.if the argument character contains an alphabet otherwise it assumes 4ero-false.similar is the case with the function isdigit. 1rogram" 87Testing character type78 [include0stdio.h0 [include0ctype.h0 main-. B char character/ printf-Cpress any eySnC./ character>getchar-./ if-isalpha-character.=D. printf-Cthe character is a letterC./ else if-isdigit-character.=D. printf-Cthe character is a digitC./ else printf-Cthe character is not alphanumericC./ E output" press any ey f the character is a letter press any ey ) the character is a digit press any ey 7 the character is not alphanumeric The function in character test include" function test #.isalpha-c. (.isalphanum-c. ).sdigit-c. !.islower-c. G.isprint-c. H.ispunct-c. I.isspace-c. R.isupper-c. is c an alphabetic characterJ is c an alphanumeric characterJ is c a digitJ is c a lower case letterJ is c a printable characterJ is c a punctuation mar J is c a white pace characterJ is c a uppercase letterJ

Wr"t"n) A C*ara!ter
The function putchar is used for writing character one at a time to the terminal.$t ta es the form as shown below" putchar-variableMname./ where variableMname is a type char variable containing a character. for example" an>0y0/ putchar-an./

will display the character y on the screen. The statement putchar-0Sn0. / would cause the cursor on the screen to move to the beginning of the next line. program" 87 Friting a character to the terminal 78 [include [include main-. B char alphabet/ printf-Center an alphabetC./ putchar-0Sn0./ alphabet>getchar-./ if-islower-alphabet.. putchar-toupper-alphabet../ else putchar-tolower-alphabet../ E

*utput"

enter an alphabet a A enter an alphabet 2 r ,ormatted input" ,ormatted input refer to an input data that has been arranged in a particular format. example"#!.)G #)! pin y The first part of data should be read into a variable float,the second into int,and the third part into char. This is possible in C using the scanf function. scanf-Ccontrol stringC, arg#,arg(............argn./ the control string specifies the field format in which the data is to be entered and the argument arg#,arg(,....... argn specify the address of locations where the data is stored. Control string contain field specification which direct the interpretation of input data. $t may include" field specifications,consisting of the conversion character9, a data type character and an optional number, specifying the field width.

Inp't"n) Inte)er N'mber


The field specification for reading an integer number is" 9wd the percent sign-9. indicates that a conversion specification follows. F is an integer number,that specifies the field width of the number to be read and d nown as data type character, indicates that the number to be read i in integer mode. &xample" scanf-C9(d 9GdC,?num#,?num(./ data line" HD #)!GH the value HD is assigned to num# and #)!GH to num(.$nput

data item must be separated by spaces,tab or new line. 1unctuation mar do not count a separator.Xarious input format ting options for reading integers are experimented with in the program. 1rogram" 872eading integer number78 main-. B int a,b,c,m,n/ int i,N, / printf-Center three integer numbers SnC./ scanf-C9d97d9dC,?a,?b,?c./ printf-C9d9d9dSnSnC,a,b,c./ printf-Center two !%integer numbers SnC./ scanf-C9d9!dC,?m,?n./ printf-C9d9dSnSnC,m,n./ printf-Center two integer numbers SnC./ scanf-C9d97d9dC,?a,?m./ printf-C9d9d9dSnSnC,a,m./ printf-Center a nine digit numbers SnC./ scanf-C9)d9!d9)dC,?i,?N,? ./ printf-C9d9d9dSnSnC,i,N, ./ printf-Center two three digits SnC./ scanf-C9d97d9dC,?m,?n./ printf-C9d9d9dSnSnC,m,n./ E *utput" enter three numbers # ( ) # ) %)GII enter two !%digit numbers ()!G H!#I () !G enter two integers !! HH !)(# !! enter a nine digit number #()!GHIRQ HH #()! GHI enter two three digit numbers #() !GH RQ #()

Inp'tt"n) Real N'mber


3nli e integer numbers,the field width of real numbers s not to be specified and therefore scanf reads real numbers using the simple specifications 9f for both the notations,namely decimal point and exponential notation. &xample" scanf-9f9f9fC,?x,?y,?4./ input data !IG.RQ !).(#e%# HIR will assign the value !IG.RQ to x,!.)(# to y and HIR.D to 4. The input field specifications may be separated by an arbitrary blan spaces. $f the number to be read is of double type ,then the pecification should be lf9 instead of 9f. A number may be s ipped using 97f.

1rogram"

872eading of real numbers 78 main-. B float x,y/ double p,q/ printf-Cvalues of x and y"C./ scanf-C9fSn9eC,?x,?y./ printf-CSnC./ printf-Cx>9f Sn y>9fSnSnC,x,y./ printf-Cvalues of p and q"C./ scanf-C9lf9lfC,?p,?q./ printf-CSn p>9lf Sn q>9eC,p,q./ printf-CSnSn p>9#(lf Sn p>9#(eC,p,q./ E values of x and y"#(.)!GH #I.Ge%( x>#(.)!GHDD y>D.#IGDDD values of p and q" !.#!(RG#IR #R.GHIRQD#()!GHIRQD p>!.#!(RG#IR q>#.RGHIRQD#()!He;DD

*utput"

Inp'tt"n) C*ara!ter Str"n)s


'ingle character can be read from the terminal using the getchar function .The same can be achieved using the scanf function also. $n addition,a function can input strings contain ing more than one character. ,ollowing are the specifications for reading character strings" 9ws or 9wc 1rogram" 87 2eading of strings using 9wc and 9ws 78 main-. B int num/ char name#T#GU,name(T#GU,name)T#GU/ printf-Center serial number and name one SnC./ scanf-C9d 9#GcC,?num,?name#./ printf-C9d 9#GsSnSnC,num,name#./ printf-Center serial number and name two SnC./ scanf-C9d 9sC,?num,?name(./ printf-C9d 9#GsSnSnC,num,name(./ printf-Center serial number and name three SnC./ scanf-C9d 9#GsC,?num,?name)./ printf-C9d 9#GsSnSnC,num,name)./ E *utput" enter # # enter ( ( enter ( enter # serial number and name #()!GHIRQD#()!G #()!GHIRQD#()!Gr serial number and name 6ew Kor 6ew serial number and name Kor serial number and name #()!GHIRQD#( one two three one

# #()!GHIRQD#( r enter serial number and name two ( 6ew%Kor ( 6ew%Kor enter serial number and name three ) London $n the above program,the specification 9s terminates reading at the encounter of a blan space.Therefore,name( has read only the first part of C 6ew Kor C and the second part is automatically assigned to name).However, during the second run,the string C6ew Kor C is correctly to name(

Rea("n) M"+e( Datat%pes


$t is possible to use one scanf statement to input a data line containing mixed mode data.$n such cases,core should be exercised to ensure that the input data items match the control specifications in order and type. The statement scanf-C9d9c9f9sC,?count,?code,?ratio,?name./ will read the data #! s #!.)!G Nohn @etection of errors in input" Fhen a scanf function completes reading its list,it returns the value of items that are successfully read. This value can be used to test whether any errors occurred in reading the input &xample" scanf-C9d9f9sC,?a,?b,?name./ will return the value ) if the following data is typed in" (D #GD.)G cycle will return the value # if the following line is typed in" (D cycle #GD.)G This is because the function would encounter a string when it was expecting a floating point value and would therefore terminates its scan after reading the first value. 'ome versions of scanf support the following conversion specifications for strings. 9TcharactersU and 9T\charactersU The specification 9TcharacterU means that only the characters specified within brac ets are permissible in the input string.$f the input string contains only other character,the string will be terminated at the first encounter of such a character. The specification of9T\charactersU does exactly the reverse. The character specified after the circumflex-\. are not permitted in the input string.The reading of the string will be terminated at the encounter of one of these character 9s specifier cannot be used to read string with blan spaces. Lut,this can be done with the help of 9TU specifi cation. Llan spaces may be included within the brac ets,this enabling the scanf to strings with spaces

E+amples

1rogram#" 87illustration of 9T U specifications78 main-. B char addressT(DU/ printf-Center the address SnC./ scanf-C9Ta%4UC,address./ printf-C9%RDs SnSnC,address./ E *utput" enter the address new delhi ##D DD( new delhi 78

1rogram(" 87illustration of 9T\ U specifications main-. B char addressT(DU/ printf-Center address SnC./ scanf-C9T\ SnUC,address./ printf-C9 %RDs SnSnC,address./ E *utput" enter address 6ew @elhi ##D DD( 6ew @elhi ##D DD(

1rogram"

87 Testing for correctness of input data78 main-. B int a/ float b/ char c/ printf-Center values of a,b,c SnC./ if-scanf-C9d9f9cC,?a,?b,?c.>>). printf-Ca>9d b>9f c>9c SnC,a,b,c./ else printf-Cerror in input SnC./ E

*utput"

enter values of a,b,c #( ).!G A a>#( b>).!GDDDD c>A enter values of a,b,c () IR Q a>() b>IR.DDDDDD c>Q enter values of a,b,c R A G.(G error in input enter values of a,b,c )G() () x a>#G b>D.)GDDDDDD c>( The function scanf in the program is expected to read three items of data and therefore ,when the values for all the three variables are read correctly the program prints out their values.@uring the third run ,the second item does not match with the type of variable and therefore the reading is terminated and the error message is printed. The same case with the fourth run.$n the last run, although data items do not match the variables,no error message has been printed. Fhen we attempt to read a real number for an int variable,the

integer part is assigned to the variable and truncated decimal part is assigned to the next variable .6ote that the character ( is assigned to the character variable c.

Commonl% ,se( s!an-./ Formates


code 9d 9e 9f 9g 9h 9i 9o 9s 9u 9c 9x 9T....U :eaning 2ead a decimal integer 2ead a floating point value 2ead a floating point value 2ead a floating point value 2ead a short integer

2ead a decimal,hexadecimal or octal integer 2ead an octal integer 2ead a string 2ead an unsigned decimal integer 2ead a single character 2ead a hexadecimal integer 2ead a string of wordTsU

1oints to remember while using scanf" $f we do not plan carefully,some cra4y things can happen with scanf.'ince the i8o routines are not a part of c language,they are made available either as a separate module of the c library or as a part of the operating system-li e unix..+ivenbelow are some of the general points to eep in mind while writing a scanf statement. #.All function arguments,except the control string,must be pointers to variables. (.,ormat specifications contained in the control string should match the arguments in order. ).$nput data items must be separated by spaces and must match the variables receiving the input in the same order. !.The reading will be terminated,when scanf encounter an invalid mismatch of data or a character that is not valid for the value being read. G.Fhen searching for a value,scanf ignores line boundar ies and simply loo s for the next appropriate character. H.Any unread data items in a line will be considered as a part of the data input line to the next scanf call. I.Fhen the field width specifier w is used,it should be large enough to contain the input data si4e.

,ormatted *utput" The printf statement provides certain features that can be effectively exploited to control the alignment and pacing of print%outs n the terminals. The general form of printf statement is printf-Ccontrol stringC,arg#,arg(,.........argn./ control string consists of three of items" #.Characters that will be printed on the screen as they appear. (.,ormat specifications that defines the output format for display of each item. ).&scape sequence characters such as Sn,St and Sb. The control string indicates how many arguments follow and what their types are. The arguments arg#,arg(,........ argn are the variables whose values are formatted and printed according to specifications of the control string. The argument should match in number,order and type with the format specifications. A simple format specification has the following form" 9w.p type%specifier. Fhere CwCis an integer number that specifies the total number of columns for the output value and p is another integer number that specifies the number of digits to the right of the decimal point or the number of characters to be printed from a string. Loth w and p are optional. 'ome examples of printf statement are" printf-Cprogramming in cC./ printf-C C./ printf-CSnC./ printf-C9dC,x./ printf-Ca>9fSn b>9fC,a,b./ printf-Csum>9dC,#()!./ printf-CSnSnC./ printf never supplies a new line automatically and therefore multiple printf statements may be used to build one line of output.

O'tp't O- Inte)er N'mbers


The format specification for printing an integer number is 9wd where w specifies the minimum field width for the output. However if a number is greater than the specified field width,it will be printed in full. *verr iding the minimum specification d specifies the value to be printed is an integer. The following examples illustrate the output of the number QRIH under different formates" ,ormat *utput printf-C9dC, QRIH. Q R I H printf-C9HdC,QRIH. ' ' Q R I H printf-C9(dC,QRIH. Q R I H printf-C9%HdC,QRIH. Q R I H ' ' printf-C9DHdC,QRIH. D D Q R I H

$t is possible to force the printing to be left% Nustified by placing a minus sign directly after the 9 character. 1rogram" The output of integer number under various formats 87 printing of integer numbers78 main-. B int m>#()!G/ long n>QRIHG!/ printf-C9dSnC,m./ printf-C9#DdSnC,m./ printf-C9D#DdSnC,m./ printf-C%#DdSnC,m./ printf-C9#DldSnC,n./ printf-C9#Dld SnC,%n./ E output" #()!G #()!G DDDD#()!G #()!G QRIHG! % QRIHG!

O'tp't O- Real N'mbers


The output of a real number may be displayed in decimal notation the following format specification" 9w.pf The integer w indicates the minimum number of positions that are to be used for the display of the value and integer ]pZ indicates the number of digits to be displayed after the decimal point. The value when displayed is rounded to ]pZ decimal places and printed right Nustified in the field of w columns. The default precision is H decimal places. we can also display a real number in exponential notation by using 9w.pe The display ta es the form T%Um.nnnneT; or %Uxx where the length of the string of nZs is specified by the precision p. The default precision is H.The field width w should satisfy the condition w=>p;I. The value will be of the rounded off and printed right Nustified in the field of w columns.1adding the leading blan s with 4eros and printing with left Nustification is also possible by introducing D or ^ before the field width specifier w. The following example illustrate the output of the number y>QR.IHG! under different format specifications" #. ,*2:AT printf-C9I.!fC,y./ *3T13T"

# $.%&'(

(. *3T13T"

,*2:AT printf-C9I.(fC,y./

#$.%%

). ,*2:AT printf-C9%I.(fC,y. *3T13T"

# #$.%%

!. *3T13T"

,*2:AT printf-C9fC,y.

# #$.%&'(

*3T13T"

G. ,*2:AT printf-C9#D.(eC,y.

#.$$e)*+

*3T13T"

H. ,*2:AT printf-C9##.!eC,%y.

# ,#.$%&'e)*+

*3T13T"

I. ,*2:AT printf-C9%#D.eC,y.

# # $$e)*+

R. ,*2:AT printf-C9eC,y. *3T13T"

# # $%&'(*e)*+

'ome systems also supports a special field at run%time.

This ta es the following form " printf-C97.7fC,width,precision,number./ $n this case both the field width and the precision are given as arguments which will supply the values for w and p. for example printf-C9I.(fC,number./ The advantage of this format is that the values for width and precision may be supplied at runtime ,thus ma ing the format a dynamic one. ,or example the above statement can be used as follows" int width>I/ int precision>(/ %%%%%%%%%%%%%%%% %%%%%%%%%%%%%%% printf-C97.7fC,width,precision,number./ 1rogram" All the options of printing a real number 87 printing of real numbers78 main-. B float y>QR.IHG!/ printf-C9 I.!fSnC,y./ printf-C9fSnC,y./ printf-C9I.(fSnC,y./ printf-C9%I.(fSnC,y./ printf-C9D. I(,fSnC,y./ printf-C97.7fC,I,(,y./ printf-CSnC./ printf-C9#D.(eSnC,y./ printf-C9#(.!eSnC,%y./ printf-C9%#D.(eSnC,y./ printf-C9eSnC,y./ E *utput" QR.IHG! QR.IHG!D! QR.II QR.II DDQR.II QR.II Q.RRe;DD# %Q.RIHGe;DD# Q.RIHG!De;DD# 1rinting of single characters" A single character can be displayed in a desired position using the format 9wc The character will be displayed right%Nustified in the field of w columns. Fe can ma e the display left% Nustified by placing a minus sign before the integer w.The default value for w is #.

Pr"nt"n) o- Str"n)s
The format specification for outting strings

is of the form 9w.ps where w specifies width for display and p instructs that only the first p characters of string are to be displayed.The display is right %Nustified. The following examples show the effect of a variety of specifications in printing a string C6&F @&LH$ ##DDD#C, containing #H -including blan s.. 'pecification ? *utput" #. 9s

- ./ 0.12I ++***+
(. 9(Ds

- . / 0 .1 2 I + + * * * +
). 9(D.#Ds

-./ 0.12I

!. 9.G'

- ./ 0

G. 9%(D.#Ds

- ./ 0.12I

H. 9Gs

- ./ 0.12I +***+

M"+e( Data $%pes


$t ispermitted to mix data types in one printf statement" printf-C9d9f9s9cC,a,b,c,d./ printf uses its control string to decide how many variables to be printed and what their types are. 1rogram" 87 printing of characters and strings78 main-.

char x>0A0 static char nameT(DU>CA6$L O3:A2C/ printf-C9cSn9)cSn9GcSnC,x,x,x./ printf-C9)cSn9cSnC,x,x,x./ printf-CSnC./ printf-C*3T13T *, 'T2$6+'SnSnC./ printf-C9sSnC,name./ printf-C9(DsSnC,name./ printf-C9.GsSnC,name./ printf-C%(D.#DsSnC,name. printf-C9GsSnC,name./

E *utput" output of characters A A A A

output of strings A6$L O3:A2 +31TA A6$L O3:A2 +31TA A6$L O3:A2 A6$L A6$L O3:A2 A6$L O3:A2 +31TA

Ob e!t"#e $%pe &'est"ons


Fhat will be the output of the following programs" #.main-. B static char strTU >CAcademyC printf-C9sSn9sC,str,CAcemedyC./ E a. Academy Academy b.&rror c.6o &rror d.6one *utput" Academy Acamedy

&xplanation" Fe now that mentioning the name of a string yields the base address of the string.Fhen this base address is passed to printf-. it prints out each character in the string till it encounters 0SD0 sitting at the end of the string.A string written double quotes also gives the base address of the string.This base address when passed to printf-. would result in printing CAcemedyConce again. (. main-. B float a>).#!/ printf-C9Sna>9fC,a./ printf-C9Sna>9H.(fC,a./ printf-C9Sna>9%H.(fC,a./ printf-C9Sna>9H.#fC,a./

printf-C9Sna>9H.DfC,a./ a>).#!DDDD a> ).#! a>).#! a> ).# a> )

*utput"

&xplanation" The first printf-. uses the format specification for a float,hence a gets printed as ).#!DDDD, as bydefault a float is printed with H decimal places.$n the next printf-. the number that precedes the f in 9f is an optional specifier,which governs how exactly the varible is to be printed H.( signifies that the field width i.e the total number of columns that the values occupies on the screen, should be H and that the value should have ( digits after the decimal point.Thus ).#! is printed with blan spaces on the left,that is with right Nustification. ,or left Nustification,we use a minus sign with the specifiers,as is done in the next printf-..$t prints the value of a starting from the 4eroth column ,with only ( decimal digits.The specification H.# prints ).# with right Nustification. $n the last printf-.,H.D specifies 4ero decimal digits,have only ) is dsplayed right Nustified. ). main-. B printf-C9(DsSnC,Cshort legC./ printf-C9(DsSnaC,Clong legC./ printf-C9(DsSnC,Cdeep fine legC./ printf-C9(DsSnC,Cbac ward short legC./ printf-C9(DsSnC,Clegs all the same5C./ E shortleg longleg deep fine leg bac ward short leg legs all the same5

*utput"

&xplanation" The output is right Nustified,as the field width specified with each 9s is plus (D.,or each string, (D column are set aside,and the strings are printed with blan s filling up the remaining columns are on the left. !. main-. B printf-ChelloSnhiSnC./ printf-ChelloSrhiC./ E *utput" hello hi hillo

&xplanation" The escape sequence 0Sn0 called new line ta es the cursor to the beginning of the next line.Hence

with the first printf-. ChelloC and ChiC are printed on consective lines.A 0Sr0 on the other hand,ta es the cursor to the beginning of the same line in which the cursor is currently present.Hence,having printed ChelloC,the cursor is sent bac at 0hi0 is printed.The first two letters of ChelloC are therefore written over,and we get the output as ChilloC. G. main-. B printf-C9helloSbSbSbSbSbC./ printf-ChiSbSbSbbyeC./ E byelo

*utput"

&xplanation" The escape sequence 0Sb0 stands for bac space which ta es the cursor to the previous character.$n the first printf-., ChelloC is printed, following which the cursor is positioned after 0o0.6ow the G bac spaces ta e the cursor to the letter 0h0 of ChelloC.The control now passes to the second printf-.,and ChiC is written over the first three characters of ChelloC resulting in ChiloC.*nce again ) bac spaces are encountered,which ta e the cursor bac at 0h0 of ChiC.6ext CbyeC is printed on top of ChiC. The CloC that is seen has persisted from the first printf-.0s. ChelloC, as it never got overwritten.Hence the output CbyeloC. H.main-. B printf-C iStamStaStboyC./ E *utput"i am a boy &xplanation" The message is printed with space inserted wherever the escape sequence 0St0 occured. This sequence stands for a tab.$n one compiler,the tabs had been setup after every G colunms,at D,G,#D etc.Hence while executing printf-.,when 0St0 is encountered,the cursor s ips to the immediately next column which is a multiple of G,and then prints the next word.Thus 0i0 is printed form the #Gth column,CamC from the Gth,0a0 from the #Dth,and CboyC from the #Gth column.'ome compilers li e turbo c allow you to change the tab settings,so that the tab widths can set up as desired. I. [include main-. B char str#T)DU,str(T)DU/ printf-Center a sentence SnC./ scanf-C9sC,str#./ printf-C9sC,str(./ fflush-stdin./ printf-CSn enter a sentence SnC./ gets-str(./ printf-C9sC,str(./ E *utput" enter a sentence nothing succeeds li e success enter a sentence

nothing succeeds li e success nothing succeeds li e success &xplanation" The scanf-. suffers from the limitation that a maximum of only one word can be accepted by it.The moment a space-or a tab or a newline.is typed,scanf-. assumes you have finished supplying information ,and hence ignores whatever follows.That0s why,strTU stroes only C6othing,as it is proved by the first output.To overcome this limitation,we have an unformatted console i8o function called gets-..$t accepts whatever u type from the eyboard till the enter ey is hit. To be precise,get-. accepts everything until a 0Sn0 is encountered,which it replaces with a 0SD0 . Thus the entire string that we entered is obtained in the second output.fflush-. flushes out the current eyboard buffer would be read by gets-. .'ince gets-. is terminated on reading an enter ey ,u won0t get a chance to supply the (nd sentence. R. [include main-. B char nameT(DU,name#T(DU/ int age,age#/ printf-Center name and ageSnC./ scanf-C9s9dC,name,?age./ printf-C9s9dC,name,age./ printf-CSn enter name and ageSnC./ fscanf-Cstdin,C9s9dC,name#,?age#./ printf-Cstdout,C9s9dC,name#,age#./ E *utput" enter name and age raN #R enter name and age anNali (# &xplanation" Here the first set of statement comprising of prinf-.s and scanf-. is fairly simple.The fscanf-. and fprintf-. that follow next need some explaning. ,scanf- . li e scanf-.,is used for formatted reading of data. The only difference is that the former ta es an additional arugement that of a file pointer.This pointer indicates to the fscanf-. from where the data is to be read. whereas scanf-. is capable of reading data onlyfrom the eyboard.$n the call to fsacnf-. the file pointer stdin is being used ,which sands for standard input device i.e the eyboard.'ince stdin is a pointer to a standard file,we do not need to use fopen-. to open it,as it is always open for reading.The counterpart of fscanf-. is fprintf-.. Here the standard stdin in li e the the sets $t too needs a file pointer as its first argument. file pointer used is stdout,which stands for output device,i.e the display monitor.Thus using fscanf-. and stdout in fprint-. ma es them them wor familiar scanf-. and printf-. functions.Hence both collect the names and ages from eyboard.

Intro('!t"on $o F'n!t"ons

,unctions are building bloc s of C. The general form of C -3ser%defined. function is" 2eturn%type%function%name-parameter list. parameter declaration B body of function/ E C functions can be divided into ( types" #.Library ,unctions" &x" printf-. , scanf-. ,etc., (.3ser%defined functions" &x" main-., fact-., etc., ,or the library functions,user needs to write the code whereas a user%defined function has to be developed by the user at the time of writing a program. $f a program is divided into functional parts,t hen each part may be independently coded and later combined into a single unit.These sub%programs are called as CfunctionsC are much easier to understand,debug and test. "urpose 2f Functions: #. 3sing functions we can avoids rewriting the same code over and over. (. $t is simpler to write a function that does a specific Nob. ). 1rograms with functions are compact. !. $t facilitates top%down modular programming. G. @ebugging the code is much simpler because errors can be locali4ed and corrected. H. The length of the source program can be reduced. I. $t increases program readability and helps documentation. R. :any other programs may use a same function. -haracteristics 2f a Function: #. A function can return only one value. (. 2eturn statement indicates exit from the function and return to the point from where the function was invo ed. ). Fhen a function is not returning any value, void type can be used as a return type. !. 1arameter argument list is optional. G. A call to the function must end with a semicolon. H. A function can call any number of times. I. A C function cannot be defined in other function. R. C allows recursion i.e., a function can call itself. +ctual and Formal "arameters3ar!uments4: main-. B statements/ calling function<%%function#-a#,a(,.........am./%%=Actual parameters statements/ E

called function<%%function#-f#,f(,..........fm.%%=,ormal parameters statements/ B statements/ E Actual parameters or arguments are the parameters that are passed to the function whereas formal parameters or dummy parameters are the name of the corresponding parameters in the called function. The parameter passing mechanism refers to the actions ta en regarding the parameters when a function is invo ed. There are two parameter passing techniques available in C. They are" #. Call Ly Xalue (. Call Ly 2efernce -all #5 ,alue: Fhenever a portion of the program invo es a function with formal arguments, control will be transferred from the main to the calling function and the value of the actual argument is copied to the function. within the function,the actual value copied from the calling portion of the program may be altered or changed. when the control is transferred bac from the function to the calling portion of the program, the alterd values are not transferred bac . This type of passing formal arguments to a function is technically nown as CCall by valueC. &x" A program to exchange the contents of two variables using a call by value. [include main-. B int x,y/ void swap-int,int. x>#D/ y>(D/ printf-Cvalues before swap-.SnC./ printf-Cx>9d and y>9dC,x,y./ swap-x,y./ 87call by value78 printf-Cvalues after swap-.SnC./ printf-Cx>9d and y>9d C,x,y./ E void swap-int x ,int y. 87values will not be swapped 78 B int temp/ temp>x/ x>y/ y>temp/ E *utput of the above program" values before swap-. x>#D and y>(D values after swap-. x>#D and y>(D

-all #5 6eference: Fhen a function is called by a portion of program, the address of the actual arguments are copied onto the formal arguments, though they may be referred by different variable names.The content of the variables that are altered with in the function bloc are returned to the calling portion of a program in the altered form itself, as the formal and actual arguments are referring the same memory location or address. This is technically nown as call by reference or call by address. &x" A program to exchange the contents of two variables using a call by reference. [include main-. B int x, y/ void swap-int 7x, int 7y./ x>#D/ y>(D/ printf-Cvalues before swap-. SnC./ printf-Cx>9d and y>9d SnC,x,y./ swap-?x,?y./ 87 call by reference 78 printf-Cvalues after swap-. SnC./ printf-Cx>9d and y>9d SnC,x,y./ E void swap-int 7x ,int 7y. 87values will be swapped 78 B int temp/ temp>7x/ 7x>7y/ 7y>temp/ E *utput of the above program" values before swap-. x>#D and y>(D values after swap-. x>(D and y>#D

F'n!t"on De!larat"on an( protot%pe


$t is one of the most important feature of A6'$ C. A function prototype tells the compiler the type of data returned by the function, the number of arguments the function expects to receive, the types of arguments,and the order in which these arguments are expected.The compiler uses function prototype to validate function calls. The function prototype is written as follows" @ata%type function%name-type#,type( ..........typen./ Fhere data%type is the data%type returned by the function type#,type(,.......typen are the type of data fed as arguments. Any C function by default returns an int value. :ore specifically whenever a call is made to a function,the compiler assumes that this function would return a value of the type int.$f we desire that a function should return a

value other than an int, the it is necessary to explicitly mention so in the calling function as well as in the called function. 'uppose we want to find out square of a number using a function, #. main-. B float a,b/ printf-CSn &nter any numberC./ scanf-C9fC,?a./ b>square-a./ printf-CSn square of 9f is 9fC, a,b./ E square-float x. B float y/ y>x7x/ return-y./ E And here are the sample runs of this program &nter any number ) square of ) is Q.DDDDDD &nter any number #.G square of #.G is (.DDDDDD &nter any number (.G square of (.G is H.DDDDDD

The first of these answers is correct. Lut square of #.G is definitely not (. This is happened because any C function, by default always returns an integer value. Therefore, even though the function square-. calculates the square of #.G as (.(G,it is not capable of returning a float value. To overcome this problem, the function square-. must be declared as float in main-. as well.The statement float square-. means that it is a function which will return a float value. 6eturn Statement: The return statement has two important uses" #. $t causes an important exit from the function it is in. That is, it causes program execution to return to the calling code. (. $t can be used to return the value. The syntax of the return statement is" return/ return-var./ return-expression./ Fhere var is any variable and expression is any arithmetic or logical expression.Fhen the return statement is encount% ered in the called function, control is passed on to the calling function and a variable var or the value obtained by the arithmetic or logical expression is returned by the called function to the calling function.

S$ANDARD LIBRAR0 F,NC$IONS


+rithmetic Functions: abs %%= 2eturns the absolute value of an integer.

cos %%= Calculates cosine. cosh %%= Calculates hyperbolic cosine. exp %%= 2aises the exponential e to the xth power. fabs %%= ,inds absolute value. floor %%= ,inds largest integer less than or equal to argument. fmod %%= ,inds floating ^ point remainder. hypot %%= Calculates hypotenuse of right triangle. log %%= Calculates natural logarithm. log#D %%= Calculates base #D logarithm. modf %%= Lrea s down argument into integer and fractional parts. pow %%= Calculates a value raised to a power. sin %%= Calculates sine sinh %%= Calculates hyperbolic sine. sqrt %%= ,inds square root tan %%= Calculates tangent tanh %%= Calculates hyperbolic tangent Data con,ersion functions: atof %%= Converts string to float atoi %%= Converts string to int atol %%= Converts string to long ecvt %%= Converts double to string fcvt %%= converts double to string gcvt %%= converts double to string itoa %%= converts int to string ltoa %%= converts long to string strtod %%= converts string to double strtol %%= Converts string to long integer. strtoul %%= Converts string to an unsigned long integer. ultoa %%= Converts unsigned long to string. -haracter classification functions: isalnum %%= Tests for alphanumeric character. isalpha %%= Tests for alphabetic character. isdigit %%= Tests for decimal digit islower %%= Tests for lowercase character. isspace %%= Tests for while space character. isupper %%= Tests for uppercase character. isxdigit %%= Tests for hexadecimal digit. tolower %%= Tests character and converts to lowercase if uppercase. toupper %%= Tests character and converts to uppercase if lowercase. Strin! manipulation functions: strcat %%= Appends one string to another strchr %%= ,inds first occurrence of a gven character in a string. strcmp %%= Compares two strings. strcmpi %%= Compares two strings without regard to case strcpy %%= Copies one string to another. strdup %%= @uplicates a string stricmp %%= Compares two strings without regard to case -identicalto strcmpi. strlen %%= ,inds length of a string. strlwr %%= Converts a string to lowercase. strncat %%= Appends a portion of one string to another. strncmp %%= Compares a portion of one string with portion of

another string. strncpy %%= Copies a given number of characters of one string to another. strnicmp %%= Compares a portion of one string with a portion of another without regard to case. strchr %%= ,inds last occurrence of a given character in a string strrev %%= 2everse a string. strset %%= 'ets all characters in a string to a given character. strstr %%= ,inds first occurrence of a given string in another string. strupr %%= Converts a string to uppercase. Searchin! and sortin! functions: bsearch %%= 1erforms binary search. lfind %%= 1erforms linear search for a given value. qsort %%= 1erforms quic sort. I72 Functions: close %%= Closes a file. fclose %%= closes a file. feof %%= @etects end%of%file. fgetc %%=2eads a character from a file. fgetchar %%= 2eads a character from eyboard-function version. fgets %%= 2eads a string from a file. fopen %%= *pens a file. fprintf %%= Frites formatted data to a file. fputc %%= writes a character to a file. fputchar %%= Frites a character to screen-function version. fputs %%= writes a string to a file. fscanf %%= 2eads formatted data from a file fsee %%= 2epositions file pointer to given location. ftell %%= +ets current file 1ointer position. getc %%= 2eads a character from a file -macro version. getch %%= 2eads a character frm the eyboard. getche %%= 2eads a character from eyboard and echoes it. getchar %%= 2eads a character from eyboard -macro version.. gets %%= 2eads a line from eyboard. inport %%= 2eads a two%byte word from the specified $8* port. inportb %%= 2eads one byte from the specified $8* port. bhit %%= Chec s for a eystro e at the eyboard. lsee %%= 2epositions file pointer to a given location. open %%= opens a file. outport %%= Frites a two%byte word to the specified $8* port. outportb %%= Frites one byte to the specified $8* port. printf %%= Frites formatted data to screen. putc %%= Frites a character to a file-macro version. putch %%= Frites a character to the screen. putchar %%= Frites a character to screen-macro version. puts %%= writes a line to file. read %%= 2eads data from a file. rewind %%= 2epositions file pointer to beginning of a file. scanf %%= 2eads formatted data from eyboard. sscanf %%= 2eads formatted input from a string. sprintf %%= Frites formatted output to a string. tell %%= +ets current file pointer position. write %%= Frites data to a file. File 1andlin! functions:

remove %%= @eletes file. rename %%= 2enames file. unlin %%= @eletes file. Director5 -ontrol Functions: chdir %%= Changes current wor ing directory. getcwd %%= +ets current wor ing directory. fnsplit %%= 'plits a full path name into its components. findfirst %%= 'earches a dis directory. findnext %%= Continues findfirst search. m dir %%= :a es a new directory. rmdir %%= 2emoves a directory. 8uffer 9anipulation Functions: memchr %%= 2eturns a pointer to the fiirst occurrence,within a specified number of characters,of a given character in the buffer. memcmp %%= Compares a specified number of characters from two buffers. memcpy %%= Copies a specified number of characters from one buffer to another. memicmp %%= Compares a specified number of characters from two buffers without regard to the case of the characters. memmove %%= Copies a specified number of characters from one buffer to another. memset %%= 3ses a given character to initiali4e a specified number of bytes in the buffer. Dis: I72 Functions: absread %%= 2eads absolute dis sectors. abswrite %%= Frites absolute dis sectors. biosdis %%= 1erforms L$*' dis services. getdis %%= +ets current drive number. setdis %%= 'ets current dis drive. 9emor5 +llocation Functions:

calloc %%= Allocates a bloc of memory farmalloc %%= Allocates memory from far heap farfree %%= ,rees a bloc from far heap. free %%= ,rees a bloc allocated with memory. malloc %%= Allocates a bloc of memory. realloc %%= 2eallocates a bloc of memory. "rocess -ontrol Functions: abort %%= Aborts a process atexit %%= &xecutes function at program termination. execl %%= &xecutes child process with argument list. exit %%= Terminates the process. spawnl %%= &xecutes child process with argument list spawnlp %%= &xecutes child process using 1ATH variable and argument list. system %%= &xecutes an :s%@os command. Graphics Functions:

arc %%= @raws an arc. ellipse %%= @raws an ellipse. floodfill %%= ,ills an area of the screen with the current color. getimage %%= stores a screen image in memory. getlinestyle %%= *btains the current line style. getpixcel %%= *btains the pixcel0s value. lineto %%= @raws a line from the current graphic output position to the specified point. moveto %%= :oves the current graphic output position to a specified point. pieslice %%= @raws a pie%slice%shaped figure. putimage %%= 2etrieves an image from memory and displays it. rectangle %%= @raws a rectangle. setcolor %%= 'ets the current color. setlinestyle %%= 'ets the current line style. putpixel %%= 1lots a pixel at a specified point. 'etviewport %%= Limits graphic output and positions the logical origin within the limited area. Time 6elated Functions: Cloc %%= 2eturns the elapsed cpu time for a process. difftime %%= Computes the difference between two times. ftime %%= +ets current system time as structure. strdate %%= 2eturns the current system date as a string. strtime %%= 2eturns the current system time as a string. time %%= +ets current system time as long integer. setdate %%= 'ets @os date. getdate %%= +ets system date. 9iscellaneous Functions: delay %%= 'uspends execution for an internal -milli seconds. getenv %%= +ets value of environment variable. getpsp %%= +ets the program segment prefix. perror %%= 1rints error message. putenv %%= Adds or modifies value of environment variable. random %%= +enerates random numbers. randomi4e %%= $nitiali4es random number generation with a random value based on time. sound %%= Turns pc spea er on at specified frequency. nosound %%= Turns pc spea er off. Dos Interface Functions: ,1%*,, %%= 2eturns offset portion of a far pointer. ,1%'&+ %%= 2eturns segment portion of a far pointer. getvect %%= +ets the current value of the specified interrupt vector. eep %%= $nstalls terminate%and%stay%resident-T'2. programs. intRH %%= $ssues interrupts. intRHx %%= $ssues interrupts with segment register values. intdos %%= $ssues interrupt (#h using registers other than @V and AL. intdosx %%= $ssues interrupt (#h using segment register values. :O%,1 %%= :a es a far pointer. segread %%= 2eturns current values of segment registers. setvect %%= 'ets the current value of the specified interrupt vector

Multiple $hoice (uestions &nd )rograms


#. There is a mista e in the following code, add a statement in it to remove it. main-. B int a/ a>f-#D,).#!. printf-C9dC,a./ E f-int aa,float bb. B return--float.aa;bb./ E Ans" Add the function prototype in main-. float f-int,float./ (. Fhat error would the following function give on compilationJ f-int a, int b. B int a/ a>(D/ return a/ E A. :issing parentheses in return statement L. The function should be defined as int f-int a, int b. C.2edeclaration of a @.6one of the above Ans" C ). $n a function two return statements should never occur successfully. T23& or ,AL'& Ans" T23& !. $n C all functions except main-. can be called recursively. T23& 8 ,AL'& Ans" ,AL'& G. 1oint out the error in the following code. main-. B int a>#D/ void f-./ a>f-./ printf-CSn 9dC,a./ E void f-. B printf-CSn HiC./ E Ans" $nspite of defining the function f-. as returning void, the program is trying to collect the value returned

by f-. in variable a. H. 1oint out the error, if any in the following program. main-. B int b/ b>f-(D./ printf-C9dC,b./ E int f-int a. B a=(D J return-#D. " return-(D./ E Ans" 2eturn statement cannot be used as shown with the conditional operators. $nstead the following statement may be used. return-a=(D J #D " (D. I. A function cannot be defined inside another function. T23& 8 ,AL'& Ans" T23& R. Fill the following function f#-int a, int b. B return-f(-(D../ f(-int a. B return-a7a./ E Ans" K&' wor J K&'86*

Q. $n a function two return statements should never occur. T23& 8 ,AL'& Ans" ,AL'& #D. 3sually recursion wor s slower than loops. T23& 8 ,AL'& Ans" T23& ##. $s it true that too many recursive calls may result into stac overflowJ K&' 8 6* Ans" K&' #(. Fhat will be the output of the following program. main-. B C-. B c-. B printf-C C is a C......SnC./ E printf-C.......... is a c..SnC./ E printf-C.......... is a sea afterall5C./

E *utput" &rror message" 'tatement missing / in function main The compiler reports an error saying there is a missing semicolon. Lut where is it missingJ After C-.. Lut suppose we only want to define the function C-., logically we shouldn0t be required to give a semi%colon after C-..That0s the point. At the most you can call a function from within the body of another function. you are not allowed to define another function within the body of another function. And that is what the above program is attempting to do. $t is trying to define C-. and c-. in main-., which ia not acceptable,hence the error message. #). main-. B int 4>!/ printf-C9dC,printf-C9d9dC,4,4./ E *utput" ! ! ) Here the inner printf-. is executed first, and it prints out a !, a space and another !. Thus it totally prints out ) characters. Fhenever the printf-. function is called it returns the number of characters it has successfully managed to print. #!. main-. B int i/ printf-C$n the year of lord SnC./ for-i>#/i!D. return-5m;;./ else return-5;;m./ E output" &rror message" 2edeclaration of 0m0in function chec The variable m used in chec -. has not been defined before the opening brace. Therefore it is assumed to be an integer variable. ((. main-. B int i>!G/ float c/ c>chec -i./ printf-Cc>9fC, c./ E chec -ch. int ch/ B ch=>!G J return-).#!. " return-H.(R./ E

*utput" c>).DDDDDD Here, the condition ch=>!G is satisfied hence ).#! gets returned. @oes it reallyJ 6o, because by default

any function is capable of returning only an int. Hence ).#! gets truncated to ) while returning the value. ().C supports modular programming. (!.A function is a self contained program which is meant to do some specific well defined tas . (G.2eturn statement is used to exit from the function. (H.A function can receive many values, but it can return only one value. (I.A function prototype tells the compiler the type of data arguments and their order,the type of data function returns, number of arguments. (R.1arameters are used to communicate data between the calling and called function. (Q.The four storage classes in c are automatic, static, external and register. )D.2ecursion is a process of calling a function within the same function. )#. main-. B int i>), , l/ >add-;;i./ l>add-i;;./ printf-Ci>9d >9d l>9dC, i, E add-ii. B ;;ii/ return-ii./ E

, l./

*utput" i>G

>G l>G Fhenever the ;; operator proceeds the variable, first the variable0s value is incremented and then used. As against this whenever the ;; operator succeeds the variable, its value is first used and then incremented. According to this rule the first call add-;;i. would first increment i to ! and then pass its value to function add-.. $n add-. ! is collected in ii,incremented to G, returned to main-. and finally stored in .Hence 0s value is printed as G. $n the next call, add-i;;., the current value of i-i.e., !. is first sent to add-. and then i0s value is incremented to G. $n add-. ii is incremented to G, which is returned and collected in l. )(. main-. B int i>#)G, a>#)G, / >function-5;;i,5a;;. printf-Ci>9d a>9d >9dC,i,a, ./ E

function-N,b. int N,b/ B int c/ c>N;b/ return-c./ E *utput" i>#)H a>#)H >D 'ince ;; preceeds i its value is incremented to #)H, and then the 5 operator negates its to give D. This D is however not stored in i but is passed to function-.. As against this while evaluating the expression 5a;; , since ;; follows a, firstly a is negated to D, this D is passed to function-. and a is incremented to #)H.Thus what get passed to function-. are D and D,which are collected in N and b, added to give another o and finally returned to main-., where it is collected in and then printed out. )). main-. B int p>(), f>(!/ pac man-p,f./ printf-Cp>9d f>9dC,p,f./ E pac man-q,h. int q, h/ B q>q;q/ h>h;h/ return-q./ return-h./ E

*utput" p>() f>(! $n pac man-. q and h are doubled and then the return-q. is executed, which sends the control bac to main-. along with the value q. Lut since this value is not collected in any variable in main-. it Nust gets ignored. As a result p and f stand unchanged at () and (! respectively. The statement return-h. never gets executed, since the previous return statement will not allow the control to reach there. )!. main-. B int i>),N/ N>add-;;i;;./ printf-Ci>9d N>9d SnC, i, N./ E add-ii. int ii/ B ii;;/ printf-Cii>9d SnC, ii./ E

*utput" &rror message" Lvalue required in function main-.

0Lvalue0 means a variable whose value can change or in other words,a variable which can occur on the Left hand side of the assignment operator. 6ow loo at the expression ;;i;;. Here firstly i would be incremented to !-due to the ;; operator before i. and the expression would become !;;. As a result ! would passed to add-. and then would attempt to get incremented owing to the operator that occurs after i.Lut ! cannot be incremented because it is not a variable. *n L8H side of assignment operator a variable -lvalue. should occur. This attempt would be made to evaluate !;; as !>!;#. Hence the error message. )G. main-. B int >)G, 74, 7y/ 4>? / 87 'uppose address of is #DDR 78 y>4/ 74;; > 7y;;/ ;;/ printf-C >9d 4>9d y>9dC, ,4,y./ E >)H 4>#D#D y>#D#D

*utput"

$n main-. the address of is stored in 4 and the same address is then assigned to y. since y and 4 contain address of an integer,they have been quite appropriately declared as integer pointer.Here the 4 and y pointers are incremented to point to the next location. Lut before the incrementation what is done is assignment.This is because ;; is occuring after the variable names y and 4. @uring assignment,value at the address contained in y-i.e.,)G.. After that the value of is incremented to )H and then printed out. )H. main-. B int a>#DD, 7b, 77c 777d/ b>?a/ c>?b/ d>?c/ printf-C9d9d9d9dC, a, 7b, 77c, 777d./ E

*utput" #DD #DD #DD #DD Here b is an integer pointer, c is a pointer to an integer pointer and d is called a pointer to a pointer to an integer pointer.$n printf-. a would printout the value #DD which is straight forward.7b would print the value at theaddresscontained n b. 'ince the address contained in b is !DD(, and the value at this address s #DD,once again #DD would get printed. C would give value at address !DD(, i.e., #DD.The similar logic is applied to the output of 777d,which would also be #DD. )I. main-. B float a>IQQQQQQ/ float 7b, 7c/

b>?a/ c>b/ printf-C9d9d9dC,?a,b,c./ printf-9d9d9d9d SnC, a ,7-?a., 7b, 7c./ E *utput" !(DD D !(DD (!GIH !(DD %) #H!#G

The first printf-. the address of a in three different ways. $n the second printf-. we are attempting to print I.QQQQQQ by applying pointer operator on a,b and c. a, 7-?a., 7c all yield I.QQQQQQ but when they are printed using 9d, printf-. blows it up as the output above would Nustify. @onZt rely on printf-. to truncate a float value to an integerwhile printing by using a 9d.Xicevers also its true. These statements would not print I.DDDDDD . @onZt be surprised if you get some odd value. $n that sense 9d ? 9f are a little unreliable. )R. main-. B int i>%G, N>%(/ Nun -i, ?N./ printf-Ci>9d N>9dC, i, N./ E Nun -i, N. int i, 7N/ B i>i 7 i/ 7N> 7N 7 7N/ E *utput" i> %G N> ! Nun -., against change 7N which

&ven though the value of i is changed to (G in this change will not be reflected bac in main-.. As this since NZs address is being passed to Nun -.,any in Nun -. gets reflected bac in main-.. Hence 7N 7 evaluates to ! is reflected bac in main-.. )Q. main-. B int 7c/ c>hec -#D,(D./ printf-Cc> 9dC, c./ E chec -i,N. int i,N/ B int 7p, 7q/ p>?i/ q>?N/ i>!G J 2eturn-p. " return-q./ E

*utput" &rror message" 6on portable pointer assignment in main Here, the conditional operators test the value of i

against !G, and return either the address stored in q. $t appears that this address would be collected in c in main-., and then would be printed out. And there lies the error. The function chec -. is not capable of returning an integer pointer. All that it can return is an ordinary integer.Thus Nust declaring c as an integer pointer is not sufficient. int chec -./ we must ma e the above modification in the program to ma e it wor properly

Lon) Ans1er &'est"ons


#. Two dates are entered through the eyboard in dd,mm,yy format. Frite a program to find out the difference in the two dates in terms of days. main-. B int d#,m#,y#,d(,m(,y(,days,dm/ dm>D/ printf-Cinput first date-dd,mm,yy.C./ scanf-C9d9d9dC, ?d#, ?m#, ?y#./ printf-Cinput second date-dd,mm,yy.C./ scanf-C9d9d9dC, ?d(, ?m(, ?y(./ dm>daysinmonth-m#,y#./ while-#. B days>days;#/ d#>d#;#/ if-d#=dm. B m#>m#;#/ d#>#/ if-m#=#(. B m#>#/ y#>y#;#/ E dm>daysinmonth-m#,y#. if-d#>>d( ?? m#>>m( ?? y#>>y(. brea /

E daysinmonth-m,y. int m,y/ B int dm/ if-m>># AA m>>) AA m>>G AA m>>I AA m>>R AA m>>#D AA m>>#(. dm>)D/ if-m>>(. B dm>(R/ f--y9!DD>>D. AA -y9#DD5>D ?? y9!>>D.. dm>(Q/ E return-dm./

E printf-C SnSn @ifference in dates> 9dC, days./

E 'ample 2un" $nput first date-dd,mm,yy. D# D# #QQ) $nput second date-dd,mm,yy. )# #( #QQ) @ifference in dates>)HGdays &xplanation",irstly the two dates are received n dd,mm,yy format. Then the function daysinmonth-. is called to find out number of days in the month m# of year y#.6extly through the indefinte while loop the variable days s continuously incremented. $t counts the number of days. , d# exceeds the days n a month, then we go to the next yearZs first month . Ths counting goes on till we reach the second date. This happens when d# equals d(, m# equals m(, y# equals y(. Fhen this happens the control comes out of the loop by executing brea and prints out the difference n dates stored in the variable days. (.1rogram to calculate the ,ibonacc number usng recurson. [include int fib-int n. B if-n<>#. return #/ else return-fib-n%#.;fib-n%(../ E int main-void. B int n/ for-n>D/n<>#G/n;;. printf-C9dC, fib-n../ return D/ E &xplanation" fib-n.># fib-n.>fib-n%#.;fib-n%(. for values of n>D and # for all integer values of n=#

Thus a sequence might be #,#,(,),G,R,#),(# and so on. Here the function fib-. is directly and recursively called twice.The call to fib-). would then in turn call itself to calculate fib-(. and fib-#.. Fhile the two calls to fib-(. would calculate the values of fib-#. and fib-D..*utput" #,#,),G,R,#),(#,)!,GG,RQ,#!!,()),)II,H#D). Towers of Hanio solved using recursion. [include [include void towers- char from, char to, char middle, nt number. B if-number>>#. printf-C:ove @is from 9c to 9c SnC,from, to./ else B towers-from,middle,to,number%#./ towers-from,to,middle,#./ towers-middle,to,from,number%#./ E E

int main-void. B int dis s/ char bufferTL3,'WU/ printf-C&nter 6umber of dis sC./ dis s>atoi-gets-buffer../ if-dis s=D. towers-]AZ,ZCZ,ZLZ,dis s./ else printf-C&nter @is must be greater than D ........SnC./ return D/ E &xplanation" Here a function can be written to move one dis , it can be recursively called n times to move n dis s. The function towers-. directly calls itself no less than three times, ma ing the transition to an iterative approach extemely difficult

Intro('!t"on $o Arra%s
An array is a group of related data items that share a common name.,or instance, we can define an array name 'alary to represent a set of salaries of a group of employees. A particular value is indicated by writing a number called index number or subscript in brac ets after the array name. ,or example, 'alary T#DU represents the salary of the #Dth employee while the complete set of values is referred to as an array,the individual values are called elements. Arrays can be of any variable type. *ne %@imensional Arrays " A list of items can be given one variable name using only one subscript and such a variable is called 'ingle%subscripted variable or a *ne%@imensional array. $n mathematics we often deal with variables that are single%subscripted.,or instance, we use the equation A > Vi n>D calculate the average of n values of x. the subscripted variable Vi refers to the ith element of V.$n C, single%subscripted variable Vi can be expressed as VT#U, VT(U, VT)U,...............VTnU The subscript can begin with number D.that is allowed. ,or example, if we want to represent a set of five numbers, say-)G,!D,(D,GI,#Q. by an array variable number, then we may declare the variable number as follows int number TGU/ and the computer reserves five storage locations as shown below. 6umberTDU 6umberT#U 6umberT(U 6umberT)U

6umberT!U values to the array elements can be assigned as follows" numberTDU>)G/ numberT#U>!D/ numberT(U>(D/ numberT)U>GI/ numberT!U>#Q/ this would cause the array number to store the values as shown below" numberTDU numberT#U numberT(U numberT)U numberT!U )G !D (D GI #Q

these elements may be used in programs Nust li e any other C variable. ,orexample, the following are valid statements" a> numberTDU ;#D/ numberT!U> numberTDU ; numberT(U/ numberT(U> VTGU ; KT#DU/ valueTHU> numberTiU7 )/ subscript of an array can be integer constant,integer variables li e i , or expressions that yield integer. C performs no bounds chec ing and therefore, care should be exercised to ensure that the array indices are within the declared limits.

De!larat"on o- Arra%s
Li e any other variables, arrays must be declared before they are used.The general form of array declaration is type variable%name Tsi4eU/ The type specifies the type of elements that will be contained in the array, such as int,float or char and the si4e indicates the maximum number of elements that can be stored inside the array. ,or example" float heightTGDU/ declares the height to be an array containing GD real elements. Any subscript D to !Q are valid. 'imilarly, int groupT#DU/ declares the group to be an array to contain maximum of #D integer constants.2emember, any reference to the array outside the declared limits would not necessarily cause an error.2ather, it might result in unpredictable program results. The C language treats character string simply as array of characters. The si4e in a character string represents the maximum number of characters that the string can hold.,or instance, char nameT#DU/ declares the name as a character array-string. variable that can hold a maximum of #D characters.'uppose we declare the following string constant into the string variable name. F&LL @*6& each character of the string is treated as an element of the array name and is stored in the memory as follows" F

& L L @ * 6 & SD Fhen the compiler sees a character string, it terminates it with an additional null character. Thus,the element nameTQU holds the null character SD at the end. Fhen declaring character array,we must always allow one extra element space for the null terminator.

In"t"al"2at"on o- Arra%s
Fe can initiali4e the elements of the array in the same way as the ordinary variables when they are declared.The general form of initiali4ation of array is" static type array%name Tsi4eU > B list of variablesE/ the values in the list are separated by commas. ,or example, the statement static int number T)U > BD,D,DE will declare the variable number as an array of si4e ) and will assign 4ero to each element. $f the number of values in the list is less than the number of elements, then only that many elements will be initiali4ed the remaining elements will be set to 4ero automatically.,or instance, static float totalTGU >B D.D, #G.IG, %#DE/ will initiali4e the first three elements to D.D, #G.IG, %#D and the remaining two elements to 4ero. 6ote that we have used the word static before type declaration. This declares the variable as a static variable. The si4e may be omitted. $n such cases the compiler allocates enough space for all initiali4ed elements. ,or example, the statement static int counter TU>B #,#,#,#E/ will declare the counter array to contain four elements with initial values #. This approach wor s fine as long as we initiali4e every element in the array. Character arrays may be initiali4ed in a similar manner. Thus, the statement static char nameTU > BY, o ,h , nE/ declares the name to be an array of characters,initiali4ed with the string Yohn. $nitiali4ation of arrays in C suffers two drawbac s. #.There is no convenient way to initiali4e only selected elements. (.There is no shortcut method for initiali4ing a large number of array elements li e the one available in ,*2TA6. 1rogram showing *ne%@imensional Array"

main-. B int i/ float VT#DU,value,total/ print f -&nter #D real numbers Sn./ for -i>D/i<#D/i;;. B scan f-9f ,?value./ VTiU>value/ E total>D.D/ for-i>D/i<#D/i;;. total >total ; VTiU 7 VTiU/ print f -Sn./ for -i>D/i<#D/i;;. print f- VT9(dU>9G.(fSn, VTiU./ print f-Sn total >9(.f Sn , total./ E *3T13T"&nter #D real numbers #.(.( ).) !.! G.G H.H I.I R.R Q.Q #D.#D VT#U>#.#D VT(U>(.(D VT)U>).)D VT!U>!.!D VTGU>G.GD VTHU>H.HD VTIU>I.ID VTRU>R.RD VTQU>Q.QD VT#DU>#D.#D total> !!H.RH consider an array of si4e ,say #DD. All the #DD elements have to be explicitly initiali4e. There is no way to specify a repeat count. $n such situations, it would be better to use a for loop to initiali4e the elements. Consider the following segment of a C program" for-i>D/i<#DD/i>i;#. B if-i<GD. sumTiU>D.D/ else sumTiU>#.D/ E the first GD elements of the array sum are initiali4ed to 4ero while the remaining GD elements are initiali4ed to #.D

$1o-D"ment"onal Arra%s
'o far we have discussed the array variable that can store a list of values .There will be situation where a table of values will have to be stored.Consider the following data table, which shows the value of the sales of three items by four sales mens" item # item ( item ) salesmen # )#D (IG )HG salesmen ( (#D #QD )(G salesmen ) !DG )(G (!D

salesmen !

(HD

)DD

(QD

the table contains a total of #( values, three in each line.Fe thin of this table as a matrix consisting of four rows and tree columns. &ach row represents the values of sales by a particular salesmen and each column represents the values of sales of a particular item.$n mathematics, we represent a particular value in a matrix by using two sub scripts such as XiN. Here X denotes the entire matrix and XiN refers to the value in the ith row and Nth column. ,or example, in the above table X() refers to the value )(G. C allows us to define such tables of items by using two%dimensional arrays. The table discussed above can be defined in c as vT(UT)U. Two%@imensional arrays are declared as follows" type array%name Trow%si4eUTcolumn%si4eU/ note that unli e most other languages which we use one pair of parenthesis with commas to separate array si4es.C places each si4e in the own set of brac ets.Two dimensional arrays are stored in memory as follows" TDUTDU )#D T#UTDU (#D T(UTDU !DG T)UTDU (HD TDUT#U (IG T#UT#U #QD T(UT#U )(G T)UT#U )DD TDUT(U )HG T#UT(U )(G T(UT(U (!D T)UT(U (QD

Initiali*ation Of +o-Dimentional &rra,s


li e the one%dimensional arrays,two%dimensional arrays may be initiali4ed by following their declaration with a list of initial values enclosed in braces. for example, static int tableT(UT)U > BD,D,D,#,#,#E/ initiali4es the elements of the first row to 4ero and the second row to one.The initiali4ation is done row by row. The above statement can be equivalently written as static int tableT(UT)U>BBD,D,DE, B#,#,#E./ by surrounding the elements of each row by braces. we can also initiali4e a two%dimensional array in the form of a matrix as shown below" static int tableT(UT)U > B BD,D,DE, B#,#,#E E/ note the syntax of the above statements, commas are required after each brace that closes off a row, except in the case of the last row.$f the values are missing in an initiali4er,they are automatically set to 4ero. ,or instance, the statement static int tableT(UT)U > B B#,#E, B(E

E/ will initiali4e the first two elements of the first row to one, the first element of the second row to two, and other elements to 4ero.Fhen all the elements are to be initiali4ed to 4ero, the following short%cut method may be used. 'tatic int mT)UT!U> BBDE, BDE, BDE,BDEE/ the first element of each row is explicitly initiali4ed to 4ero while other elements are automatically initiali4es to 4ero.

M'lt% D"ment"onal arr%s


C allows arrays of three or more dimensions. The exact limit is determined by the compiler. The general form of multi%dimensional array is type array%nameTs#UTs(UTs)U%%%%%%%%%%%%%%%%%%%%%%TsmU/ where si is the si4e of the ith dimension. 'ome examples are" int survey T)UTGUT#(U/ float table TGUT!UTGUT)U/ survey is a three dimensional array declared to contain #RD integer type elements.'imilarly table is a four dimensional array containing )DD elements of floating%point type.

Ob e!t"#e $%pe &'est"ons


#.what will be the output of the following program main-. B int aTGU, i/ static int bTGU/ for-i>D / i<G /i;;. print f-9d 9d 9d , i, aTiU, bTiU./ E output" D # ( ) ! #DD D %IG D #() D #(!G D )!I D

&xplanation "since the storage class of the array aTU has not been mentioned, the default storage class auto is assigned for it. As against this, the storage class of bTU has been explicitly mentioned as static. The default value of auto storage class variable is any garbage value and the default value of static storage variable is D. therefore all 4eros are printed out for bTU, where as garbage values are printed out for aTU. (. main-. B static int subTGU > B#D,(D,)D,!D,GDE/

int i/ for -i>D/i<>!/i;;. B if-i<>!. B subTiU>i7i/ print f- 9d, subTiU./ E E

output" no output &xplanation"there is a semicolon at the end of the for loop, thus the loop is reduced to the form" for-i>D/i<>!/i;;. this loop repeats the null statement -/.Gtimes and then the control comes out of the loop. At this time the value of i has become G and hence the if condition fails and the control reaches the closing brace of main-.. The execution is therefore terminated without any output to the screen. ). int bTGU/ main-. B static int aTGU/ int i/ for-i>D/i<>!/i;;. print f-9d 9d, bTiU, aTiU./ E D D D D D D D D D D

output "

&xplanation" default initial value of a static or extern storage class variable is D. thus ,though the array bTU and aTU have not been initiali4ed, the fact that their storage class is extern and static respectively causes their values to be D. !.main-. B static float arrTU> B#.(,#(,(.!,(!,).G,)GE/ int i/ for-i>D/i<>G/i;;. print f-9f, arrTiU./ E output" #.(DDDDD #(.DDDDDD (.!DDDDD (!.DDDDDD ).GDDDDD )G.DDDDDD &xplanation" were you expecting an error message because in the array initiali4ation some values are integers where as others are floatsJ Fell, the initiali4ation is perfectly alright. Fhen we initiali4e arrT#U to a value #(, what really gets stored in arrT#U is #(.Dsome thing happens when we try to store (!or )G in the array. They

are promoted to floats before storing the values.Thus the array contains all floats, there by meeting the basic requirement of the array that all its elements must be similar. 'ince print f-. always prints a float with a precision of H digits after the decimal point, each array element has been printed with six places after the decimal point. G.main-. B int si4e>#D/ int arrTsi4eU/ for-i>#/i<>si4e/i;;. B scan f-9d, ?arrTiU./ print f-9d,arrTiU./ E E output" error message" constant expression required in function main. &xplanation" while declaring the array , its si4e should always be mentioned with a positive integer constant.Thus arrT#DU is acceptable, where as arrTsi4eU is unacceptable, irrespective of whether si4e has been declared earlier to array declaration or not. Hence the error message. H.main-. B int i, N>#D, arrsi4e/ int arrTarrsi4eU/ if-N>>#D. arr si4e>(D/ else arr si4e>!D/ for-i>D/i< declaration. si4e array acceptable integer positive array.'o,only declare opportunity lost already if array, used be should this if, determined can that except 'o,if array. reserved space much how now executed,C statement declaration when because ambitious, too expecting si4e,and arr determine attempting N, values upon depending &xplanation" main. required expression constant error output"= #D.main-. B int i, N>#D, arrsi4e/ int arrTarrsi4eU/ if-N>>#D. arrsi4e>(D/ else arrsi4e>!D/ for-i>D/iD/. print f-9d, aT%%iU./ E output" $n the for loop, print f-. uses the expression aT%%iU. can operator be used with an array subscript J Ly all means. Here, since precedes i, firstly i is decremented and then its value is used in accessing the array elements. Thus,first time through the foor loop, when control reaches aT%%iU with i equal to G, firstly i is reduced to ! and then this ! is used to access the array element aT!U. This is done repeatedly through the

for loop till the array elements have been printed. #(.main-. B static int aTGU>BG,#D,#G,(D,(GE/ int i,N,m,n/ i>;;aT#U/ N>aT#U;;/ print f-i>9d N>9d aT#U9dSn,i,N,aT#U./ i>#/ m>aTi;;U/ print f-i>9d m>9d Sn, i,m./ i>(/ n>aT;;iU/ print f-i>9d n>9d i, n./ E output" i>## N>## aT#U>#( i>( m>#( i>) n>(D explanation" in i>;;aT#U, since ;; precedes aT#U,firstly the value of aT#U i.e, #D would be incremented to ##, and then assigned to the variable i. As against this, in the next statement,firstly the element aT#U-i.e, ##. would be assigned to N and then the value of aT#U would be incremented to #(. the value of i,N ? aT#U are then printed out.6ext,i is reset to #.in m>aTi;;U, since ;; succeeds i, firstly aTiU, i.e, #( is assigned to variable m,and then the value of i, i.e, #, is incremented to (. the values of i and m are then printed out. #).main-. B int arr-(!.,i/ for-i>D/i<>#DD/i;;. B arr-i.>#DD/ print f-9d, arr-i../ E E output" error message"function definition out of place in function main. &xplanation" the moment the compiler finds -.,it expects a reference to a function, and arr has not been defined as a function. Hence the error message. #!.main-. B static int aTU>B#D,(D,)D,!D,GDE/ int N/ for-N>D/N<G/N;;. B print f-9d, 7a./ a;;/ E E output"error message" L value required in function main.

&xplanation " whenever we mention the name of the array, we get its base address. Therefore,first time through the loop, the print f-. should print the value of this base address. There is no problem up to this. The problem lies in the nextstatement,a;;. since C doesn0t perform bounds chec ing on an array, the only thing that it remembers about an array oncedeclared is its base address. And a;; attempts to change this base address, which C wont allow because if it does so, itwould be unable to remember the beginning of the array. Anything which can change in compilers language is called Lvalue. 'ince value of a cannot be changed through ;;, it flashes the error saying L value required. 'o that ;; operator can change it. #G.main-. B static float aTU>B#).(!,#.G,#.G,G.!,).GE/ float 7N, 7 / N>a/ >a;!/ N>N7(/ > 8(/ print f-9f9f, 7N, 7 ./ E output"error message" illegal use of pointers in function main. &xplanation" N and has been declared as pointer variables, which would contain the addresses of floats. $n other words,N and are float pointers.To begin with, the base address of the array aTU is stored in N. the next statement is perfectly acceptable/ the address of the fourth float from the base address is stored in . the next two statements are erroneous.This is because the only operations that can be performed on pointers are addition and subtraction. :ultiplication or division of a pointer is not allowed. Hence the error message. #H.main-. B int nT(GU/ nTDU>#DD/ nT(!U>(DD/ print f-9d 9d,7n, 7-n;(!. ; 7-n;D../ E output" #DD )DD explanation" nTU has been declared as an array capable of holding (G elements numbered D to (!.then #DD and (DD are assigned to nTDU and nT(!U respectively. Them comes the most important part the print f-. statement. Fhenever we mentionthe name of the array, we get its base address.Thus, 7n would give the value at this base address, which in this case is #DD.this is then printed out. Loo at the next expression, 7-n;(!. ; 7-n;D. n gives the address of the 4eroth element, n;# gives the address of the next element of the array, and so on. Thus n;(! of the next element of the array, and so on. Thus n;(!

gives the address of the last element of the array, and therefore 7-n;(!. would give the value at this address, which is (DD in this case. 'imilarly, 7-n;D. would give #DD and the additionof the two would result into )DD, which is outputted next. #I.main-. B static int aTGU > B(,),!,G,HE/ int i/ change -a./ for-i>!/i>D/i%%. printf-9d, aTiU./ E change -b. int 7b/ B int i/ for-i>D/i<>!/i;;. B 7b > 7b;#/ b;;/ E E output" I H G ! ) explanation" while calling change-. we are passing the base addresses of the array, which as per fig is !DD(. this address is collected in b in function change-.. Then the control enters the for loop, where we meet the expression b>b;#. This means replace the value at the address contained in b, with value at the address contained in b plus #.every time b;; is executed, the address of the next integer gets stored in b. thus, using the address stored in b, we get an access to array elements which are now changed to ),!,G,H,I. once the control comes bac from chance-. the current array contents are then printed out from end to beginning through the for loop. ( ! G H

Intro('!t"on $o Str"n)s
The way a group of integers can be stored in an integer array, similarly a group of characters can be stored in a character array . Character array are often called strings. A string constant is a one%dimensional array of characters terminated by a null-0SD0..The A'C$$ value of -0SD0. is D. &ach character in the array occupies one byte of memory and the last character is always0SD0. The following example illustrates how a string is stored and accessed main-.

static char nameTU>C6agpurC/ int i>D/ while -nameTiU5>0SD0. B printf-C9cC,nameTiU./ i;;/ E A string can also be initiali4ed as static charTU>C6agpurC/

Here 0SD0 is not necessary . C inserts it automatically. The terminating null-0SD0. is important,because it is the only way the functions that wor with a string can now where the string ends. Declarin! and Initiali;in! strin! ,aria#les: A string variable is any valid c variable name and is always declared as an array .The general form of declaration of a string variable is" char stringMname Tsi4eU/ The si4e determines the number of characters in the stringMname.The si4e should be equal to the maximum number of characters in the string plus one.0C0 permits a character array to be initiali4ed in either of the following two forms static char cityTQU > C6ewyor C/ static char cityTQU > B060,0&0,0F0,0K0,0*0,020,0O0,0SD0E/

Rea("n) Str"n)s From t*e $erm"nal


The familiar input function scanf can be used with 9s format specification to read in a string of characters. char addressT#GU/ scanf-C9sC, address./ The problem with the scanf function is that it terminates its input on the first white space it finds.Therefore if the following line of text is typed in at the terminal,6&F K*2O then only the string C6&FC will be read into the array address,since the blan space after the word C6&FC will terminate the string. <ote: 3nli e previous scanf calls, in the case of character arrays , the ampersand-?. is not required before the variable name. The scanf function automatically terminates the string that is read with a null character and therefore the character array should be large enough to hold the input string plus the null character.0C0 does not provide operators that wor on strings directly. ,or instance we cannot assign one string to another directly. string > CALCC/ string# > string(/ are not valid. 0ritin! strin!s to screen: The 9s format can be used to display an array of characters that is terminated by the null character.9 #D.!s indicates that the first four characters are to be printed in a field width of #D columns.9%#D.!s indicates that the string will be printed left Nustified.

<ote : #.Fhen the field width is less than the length of the string, the entire string is printed. (.The integer value on the right side of the decimal print specifies the number of characters to be printed. ).Fhen the number of characters to be printed is specified as 04ero0 nothing is printed. !.The minus sign in the specification causes the string to be printed left Nustified

Ar"t*emet"! Operat"ons On C*ara!ters


0C0 allows us to manipulate characters in the same way we do with numbers.Fhenever a character constant or character variable is used in an expression , it is automatically converted to integer value by the system . $nteger value depends on local character set of the system . $f the machine uses the A'C$$ representation then x > 0a0/ printf-C9dC, x./ will display the number QI on the screen. ex: x > 040%#/ is a valid statement $n A'C$$ , the value of 040 is #(( , therefore the value #(# is assigned to x. The 0c0 library supports a function that converts a string of digits into their integer values . The function ta es the form x > atoi-string./ x is an integer variable and string is a character array containing a string of digits. ex" %%%%%%%%%%%%%%%%%% number > C#QRRC/ year > atoi-number./ The function converts the string C#QRRC to its numeric equivalent #QRR and assigns it to the integer variable year

P'tt"n) Str"n)s $o)et*er


Fe cannot assign one string to another directly Fe cannot Noin two strings together by the simple arithmetic addition. string) > string#;string(/ string) > string#;0helloC/ are not valid. The characters from string# and string( should be copied into the string) one after the other.The si4e of string) should be large enough to hold the total characters.The process of combining two strings together is called concatenation.0C0 does not permit the comparison of two strings directly. if-name#>>name(. if-name>>00ALCC. are not valid. $t is therefore necessary to compare the two strings to be tested , character by character.

The comparison is done until there is a mismatch or one of the string terminates into a null character, whichever occurs first.

Str"n) Han(l"n) F'n!t"ons In C


Fith every C compiler a large set of useful string handling library functions are provided. The following figure illustrates the more commonly used functions along with their purpose. #.strlen" ,inds length of a string (.strlwr" Converts a string to lower case ).strupr" Converts a string to upper case !.strcat" Appends one string at the end of the other G.strncat" Appends first n characters of a string at the end of another H.strcpy" Copies a string into another I.strncpy" Copies first n characters of one string into another R.strcmp" Compares two strings Q.strncmp" compares first n characters of two strings #D.strcmpi" compares two strings without regard to case ##.strnicmp" compares first n characters of two strings without regard to case #(.strdup" duplicates a string #).strchr" finds first occurrence of a given character in a string #!.strrchr" ,inds last occurrence of a given character in a string #G.strstr" ,inds first occurrence of a given string in another string #H.strset" 'ets all characters of string to a given character #I.strnset" 'ets first n characters of a string to a given character #R.strrev" 2everses string strlen34 strcp534 strcat34 strcmp34

Pro)rams In Str"n) Han(l"n) F'n!t"ons


#.$s the folowing program correct or notJ main-. B char 7str# > C3nitedC/ char 7 str( > C,rontC/ char 7str)/ str) > strcat-str#, str(./ printf-CSn 9sC, str)./ E Ans" 6o, since what is present in memory beyond CunitedC is not nown and we are attaching C,rontC at the end of C3nitedC, thereby overwriting something, which is unsafe thing to do. yes8no

(.How would you improve the code in the above programJ Ans" main-. B char str#T#GU > C3nitedC/ char 7str( > C,rontC/ char 7str)/ str) > strcat-str#,str(./ printf-CSn9sC, str)./ E ). Frite a program to enter the two strings and compare them without using any standard function. @etermine whether the strings are identical or not. Also display the number of position where the characters are different. main-. B static char srT#DU, trT#DU/ int diff > D,i/ clrscr-./ printf-CSn enter the stringC./ gets-sr./ printf-Center the second stringC./ gets-tr./ for-i >D/ i<#D/i;;. B if-srTiU >>trTiU./ continue/ else B printf-C9c 9cSnC, srTiU,trTiU./ diff;;/ E E if-strlen-sr. >> strlen-tr.??diff >> D. puts-CSn The two strings are identicalC./ else printf-CSn The two strings are different at 9d placesC, diff./ getch-./ E output" enter the string" L&'T L3CO enter the second string" +**@ L3CO + L * & * ' @ T !.Frite a program to concatenate two strings without the use of standard library functions main-. B char nameTGDU, fnameT#GU, snameT#GU, lnameT#GU/ int i,N, / printf-Cfirst nameC./ grts-fname./

printf-Csecond nameC./ grts-sname./ printf-Clast nameC./ grts-lname./ for-i >D/ fnameTiU5>0SD0/ i;;. nameTiU>fnameTiU/ nameTiU>0 0/ for-N >D/ snameTNU5>0SD0/ N;;. nameTi;N;#U>snameTiU/ nameTi;N;#U>0 0/ for- >D/ lnameT U5>0SD0/ ;;. nameTi;N; ;(U>lnameT U/ nameTi;N; ;(U>0SD 0/ printf-CSnSnC./ printf-Ccomplete name after concatenationSnC./ printf-C9sC, name./ getch-./ E output" first name" :*HA6 second name"OA2A:CHA6@ last name" +A6@H$ complete name after concatenation :*HA6 OA2A:CHA6@ +A6@H$ G.Frite a program to display reverse of a string without using standard library functions. main-. B char textT#GU/ int i > D/ printf-Center the stringC./ gets-text./ while-textTiT5>0SD0. B printf-CSn Gc is stored at location 9uC, textTiU,?textTiU. i;;/ E strrev-text./ printf-Creverse stringC./ printf-C9sC,text./ i >D/ while-textTiU5>0SD0. B printf-CSn 9c is stored at location 9uC,textTiU, ?textTiU./ i;;/ E E output" enter string"ALC A is stored at location L is stored at location C is stored at location reverse string"CLA C is stored at location L is stored at location A is stored at location

!DG! !DGG !DGH !DG! !DGG !DGH

H.Frite a program to find the number of words in a given

statement . &xclude spaces between them. main-. B char textT)DU/ int count > D,i > D/ printf-Center the line of textC./ printf-Cgive one space after each wordC./ gets-text./ while-textTi;;U5>0SD0. if-textTiU>>)( AA textTiU>>0SD0. cout;;/ printf-CThe number of words in line > 9dSnC, count./ E output" enter the line of text give one space after each words read boo s The number of words in line > (

Arra% O- Po"nters $o Str"n)s


As we now , a pointer variable always contains an address. Therefore , if we construct an array of pointers it would contain a number of addresses.Let us see how the names in the earlier example can be stored in the array of pointers. char 7namesTU > B Ca shayC, CparagC, CramanC, CsrinivasC, CgopalC, CraNeshCE/ $n this declaration namesTU is an array of pointers.$t contains base addresses of respective names.That is. base address of Ca shayC is stored in namesTDU, base address of CparagC is stored in namesT#U and so on. $n the two%dimensional array of characters,the strings occupied HD bytes.As against this ,in array of pointers,the strings occupy only !# bytes. 6ote that in two%dimensional array of characters ,the last name ended at location number #DHD,whereas in array of pointers to strings , it ends at #D!#.A substantial saving, you would agree. Lut realise that actually #Q bytes are not saved, since #D bytes are sacrificed for storing the address in array names .Thus ,one reason to store strings in an array of pointers is to ma e a more efficient use of available memory. Another reason to use an array of pointers to store strings is to obtain greater ease in manipulation of the strings. This is shown by the following programs. The first one uses a two%dimensional array of characters to store the names, whereas the second uses an array of pointers to strings . The purpose of both the programs is very simple. Fe want to exchange the position of the names CramanC and CsrinivasC. Exchan!e names usin! 2-D arra5 of characters

main-. B char namesTUT#DU > B Ca shayC, CparagC, CramanC, CsrinivasC, CgopalC, CraNeshCE/ int i/ char t/ printf-CSn original" 9s9sC,?namesT(UTDU, ?namesT)UTDU./ for-i > D/ i<> Q/ i;;. B t > namesT(UTiU/ namesT(UTiU > namesT)UTiU/ namesT)UTiU > t/ E printf-CSn 6ew"9s9'C, ?namesT(UTDU, ?namesT)UTDU./ E output" *riginal" raman srinivas 6ew" srinivas raman 6ote that in this program to exchange the names we are required to exchange corresponding characters of the two names. $n effect , #D exchanges are needed to interchange two names Let us see if the number of exchanges can be reduced by using an array of pointers to strings. Here is the program... main-. B char 7namesTU > B Ca shayC, CparagC, CramanC, CsrinivasC, CgopalC, CraNeshCE/ char 7temp/ printf-Coriginal" 9s 9sC, namesT(U, namesT)U./ temp > namesT(U/ namesT(U > namesT)U/ namesT)U > temp/ printf-CSn 6ew" 9s 9sC, namesT(U, namesT)U./ E output" original" raman srinivas 6ew" srinivas raman

Limitations of arra, )ointers to strings


Fhen we are using a two%dimensional array of characters we are at liberty to either initiali4e the strings where we are declaring the array, or receive the stringsusing scanf-. function. However,when we are using an array of pointers to stringswe can initiali4e the strings at the place where we are declaring the array,but we cannot receive the strings from eyboard using scanf-..Thus the following program would never wor out. main-. B char 7namesTHU/ int i/ for-i >D/ i<> G/ i;;. B printf-CSn enter nameC./

scanf-C9sC,namesTiU./ E E The program doesn0t wor because/ when ae are declaring the array it is containing the garbage values. And it would be definitely wrong to send these garbage values to scanf-. as the address where it should eep the strings received from the eyboard. Frite a function xstrstr-. that will return the position where one string is present within another string. $f the second string doesn0t occur in the first string xstrstr-. should return a D. ,or example, in the string Csomewhere over the rainbowC, CoverC is present at location ##. main-. B static char str#TU > Csomewhere over the rainbowC/ static char str(TU > CoverC/ printf-Cstring found at 9dC, xstrstr-str#, str(../ E xstrstr-s#, s(. char 7s#, 7s(/ B int i, a, len#, len(/ len# > strlen-s#./ len( > strlen-s(./ for-i > D/ i<>-len%#./ i;;. B a > strncmp--s#;i. , s(, len(./ if-a >> D. return -i;#./ E return -D./ E output" string found at ## &xplanation" The two strings have been declared as str#TU and str(TU in main from where the base addresses are sent to the function xstrstr-. for searching the second string in the first one. $n xstrstr-., len# and len( store the lengths of the ( strings withbase addresses s# and s( respectively .$n the for loop, i is incremented len# number of times. As many times, the standard library function strncmp-t,s, n. gets called.This function compares the first n elements of strings starting from t and s and returns D if they are equal.The first time through the for loop, i is D. Hence strncmp-. compares the first len( -here len( is equal to !. elements of strings starting from -s#;D. i.e s#and s( a collects a non%4ero value, as the first four elements of the two strings are found to be different.The control therefore reverts bac to the for where i is incremented to #.'o the second time through the loop strncmp-. compares first len( elements of strings starting from s# and s(. Literally first ! elements of Csomewhere over the rainbowC and CoverC are compared .*nce again a collects a non%4ero value and i is incremented a second time.this goes on similarly till i is #D, when s#;#D

denotes the base address of the string Cover the rainbowC. This time a is assigned a D,as both the strings have o, v, e and r as the first four elements, and control returns to main-. with i;#, i.e ##.This is the position of the second string in the first one.'uppose the second string is not present in the first string at all, then at no time a would contain D. Thus the return statement after the loop would return D,signifying that the second string was not found in the first one.

Sample Pro)rams
#.Frite a program to count the number of capital letters in the following array of pointers to strings. static char 7strTU > B C+ive A 'tring HereE/ main-. B static char 7strTU > B C+ive A 'tring HereE/ printf-Cno.of capitals > 9dC, capcount-s,!../ E capcount-s, c. char 77s/ int c/ B int i, cap > D/ char 7t/ for-i > D/ i>HG ?? 7t<> QD. cap;;/ t;;/ E E return -cap./ E output" 6o.of capitals > ! (.Frite a program to print those strings which are polindromes from a set of strings stored in the following array of pointers to strings. static char 7sTU > BC:alayala:C/CTo really mess things up...C/ C*ne needs to now c55C Cable was i ere i saw elbaCE/ main-. B static char 7sTU > BC:alayala:C/CTo really mess things up...C/ C*ne needs to now c55C Cable was i ere i saw elbaCE/ char revT)DU/ int i,a/ for-i>D/ i<>)/ i;;. B strcpy-rev, sTiU./ strrev-rev./ a > strcmp-sTiU, rev./ if-a >>D. printf-C9sSnC, sTiU./

E E output" :alayala: able was i ere i saw elba

Ob e!t"#e $%pe &'est"ons


#.Fhat would be the output of the following programJ main-. B printf-G;CfascimileC./ E A. error L. fascimile C. mile @. none of the above Ans" C (.Fhat would be the output of the following programJ main-. B char str#TU > CHelloC/ char str(TU > CHelloC/ if-str# >> str(. printf-CSn &qualC./ else printf-CSn3nequalC./ E A. &qual Ans" L ).Fhat would be the output of the following programJ main-. B printf-C9cC,CabcdefghCT!U./ E A. &rror Ans" C !.How would you output Sn on the following screenJ Ans" printf-CSSnC./ G.Fhat would be the output of the following programJ main-. B char strTIU > CstringsC/ printf-C9sC, str./ E A. error L. strings C. cannot predict L. d C. e @. abcdefgh L. 3nequal C. &rror @. 6one of the above

@. none of the above

Ans" C Here strTU has been declared as a I character array and

into it a R character string has been stored . This would result into overwriting of the byte beyond the seventh byte reserved for the array with a 0SD0.There is always a possibility that something important gets overwritten which would be unsafe . H.Fhat would be the output of the following programJ main-. B char ch > 0A0/ printf-C9d9dC, si4eof-ch., si4eof-0A0../ E A. # # Ans" L L. # ( C. ( ( @. ( #

I. Fhat would be the output of the following programJ main-. B printf-CSn9d9d9dC, si4eof-0)0., si4eof-C)C., si4eof-)../ E A # # # L. ( ( ( C. # ( ( @. # # # Ans"L R. Fhat would be the output of the following programJ main-. B char 7strTU > BC,rogsC, C@oC, C6otC, C@ieC, CTheyC, CCroa CE/ printf-C9d 9dC, si4eof-str., si4eof-strTDU../ E Ans" #( (

Q. Fhat would be the output of the following programJ main-. B static char sTU > C2ende4vousC/ printf-C9dC, 7-s;strlen-s.../ E Ans" D

&xplanation" 6o 2ende4vous, but a 4ero is printed out. :entioning the name of the string gives the base address of the string. The function strlen-s. returns the length of the string sTU, which in this case is #(. $n the printf-., using the 0contents of0 operator , we are trying to print out the contents of #(th address from the base address of the string. At this address there is a 0SD0 ,which is automatically stored to mar the end of the string. The A'C$$ value of 0SD0 is D, which is what being printed by the printf-.. #D. Fhat would be the output of the following programJ main-.

char chT(DU/ int i/ for-i>D/ i<>#Q/ i;;. 7-ch;i. > HI/ 7-ch;i. > 0SD0/ printf-C9sC , ch./

Ans" CCCCCCCCCCCCCCCCCCC &xplanation":entioning the name of the array always gives its base address . Therefore -ch;i. would give the address of the ith element from the base address , and 7-ch;i. would give the value at the address , i.e the value of the ith element . Through the for loop we store HI, which is the A'C$$ value of upper case 0C0 , in all locations of the string.*nce the control reaches outside the for loop the value of i would be #Q , and in the #Qth location from the base address we store a 0SD0 to mar the end of the string. This is essential , as the compiler has no other way of nowing where the string is terminated .$n the printf-. that follows , 9s is the format specification for printing a string, and ch gives the base address of the string .Hence starting from the first element ,the complete string is printed out. ##. Fhat would be the output of the following programJ main-. B char strT(DU/ int i/ for-#>D/#<>#R/ i;;. iTstrU > 0C0/ iTstrU > 0SD0/ printf-C9sC,str./ E Ans"CCCCCCCCCCCCCCCCCCC &xplanation" $f your concept of arrays is fool%proof , you should find the above o8p only natural. $f not, here0s your chance to ma e it so. C ma es no secret of the fact that it uses pointers internally to access array elements .Fith the nowledge of how array elements are accessed using pointers, we can thin of strTiU as 7-str;i.. Lasic maths tells us that 7-str;i. would be same as 7-i;str.. And if strTiU is same as 7-str;i., then naturally 7-i;str. would be same as iTstrU.Thus, we can conclude that all the following expressions are different ways of referring the ith element of the string" strTiU 7-str;i. 7-i;str. iTstrU Hence, through the for loop upper case C is stored in all the elements of the string. A 0SD0 is stored to mar the end of the string, and then the string is printed out using printf-.. #(.Fhat would be the output of the following programJ main-.

char strT(DU/ static int i/ for-/ /. B i;;TstrU > 0A0 ; (/ if-i >> #Q. brea / E iTstrU > 0SD0/ printf-C9sC,str./

Ans"CCCCCCCCCCCCCCCCCCC #). Fhat would be the output of the following programJ main-. B static char strTU>B!R,!R,!R,!R,!R,!R,!R,!R,!R,!RE/ char 7s/ int i/ s > str/ for- i > D/ i<>Q/ i;;. B if-7s. printf-C9cC, 7s./ s;;/ E E Ans" DDDDDDDDDD &xplanation" $n all #D elements of strTU, an integer , !R is stored. Fondering whether a char string can hold intsJ The answer is yes, as !R does not get stored literally in the elements. !R is interpreted as the A'C$$ value of the character to be stored in the string. the character corr% esponding to A'C$$ value !R happens to be D, which assig% ned to all the locations of the string.0s0, a character pointer, is assigned the base address of the string strTU. 6ext , in the if condition,the value at address contained in s is chec ed for truth8falsity.As D represents A'C$$ !R, the condition evaluates to true every time, until the end of the string is reached. At the end of the string a 0SD0, i.e A'C$$ D is encountered , and the if condition fails. $rrespective of whether the condition is satisfied or not, 0s0 is incremented so that each time it points to the subsequent array element .This entire logic is repeated in the for loop , printing out #D 4eros in the process. #!. Fhat would be the output of the following programJ main-. B static char strTU>BD,D,D,D,D,D,D,D,D,DE/ char 7s/ int i/ s > str/ for- i > D/ i<>Q/ i;;. B if-7s.

printf-C9cC, 7s./ s;;/ E E

Ans" 6o output &xplanation" Though you may not have expected 4eros to be outputted this time,you surely did expect some output5 Fe stored the character corresponding to A'C$$ D in all #D elements of the string. 6ext, we assigns s, a char pointer, the base address of the string . Though the for loop , we are attempting to print out all elements one by one , but not before imposing the if condition.The if is made to test the value at address contained in 0s0 before the execution of the printf- . .The first time , 7s yields A'C$$ D. Therefore the if condition reduces to if-D. , and as D stands for falsity, the condition fails. Hence ,0s0is incremented and control loops bac to for without executing the printf-.. The same thing happens the next time around , and the next, and so on, till the for loop ends, resulting in no output at all. #G. Fhat would be the output of the following programJ main-. B static char sTU>CC 'mart55C/ int i/ for-i >D/ sTiU/ i;;. printf-C9c9c9c9cSnC,sTiU,7-s;i.,iTsU,7-i;s../ E Ans" C ' m a r t C ' m a r t C ' m a r t C ' m a r t

5 5 5 5 &xplanation"The above program rubs in the point that sTiU, iTsU,7-s;i. and 7-i;s. are various ways of referring to the same element, that is the ith element of the string s. &ach element of the string is printed out for four times,till the end of the string is encountered. 6ote that in the for loop there is an expression sTiU in the condition part. This means the loop would continue to get executed till sTiU is not equal to 4ero. Fe can afford to say this because a string always ends with a 0SD0, whose A'C$$ value is D. Thus the for loop will be terminated when the expression sTiU yields a 0SD0. #H. Fhat would be the output of the following programJ main-. B static char sTU > C*in s +runts and +uffawsC/ printf-C9cSnC, 7-?sT(U../ printf-C9sSnC, s;G./ printf-C9sSnC, s./ printf-C9cSnC, 7-s;(../ printf-9sSnC, s./ E

Ans" n

+runts and +uffaws *in s +runts and +uffaws n !D! &xplanation" $n the first printf-. the address of operator, ? gives the address of the second element of the string . Xalue at this address is 0n0 , which is printed out by the printf-. using 9c. since s gives the base address of the array , -s;G. would give the address of the fifth element from the base address . This address is passed to the second printf-. . 3sing the format specification 9s , the contents of the string are printed out the Gth element onwards.The third printf-. prints the entire string , as the base address of the string is being passed to it. The fourth printf-. is made to print the second character of the string , as 7-s;(. is nothing but sT(U. Thus 0n0gets printed.@oes the o8p of the final printf-. surprise you by printing out a number , !D!J 6ote that the format specification 9d is used with s, which gives the base address of the string. $t happened to be !D! when we executed the program, which got printed out. *n executing the same yourself, you may get any other address, depending on what address is allotted to the string by the compiler. #I.Fhat would be the output of the following programJ main-. B static char sT(GU > CThe cocaine manC/ int i >D/ char ch/ ch > sT;;iU/ printf-C9c9dSnC,ch,i./ ch > sTi;;U/ printf-C9c9dSnC,ch,i./ ch > i;;TsU/ printf-C9c9dSnC,ch,i./ ch > ;;iTsU/ printf-C9c9dSnC,ch,i./ E Ans" h # h ( e ) 5 ) #R.Fhat would be the output of the following programJ main-. B static char arrTU > Cpic poc eting my piece of mindC/ int i" printf-C9cSnC, 7arr./ arr;;/ printf-C9cSnC, 7arr./ E Ans" Lvalue required in function main

Bas"! Po"nters
"ointer Definition: 1ointer is a variable which contains the address of another variable.2easons for using pointer" #.A pointer enables us to access a variable that is defined outside the function. (.1ointers are more efficient in handling the data tables. ).1ointers reduce the length and complexity of a program. !.They increase the execution speed G.The use of pointer array to character strings results in saving of data storage space in memory. 2epresentation of a variable" Consider the following statement int 7p/ int quantity>#IQ/ p>?quantity/ Here p is a pointer variable of type integer,which holds the address of the variable quantity. Declarin! and initiali;in! pointers: $n c,every variable must be declared for its type since pointer variable contain address that belong to a seperate data type, they must be declared as pointers before we use them.The declaration of a pointer variable ta es the following form. data type 7pt%name/ This tells the compiler three things about the variable pt%name #.The asteric -7. tells that the variable pt%name is a pointer variable. (.pt%name needs a memory location. ).pt%name points to a variable of type data type. for example, int 7p/ declares the variable p as apointer variable that points to an integer data type.2emember that the type int refers to the data type of the variable being pointed to by p and not the type of the value of the pointer. 1rogram to print the address of a variable along with its value. main-. B char a/ int x/ float p,q/ a>0A0/ x>#(G/ p>#D.(G,q>#R.IH/ printf-C9c is stored at printf-C9d is stored at printf-C9f is stored at printf-C9f is stored at E *utput" A is stored at addr !!)H #(G is stored at addr !!)!

addr addr addr addr

9u 9u 9u 9u

SnC,a,?a./ SnC,x,?x./ SnC,p,?p./ SnC,q,?q./

#D.(GDDDD is stored at addr !!!( #R.IHDDDD is stored at addr !!)R. Accessing variables using pointers main- . B int x,y/ int 7ptr/ x>#D/ ptr>?x/ y>7ptr/ printf-Cvalue of x is 9dSnSnC,x./ printf-C9d is stored at addr 9uSnC,x,?x./ printf-C9d is stored at addr 9uSnC,7?x,?x./ printf-C9d is stored at addr 9uSnC,7ptr,ptr./ printf-C9d is stored at addr 9uSnC,y,?7ptr./ printf-C9d is stored at addr 9uSnC,ptr,?ptr./ printf-C9d is stored at addr 9uSnC,y,?y./ 7ptr>(G/ printf-CSn 6ow x>9dSnC,x./ E *uput" value of x is #D #D is stored at addr !#D! #D is stored at addr !#D! #D is stored at addr !#D! #D is stored at addr !#D! !#D! is stored at addr !#DH #D is stored at addr !DR.

6ow x>(G.

Ob e!t"#e $%pe &'est"ons on Po"nters


#.Fhat would be the output of the following programJ [include Cstdio.hC main- . B printf- C9d 9dC, si4eof-63LL.,si4eof-C C . ./ E -a. -b. -c. -d. Ans" # # ( ( c # ( # (

(.How many bytes are occupied by near,far and huge pointersJ -a. -b. -c. -d. Ans" (,(,! (,!,! (,!,( (,(,( b

!.Can anything else generate a 6ull 1ointer Assignment

errorJ -a. -b. -c. -d. Ans" Kes 6o Can0t say 6one a

G. Are the three declarations char 77apple, char 7orangeT U, and char cherry T U T U sameJ -a. -b. -c. -d. Ans" Kes 6o Can0t say 6one b

H.Can two different near pointers contain two different addresses but refer to the same location in memoryJ -a. -b. -c. -d. Ans" Kes 6o Can0t say 6one b

I. Can two different far pointers contain two different addresses but refer to the same location in memoryJ -a. -b. -c. -d. Ans" Kes 6o Can0t say 6one a

R. Can two different huge pointers contain two different addresses but refer to the same location in memoryJ -a. -b. -c. -d. Ans" Kes 6o Can0t say 6one b

Q.Fould the following program give any warning on compilationJ [include Cstdio.hC main- . B int 7p#,i>(G/ void 7p(/ p#>?i/ p(>?i/ p#>p(/ p(>p#/ E

-a. -b. -c. -d. Ans"

Kes 6o Can0t say 6one b

#D.Fould the following program give any warning on compilationJ [include CstdiohC main- . B float 7p#,i>(G.GD/ char 7p(/ p#>?i/ p(>?i/ E -a. -b. -c. -d. Ans" Kes. 'uspicious pointer conversion in function main 6o Can0t say 6one a

##.Fhat warning would be generated on compiling the following programJ main- . B char far 7scr/ scr>D7LRDDDDDD/ 7scr > 0A0/ E -a. -b. -c. -d. Ans" 'uspicious pointer conversion in function main 6on%portable pointer assignment in function main Can0t say 6one b

#(.How would you eliminate the warning generated on compiling the following programJ main- . B char far 7scr/ scr>D7LRDDDDDD/ 7scr > 0A0/ E -a. -b. -c. -d. 3se 3se 3se 3se the the the the typecast typecast typecast typecast scr> scr> scr> scr> -char -char -char -char 7far . D7LRDDDDDD/ far 7 . D7LRDDDDDD/ 77far . D7LRDDDDDD/ far 77 . D7LRDDDDDD/

Ans" b #). $n a large data model -compact, large, huge. all pointers to data are )( bits long,whereas in a small data model -tiny, small,medium. all pointers are #H bits long

-a. -b. -c. -d. Ans"

True ,alse Can0t say 6one a

#!. A near pointer uses the contents of C' register -if the pointer is pointing to code. or contents of @' register -if the pointer is pointing to data. for the segment part,whereas the offset part is stored in the #H%bit near pointer -a. -b. -c. -d. Ans" #G. True ,alse Can0t say 6one a Fhat would be the output of the following programJ

main- . B char far 7a>D7DDDDD#(D/ char far 7b>D7DD#DDD(D/ char far 7c>D7DD#(DDDD/ if-a>>b. printf-CSnHelloC./ if-a>>c. printf-CSnHiC./ if-b>>c. printf-CSnHello HiC./ if-a=b ?? a=c ??b=c. printf-CSnLyeC./ E -a. -b. -c. -d. Ans" #H. Hello Hi Hello Hi Lye d Fhat would be the output of the following programJ

main- . B char huge 7a>D7DDDDD#(D/ char huge 7b>D7DD#DDD(D/ char huge 7c>D7DD#(DDDD/ if-a>>b. printf-CSnHelloC./ if-a>>c. printf-CSnHiC./ if-b>>c. printf-CSnHello HiC./ if-a=b ?? a=c ??b=c. printf-CSnLyeC./ E

-a. -b. -c. -d. ans" #I.

Hello Hi Hello Hi all d Are the expressions 7ptr;; and ;;7ptr sameJ

-a. Kes -b. 6o -c. Can0t 'ay -d. 6one Ans" b #R.Can you write another expression which does the same Nob as ;;7ptrJ -a. -b. -c. -d. -ptr7.;; 7ptr;; ptr7;; -7ptr.;;

Ans" d #Q. Fhat would be the equivalent pointer expression for referring the same element as aTiUTNUT UTlUJ -a. -b. -c. -d. 7-7-7-7-a;i.;N.; .;l. 7-7-7-7aTiU.TNU.T U.TlU. both 6one

Ans" a (D. Fhat would be the output of the following program J main- . B int arrT U>B#(,#),#!,#G,#HE/ printf-CSn9d 9d 9dC,si4eof-arr.,si4eof-7arr., si4eof-arrTDU../ E -a. -b. -c. -d. #D #D #D #D ! ! ( ( ! ( ( !

Ans" c (#.Fhat would be the output of the following program assuming that the array begins at location #DD(J main- . B int aT)UT!U>B#,(,),!, G,H,I,R, Q,#D,##,#( E/ printf- CSn9u 9u 9uC,aTDU;#,7-aTDU;#.,7-7-a;D.;#../ E

-a. -b. -c. -d.

#DD! #DD! #DD( #DD(

! ( !

! ( !

Ans" a ((. Fhat would be the output of the following program assuming that the array begins at location #DD(J main- . B int aT(UT)UT!U>B B

#,(,),!, G,H,I,R, Q,#,#,( E, B (,#,!,I, H,I,R,Q, D,D,D,D E

E/ printf-CSn9u 9u 9u 9dC,a,7a,77a,777a./ E -a. -b. -c. -d. #DD( #DD( #DD( #DD( #DD! #DD! #DD! #DD! #DD( #DD( #DD! #DD! ( # # (

Ans" b (). $n the following program how would you print GD using pJ main- . B int aT U>B#D,(D,)D,!D,GDE/ char 7p/ p > -char 7. a/ E -a. -b. -c. -d. Ans" printf-CSn9dC,7- -int 7.p;!. ./ printf-CSn9dC,- -int 7.p;!. ./ printf-CSn9dC,7- -int .p;!. ./ printf-CSn9dC,7- -int 77.p;!. ./ a

(!.$n the following program add a statement in the function fun- . such that address of a gets stored in N main- . B int 7N/ void fun-int 77./ fun-?N./ E void fun-int 77 .

B E

int a>#D/

-a. 7 >?a/ -b. ?a>7 / -c. ? >7a/ -d. 7a>? / Ans" a (G.How would you declare an array of three function pointers where each function receives two ints and returns a floatJ -a. -b. -c. -d. float -arrT)U.-int,int./ int -arrT)U.-float,float./ int -7arrT)U.-float,float./ float-7arrT)U.-int,int./

Ans" d

3ointers 4nd 5trings

Str"n)s
A group of characters can be stored in a character array. Character arrays are many a times also nown as 0strings. 'trings are the data types used by programming languages to manipulate text such as words and sentences.A string constant is a one%dimensional array of characters terminated by a null-0SD0.. ,or example"char nameTU>B0'0,020,030,0Y0,0A0,060,0A0,0SD0E/ ' (DD# 2 (DD( 3 (DD) (DD! Y (DDG A (DDH 6 A (DDI SD (DDR

Here 0SD0 is actually an escape sequence li e 0Sn0. $t is called a null character. <2TE:0SD0 and 0D0 are not same. A'C$$ value of 0SD0 is D and A'C$$ value of 0D0 is !R. The terminating null-0SD0. is important because it is the only way the functions that wor with strings can now where a string ends.A 'tring not terminated by a 0SD0 is not really a string,but merely a collection of characters. as, The string initiali4ed above can also be initiali4ed

char nameTU>C'23YA6AC / Here C inserts the null automatically. 6ow we will loo at pointer assignment to string values, with an example" 87program to print string elements using pointer notation78

main-. B char nameTU>CsruNanaC/ char 7ptr/ ptr>name/ while-7ptr5>0SD0. B printf-C9cC,7ptr./ ptr;;/ E E ptr is incremented to point to the next character in the string.This derives from two facts" Array elements are stored in contiguous memory locations and on incrementing a pointer it points to the immediately next locations of its type. <2TE: printf-. doesn0t print the 0SD0. The 9s is a format specification for printing out a string.

Stan(ar( L"brar% Str"n) F'n!t"ons


:ost commonly used functions are strlen-.,strcpy-., strcat-. and strcmp-.. strlen34: ,or example" char str#T(DU>CchowdaryC/ l>strlen-str#./ printf-CSn length>9dC,l./ $n the call to the function strlen-.,we are passing the base address of the string,and the function inturn returns the length of the string.Fhile calculating the length it doesnot count 0SD0.*utput would be length>R. strcp534: ,or example" char str#T(DU>CchowdaryC/ char str)T(DU/ strcpy-str),str#./ printf-CSn after copying str)>9sC,str)./ *n supplying the base address, strcpy-. goes on copying the source string into the target string till it doesn0t encounter the end of source string. Thus a string gets copied into another,character by character. strcmp34: compares two strings to find out whether they are same or

different.The two strings are compared letter by letter until there is a mismatch or end of one of the strings is reached, whichever occurs first.$f the two strings are identical, strcmp-. returns a value D.$f they are not ,it returns the numeric difference between the A'C$$ values of the first non%matching pair of characters. The 9s is a format specification for printing out a string.

Po"nters An( Str"n)s


Fe cannot assign a string to another,whereas we can assign a char pointer to another char pointer. This is shown with an example" main-. B char str#TU>ChelloC/ char str(T#DU/ char 7s>Cgood morningC/ char 7q/ str(>str#/87error78 q>s/87wor s78 E Also,once a string has been defined it cannot be initiali4ed to another set of characters.3nli e strings, such an operation is perfectly valid with char pointers. &xample" main-. B char str#TU>ChelloC/ char 7>ChelloC/ str#>CbyeC/87error78 p>CbyeC/87wor s78 E T1E const =.+ IFIE6: The eyword const, if present, precedes the data type of a variable. $t specifies that the value of the variable will not change throughout the program. Any attempt to vary the value of variable will result into an error message from compiler. const is usually used to replace [ define d constants. &xample" main-. B float r,a/ const float,1$>).#!/ printf-CSn &nter radius"C./ scanf-C9fC,?r./ a>1$7r7r/ printf-CArea>9fC,a./ E $f a const is placed inside a function its effect would be localised to that function,whereas if it is placed outside

all functions then its effect would be global. 6ET.6<I<G const >+ .ES: A function can return a pointer to a constant string as shown &xample" main-. B const char 7fun-./ const char 7p/ p>fun-./ p>0A0/8error78 printf-CSn9sC,p./

E const char 7 fun-. B return C2ain-.C/ E 'ince the function fun-. is returning a constant string we cannot use the pointer p to modify it. The following operations too would be invalid" -a.main-. non%const -b.main-. expecting cannot assign the return value to a pointer to a string. cannot pass the return value to a function that is a pointer to a non%const string.

$1o D"mens"onal Arra% O- C*ara!ters


*ur example program as s you to type your name.Fhen you do so,it chec s against a master list to see if you are worthy of entry to the palace. &xample" [include Cstring.hC [define ,*36@ # [define 6*T,*36@ D main-. B char masterlistTHUT#DU>BCsruNanaC, CsnehaC, CswathiC, ClavanyaC, CramyaC, C alyaniC E/ int i,flag,a/ char yournameT#DU/ printf-CSn &nter your name"C./ scanf-C9sC,yourname./ flag>6*T,*36@/ for-i>D/i<>G/i;;. B a>strcmp-?masterlistTiUTDU,yourname./ if-a>>D. B

E E if-flag>>6*T,*36@. printf-Csorry,u r a trespasserC./

printf-Cwelcome,u can enter the palaceC./ flag>,*36@/ brea /

*3T13T" &nter your name" eerthi sorry,u r a trespasser &nter your name"sruNana welcome,u can enter the palace. 6ames can be supplied from eyboard as" for-i>D/i<>G/i;;. scanf-C9sC,?masterlistTiUTDU./ while comapring the strings through strcmp-. note that the addresses of strings are being passed to strcmp-.. sruNanaSD snehaSD swathiSD lavanyaSD ramyaSD alyaniSD #DD# #D## #D(# #D)# #D!# #DG# Here #DD#,#D##,....are the base adresses of successive names. ,or example, even though #D bytes are reserved for storing the name CramyaC, it occupies only G bytes. Thus G bytes go waste. +66+? 2F "2I<TE6S T2 ST6I<GS : pointer variable always contains an address. Therefore, if we construct an array of pointers it would contain a number of addresses. Array of pointers can be stored as char 7namesTU>B CsruNanaC, CsnehaC, CswathiC, ClavanyaC, CramyaC, C alyaniC E/ *ne reason to store strings in an array of pointers is to ma e more efficient use of available memory. I9IT+TI2<S 2F +66+? 2F "2I<TE6S T2 ST6I<GS: Fhen we are using a (%@ array of characters we are at liberty to either initiali4e the strings where we are declaring the array or receive the strings using scanf-. function. &xample" main-. B char 7namesTHU/ int i/ for-i>D/i<>G/i;;. B printf-CSn enter nameC./ scanf-C9sC,namesTiU./ 87doesnot wor 78 E E The program doesn0t wor because when we are declaring the array it is containing garbage values. And it would be definitely wrong to send these garbage values to scanf-. as

the addresses where it should the eyboard.

eep the strings received from

Problems
*utput of following" [include main-. B char sTU>C2ende4vous5C/ printf-CSn9dC,7-s;strlen-s.../ E o7p: D

Explanation: Fe are trying to print out the contents of #(th address from the base address of the string. At this address there is a 0SD0, which is automatically stored to mar the end of the string. The A'C$$ value of 0SD0 is D,which is what being printed by printf-.. -(. B printf-G;C,ascimileC./ E o7p: mile main-.

Explanation: when we are passing a string to a function,what gets passed is the base address of string. $n this case what is being passed to printf-. is the base address plus G,i.e address of 0m0 in C,ascimileC. printf-. prints a string from the address it receives, up to the end of the string. -).main-. B

char chT(DU/ int i/ for-i>D/i<#Q/i;;. 7-ch;i.>HI/ 7-ch;i.>0SD0/ printf-CSn9sC,ch./ E o7p" CCCCCCCCCCCCCCCCCCC

Explanation" #Qth location from base address we store a0SD0 to mar the end of string .This is essential, as the compiler has n other way of nowing where the string is terminated. -!.main-. B char strTU>B!R,!R,!R,!R,!R,!R,!R,!R,!R,!RE/ char 7s/ int i/ s>str/ for-i>D/i<>Q/i;;. B if-7s. printf-C9cC,7s./ s;;/ E E

o7p" DDDDDDDDDD Explanation" $n all #D elements of strTU, an integer !R is stored. Fondering whether a char string can hold int0sJ The answer is yes, as !R doesn0t get stored literally in the elements.!R is interpreted as the A'C$$ value of the character to be stored in the

string.The character corresponding to A'C$$ !R happens to be D,which is assigned to all the locations of the string.s, a character pointer ,is assigned to the base address of the string strTU. 6ext,in the if condition,the value at address contained in s is chec ed for truth8falsity. As D represents A'C$$ !R,the condition evaluates to true every time.$rrespective of whether the condition is satisfied or not, s is incremented so that each time it points to the subsequent array element.The entire logic is repeated in for loop, printing out #D 4ero0s in the process. -G.main-. B char str#TU>ChelloC/ char str(>ChelloC/ if-str#>>str(. printf-CSn equalC./ else printf-CSn unequalC./ E o7p" unequal

Explanation" base address of str# ? str( are different. $f we are to compare the contents of two char arrays, we should comapre them on a character by character basis or use strcmp-.. -H.

main-. B int arrT#(U/ printf-CSn 9dCsi4eof-arr../ E

o7p" (! Explanation" The si4eof-. operator gives the si4e of its argument.As arrTU is an integer array of #( elements , saying si4eof-arr. gives us the si4e of this array. &ach int is ( bytes long.Hence the array arrTU engages twice the number of elements i.e

(! bytes. -I.main-. B static char 7sTU>BCiceC, CgreenC, CconeC, CpleaseC E/ static char 77ptrTU>Bs;),s;(,s;#,sE/ char 77p>ptr/ printf-CSn9sC,77;;p./ printf-CSn9sC,7%%7;;p;)./ printf-CSn9sC,7pT%(U;)./ printf-CSn9sC,pT%#UT%#U;#./ E o7p" cone ase reen Explanation" sTU has been declared and initiali4ed as an array of pointers.s gives us the base address of this array.

iceSD #DDD sTDU #DDD !DDH

greenSD #DD! sT#U #DD! !DDR

coneSD #D#D sT(U

pleaseSD #D#G sT)U

#D#D #D#G %%%values of sTDU,sT#U.... !D#D !D#(%%%%address

ptrTDU

ptrT#U

ptrT(U

ptrT)U

!D#( HD(D

!D#D HD(( p

!DDR HD(!

!DDH%%%values at ptrTDU,ptrT#U.. HD(H%%%address values

HD(D ptrTU stores the addresses of the locations where the base addresses of strings comprising sTU have been stored, starting with the last string. ptrTDU stores the address !D#(,which is the address at which base address of string CpleaseC is stored.'imilarly,ptrT#U stores the address !#D# which is where the base address of the string CconeC is stored ,and so on.'ince ptrTU esssentially stores addresses of addresses,each element of it is a pointer to a pointer and has been declared as such using 77. ,inally the base address of ptrTU is assigneed to a pointer to a pointer p. #.77;;p" p is pointed to HD(( ;;p>HD(( 7HD((>!D#D 7!D#D>#D#D 7#D#D>cone

(.7%%7;;p;) p>HD(( ;;p>HD(! 7HD(!>!DDR %%!DDR>!DDH 7!DDH>#DDD #DDD;)>#DD) 7#DD)>0SD0 ).7pT%(U;) p>HD(! 7pT%(U>7-7-p%(.. >7-7-HD(!%(.. >7-7-HD(D.. >7-!D#(.

>7-#D#G. >CpleaseC p;)>7#D#R>0ase0

!.pT%#UT%#U;# >7-pT%#U%#.;# >7-7-p%#.%#.;# p>HD(! 7-HD(!%#.>7-HD((.>!D#D >7-!D#D%#.;# >7-!DDR.;# >CreenC

R. main-. B printf-C9cC,ITCsundaramCU./ E o7p" 0m0 of Cs u n d a r a mC D # ( ) ! G H I

Po"nters An( Str'!t'res


Fe now that the name of an array stands for the address of its 4eroth element.The samething is true of the names of arrays of structure variables.'uppose product is an array variable of structtype.The name product represents the address of its 4eroth element consider the following declaration. struct inventory B char nameT)DU/ int number/ float price/ E productT(U,7ptr/ This statement declares product s an array of two elements, each of the type struct inventory and ptr as a pointer to data obNects of the type struct inventory. The assignment ptr>product/

would assign the address of the 4eroth element of product to ptr.This is,the pointer ptr will now point to productTDU. $ts members can be accessed using the following notation. ptr %%= name ptr%%= number ptr %%= price The symbol %%=is called the arrow operator and is made up of a minus sign and a greater than sign.6ote that ptr%%= is simply another way f wrting productTDU.Fhen the pointer ptr is incremented by one,it is made to point to the next record. i.e,productT#U. Fe could use the notation -7ptr..number to access the member number.The parantheses around 7ptr are necessary because the member operator C.C has a higher precedence than the operator 7 A program to illustrate the use of a structure pointer to manipulate the elements of an array of structures the program highlights all the features discussed above.6ote that the pointer ptr-of type struct invert. is also used as the loop control index in for loops struct invent B char 7nameT(DU/ int number/ float price/ E/ main- . B struct invent productT)U,7ptr/ printf-C$613TSnSnC./ for-ptr>product/ptr lessthan product;)/ptr;;. scannf-C9s9d9fC,ptr%=name,ampercent ptr%=number, ampercent ptr%=price./ printf-CSn *3T13TSnSnC./ ptr>product/ while-ptr lessthan product;). B printf-C9 %(Ds 9Gd 9#D(fSnC,ptr%=name, ptr%=number,ptr%=price./ ptr;;/ E E *utput" $613T Fashing%machine G IGDD &lectric%iron #( )GD Two%in%one I #(GD *3T13T" Fashing%machine &lectric%iron Two%in%one G IGDD.DD #( )GD I #(GD.DD

Fhile using structure pointers, we should ta e care of the precedence of operators. The operators 0%=0, 0.0,-.,TU enNoy higher priority

among the operators.They bind very tightly with thier operands ,or example,given the definition struct B int count/ float 7p/ 7ptr E then the statement ;;ptr%=count/ increments count,not ptr however, 3@@ptr4-AcountB increments ptr first,and then lin s count the statement ptr@@-AcountBincrements ptr first,and then lin s count the statement ptr@@-AcountB is legal and increments ptr after accessing count.The following statements also behave in the similar fashion. Cptr-Ap ,etches whatever p points to Cptr-p@@ $ncrements p after accessing what ever it points to 3Cptr-Ap4@@ $ncrements whatever p points to Cptr@@-Ap $ncrements ptr after accessing whatever it points to. 1assing of a structure as an argument to a function or a function recieves a copy of an entire structure and returns it after wor ing on it.This method is inefficient in terms of both.The execution speed and memory. Fe can overcome this drawbac by passing a pointer to the structure and then using this pointer to wor on the structure members.Consider the following function" 1rintMinvent-item. struct invent 7item/ B printf-C6ame"9sSnC,item%=name./ printf-Cprice"9fSnC,item%=price./ E this function can be called by printMinvent-?product. The ormal argument item recieves the address of the structure product an therefore it must be declared as a pointer of type struct invent,which represents the structure of product.

(uestions On )ointers hrough Structures


#.Can a structure contain a pointer to itself J Ans"Certainly such structures are nown as self referential structures (.Fhat would be the output of the following program J main- . B struct emp B char 7n/ int age/ E struct emp e#>BCdravidC,#()E/ struct emp e(>e#/

strupr-e(.n./ prntf-CSn9sC,e#n./ E Ans" @2AX$@ ).$f the following structure is written to a file usng fwrite- . ,can fread- . read it bac successfully J Ans" 6o,'ince the structure contains a char pointer while writting the structure to the dis using fwrite- . only the value stored in the pointer would get written. Fhen this structure is read bac the address would be read bac but it is quite unli ely that the desired string would be present at this adress in memory. !.Fhat is the output of the following program" main-. B struct a B char chTIU/ char 7str/ E/ static struct a s#>BC6agpurC,CLombayCE/ printf-C9c9cSnC,s#.chTDU,7s#.str./ printf-C9s9sSnC,s#.ch,s#.str./ E *utput" 6 L 6agpur Lombay G.what is the output of the following programJ main-. B struct s# B char 74/ int i/ struct s# 7p/ E/ static struct s# aTU>B BC6agpurC,#,a;#E/ BC2aipurC,(,a;(E/ BOanpurC,),aE E/ struct s# 7ptr>a/ printf-C9s9s9sSnC,aTDU.4,ptr%=4,aT(Up%4./ E H.Fhat is the output of the following programJ main- . B struct node B int data/ struct node 7lin / E/ struct node 7p,7q/ p>malloc-si4eof-struct node../ q>malloc-si4eof-struct node../ printf-C9d9dC,si4eof-p.,si4eof-q../ E 2utput: ((

Inro('!t"on $o Str'!t'res

Arrays can be used to represent a group of data items that belong to same type,such as int or float.However, $f we want to represent a collection of data items of different types using a single name,then we cannot use arrays.At this time,we use structures.'tructure is used to represent a set of attributes,such as studentMname, rollMnumber and mar s.The individual structure elements are referred to as members. Consider a boo database consisting of boo name, author,number of pages and price. Fe can define a structure to hold this information as follows. struct boo Mban B char titleT(DU/ char authorT#GU/ int pages/ float price/ E/ The eyword ]structZ declares a structure to hold the details of four fields,namely title,author,pages and price. These fields are nothing but members of structure elements.&ach member may belong to a different type of data. boo Mban is the name of the structure and is called the structure tag.This will be used to declare variables that have tagZs structure. This declaration has not declared any variable. $t simply describes a format called template to represent information as follows....... struct boo Mban title array of (D charZs author array of #G charZs pages integer price float general declaration of a structure struct tagMname B dataMtype member#/ dataMtype member(/ %%%%%%%%%%%% %%%%%%%%%%%% E we can declare structure variables using the tag name any where in the program.,or example, struct boo Mban , boo Mban #,boo Mban (, boo Mban )/ each one of these variables has ! members as specified by the template.The complete declaration is li e .... struct boo Mban B char titleT(DU/ int authorT#GU/ int pages/ float price/ E/ struct boo Mban boo #,boo (,boo ),boo )/ These members do not occupy any memory until they are

associated with the structure variables such as boo #. $n defining structure we may follow the syntax #.The template is terminated with a semicolon. (.Fhile the entire declaration is considered as a statement, each member is declared independently for its name and type in a separate statement inside the template. ).The tag name such as boo Mban can be used to declare structure variables of its type,later in the program. 6ormally structure definitions appear at the beginning of the program profile,before any variables or functions are defined. They also appear before the main,along with macro definitions such as [define. Fe can assign values to the member of a structure in a no. of ways. The lin between a member and a variable is established using the member operator.Fhich is also nown as dot period or period operator. ,or example, boo #.price is the variable representing the price of boo # and can be treated li e anyother ordinary variable. 'trcpy-boo #.title,CLA'$CC./ boo #.pages>(GD/ Li e any other data type,a structure variable can be initiali4ed. A structure must be declared as static if it is to be initiali4ed inside a function. main-. B static struct/ B int wt/ float ht/ E student >BHD,#RD.IGE/ E we can initiali4e a structure by using different ways. main-. B struct stMrecord/ B int wt/ float ht/ E static struct stMrecord student#>BHD,#ID.IGE/ static struct stMrecord student(>BH),#ID.HGE/ E Another method is to initiali4e a structure variable outside the function li e... struct stMrecord/ B int wt/ float ht/ E student#>BHD,#ID.IGE/

main-. B static struct stMrecord student(>BH),#ID.HGE/ E C language does not permit the initiali4ation of individual structure members within the template. The initiali4ation must be done only in the declaration of the actual variables.

Str'!t'res an( F'n!t"ons


The main philosophy of C language is the use of functions. C supports the passing of structure values as arguments to function. $n this ,the values of a structure can be transferred from one function to another by using ) methods. The first method is to pass each member of the structure as an actual argument of the function call. The actual arguments are then treated independently li e ordinary variables.This method is inefficient when the structure si4e is large. The second method involves passing of copy of entire structure to the called function.Here ,the function is wor ing on a copy of the structure ,so any changes to structure member within the function are not reflected in the original structure -in the calling function..$t is,therefore ,necessary for the function to return the entire structure bac to the calling function. Lut all compilers may not support this method of passing the entire structure as a parameter. The third method employs a concept called pointers to pass the structure as an argument. $n this case,the address location of the structure is passed to the called function. This function can access the entire structure indirectly. This is smiler to the way ,arrays are passed to functions. This method is more efficient as compared to the second approach. The general format of sending a copy of a structure to the called function is" function name-structure variable name. The called function ta es the following form" data%type function name-st%name. struct%type st%name B % % % % % %%%%%%%% return -expression./ E #. The called function must be declared for its type, appropriate to the data type it is expected to ,or example, if it is returning a copy of the entire structure,then it must be declared as struct with an appropriate tag name. (.The structure variable used as the actual argument and the corresponding formal argument in the called function must be of the same struct type. ).The return statement is necessary only if the function is returning some data .The expression may be any simple variable or structure variable or an expression using simple variables. !.Fhen a function returns a structure it must be assigned to a structure of identical type in the calling function.

G.The called function must be declared in the calling function for its type if it is placed after the calling function.

Arra%s W"t* In $*e Str'!t'res


C permits the use of arrays as structure members.we can use single or multidimensional arrays of type int or float. &x" struct mar s B int number/ float subNectT)U/ studentT(U/ E here,the member subNect contains ) elements,subNectTDU, subNectT#U and subNectT(U.These elements can be accessed using appropriate subscripts. ,or example ,the name studentT#U.subNectT(U/ would refer to the mar s obtained in the third subNect by the second student. Fe can use arrays inside the structures. Fe can use single or multidimensional arrays of type int or float.,or example, the following structure declaration is valid. struct mar s B int number/ float subNectT)U/ EstudentT)U/ Here,the member subNect contains ) elements,subNectTDU, subNectT#U and subNectT(U.These elements can be accessed using subscripts li e studentT#U.subNectT(U/would refer to the mar s obtained in the third subNect by the second student. 87Arrays Fithin The 'tructures78 main-. B struct mar s B int subT)U/ int total/ E/ static struct mar s studentT)U>B!G,HI,R#,D,IG,G), HQ,D,GI,)H,I#,DE/ static struct mar s total/ int i,N/ for-i>D/i<>(/i;;. B for-N>D/N<>(/N;;. B studentTiU.total ;> studentTiU.subTNU/ total.subTNU ;>studentTiU.subTNU/ E total.total ;>studentTiU.total/ E printf-C'T3@&6T T*TAL SnSnC./ for-i>D/i<>(/i;;. printf-CstudentT9dU 9dSnC,i;#,studentTiU.total./ printf-C'3LY&CT T*TAL SnSnC./

for-N>D/N<>(/N;;. printf-CsubNect%9d 9dSnC,N;#,total.subTNU./ printf-CSn +rand Total > 9dSnC,total.total./ E *3T13T" 'T3@&6T T*TAL studentT#U #Q) studentT#U #QI studentT#U #H! '3LY&CT T*TAL subNect%# #II subNect%( #GH subNect%) ((# +rand Total >GG!

A(("t"onal Feat'res O- Str'!t'res


The values of structure variables can be assigned to another structure variable of the same type using the assignment operators. $t is not necessary to copy the structure elements piecemeal. #. main-. B struct employee B char nameT#DU/ int age/ float sal/ E/ struct employee e#>BCsanNayC,)D,#DDD.DDE/ struct employee e(,e)/ 87 piecemeal copying78 strcpy-e(.name,e#.name./ e(.age>e#.age/ e(.sal>e#.sal/ 87copying all elements at one time 78 e)>e(/ printf-CSn 9s 9d 9fC,e#.name,e#.age,e#.sal./ printf-CSn9s 9d 9fC,e(.name,e(.age,e(.sal./ printf-CSn9s 9d 9fC,e).name,e).age,e).sal./ E *3T13T" sanNay )D #DDD.DDDD sanNay )D #DDD.DDDD sanNay )D #DDD.DDDD

,or copying arrays we have to copy the contents of the array element by element.This copying of all structure elements at one time has been possible only because the structure elements are stored in contiguous memory locations. (.*ne structure can be nested within another structure.3sing this facility complex data types can be Created.

:ain-. B struct address B char phonenoT#GU/ char cityT)DU/ int pin/ E/ struct emp B char nameTU/ struct address a/ E/ struct emp e>BCsnehaC,CG)#D!HC,CTexasC,GDIE/ printf-CSn name>9s phone>9sC,e.name,e.a.phoneno./ printf-CSn city>9spin>9dC ,e.a.city,e.a.pin./ E *3T13T" name>sneha phone>G)#D!H city>Texas pin>GDI

Po"nters An( Str'!t'res


Fe now that the name of an array stands for the address of its 4eroth element.The samething is true of the names of arrays of structure variables.'uppose product is an array variable of structtype.The name product represents the address of its 4eroth element consider the following declaration. struct inventory B char nameT)DU/ int number/ float price/ E productT(U,7ptr/ This statement declares product s an array of two elements,each of the type struct inventory and ptr as a pointer to data obNects of the type struct inventory. The assignment ptr>product/ would assign the address of the 4eroth element of product to ptr.This is,the pointer ptr will now point to productTDU.$ts members can be accessed using the following notation. ptr %%= name ptr%%= number ptr %%= price The symbol %%=is called the arrow operator and is made up of a minus sign and a greater than sign.6ote that ptr%%= is simply another way f wrting productTDU.Fhen the pointer ptr is incremented by one,it is made to point to the next record. i.e,productT#U.Fe could use the notation -7ptr..number to access the member number.The parantheses around 7ptr are necessary because the member operator C.C has a higher precedence than the operator 7

A program to illustrate the use of a structure pointer to manipulate the elements of an array of structures the program highlights all the features discussed above.6ote that the pointer ptr-of type struct invert. is also used as the loop control index in for loops

Problems In Str'!t'res
typedef struct B int data/ 6*@&1T2 lin / E76*@&1T2/ A typedef defines a new name for a type and in similar cases li e the one shown below you can define a new structure type and a typedef for it at the same time. typedef struct B char nameT(DU/ int age/ Eemp/ typedef struct B int data/ 6*@&1T2 lin / E76*@&1T2/ There is no error in this because a typedef declaration cannot be used until it is defined.$n the given code fragment the typedef declaration is not yet defined at the point where the lin file is declared.To eliminate this problem ,first give the structure a name-Cstruct nodeC..Then declare the lin field as a simple struct node as shown below" typedef struct node B int data/ struct node 7lin / E76*@&1T2/ Another way to eliminate this problem is to disentangle the typedef declaration from the structure definition as struct node B int data/ struct node 7lin / E/ typedef struct node 76*@&1T2/ Another way is to precede the struct declaration with the typedef ,in which case we would use the 6*@&1T2 typedef when declaring the lin field as typedef struct node 76*@&1T2 struct node B int data/ 6*@&1T2 next/ E/

$n this case ,we declare a new typedef name involving struct node even though struct node has not been completely defined yet,this allowed to do. (.void modify-struct emp 7./ struct emp B char nameT(DU/ int age/ E/ main-. B struct emp e>BCsanNayC,!E/ modify- ?e./ printf-CSn 9s9dC,e.name,e.age./ E void modify-struct emp 7p. B strupr-struct emp 7p. p%=age>p%=age;(/ E

Inro('!t"on $o Stora)e Classes


strong class provides information about their location and visibility.The storage class decides the portion of the program within which the variables are recogni4ed. A variables storage class tells us #.where the variables would be stored. (.Fhat will be the initial value of the variable,if the initial value is not specifically assigned. ).Fhat is the scope of the variable i.e., which functions the value of the variable would be available. !.Fhat is the lifetime of the variable, i.e., how long the variable exist. There are ! types of storage classes in C. #.+utomatic (.Static ).External !.6e!ister

A'tomat"!
The auto variables stored in memory $ts default initial value is garbage value.'cope of the variable is with in the function in which it is declared8defined. Lifetime" Till the control remains in the bloc in which the variable is defined. ex#" main-. B auto int x,y/ printf-C9dC St 9dC, x,y./ E *utput" 'ome garbage values we get 't different times of running this program, we can

get different outputs. To examine scope and lifetime of variable -auto. &x" main-. B auto int i>#/ B auto int i>(/ B auto int i>)/ printf-C9d SnC, i./ E printf-C9d SnC, i./ E printf-C9d SnC, i./ E *utput" ) ( #

Stat"!
The static variables are stored in memory.$ts default initial value is Wero.'cope of this variable is local to the variable in which it is defined.Lifetime" value of the variable persists between different function calls. *nce the variable is declared as static, if the control comes bac to the same function again the static variables have the same values they had last time around. &x" main-. B increment-./ increment-./ increment-./ increment-. B static int i>#/ printf-C9d SnC, i./ i>i;#/ E *utput" # ( ) *nce the variableis declared as static, that variable is initiali4ed only oncew though for many function calls. $n the above exampl, for the first function call of increment-., i>#then i># is printed then i value incremented to (. Then for second functioncall, the first statement initiali4ation of i is not executed, o8p is ( then i is incremented to # becomes ),for third function call,again ) gets printed on screen.The advantage of defining the variable as stati is the value of variable can persist for different function calls. The different between a static external variable and a

simple external variable is that the static external variable is available only within the file where it is defined while the simple external variable can be accessed by other files

E+tern
&xternal type of variable is also stored in memory. $ts default initial value is Wero.'cope of the variable is global.Lifetime" As long as the program0s execution doesnt come to an end. &xternal variables are declared outside all functions, hence available to all functions.variables that are both alive and active throughout program are nown as external variables. They are also nown as global variables. &x" int x/ main-. B x>#D/ printf-C9dC, printf-Cx>9d printf-Cx>9d printf-Cx>9d E fun#-. B x>x;#D/ return-x./ E fun(-. B int x/ x>#/ return-x./ E fun)-. B x>x;#D/ return-x./ E *utput" #D x>(D x># x>)D

x./ SnC fun#-../ SnC fun(-../ SnC fun)-../

*nce a variable has been declared as global, any function can use it and change its value. Then ,subseqent functions can reference only that new value. Lecause of this property, we should try to use global variables only for tables or for variables shared between functions when it is inconvenient to pass them as variables. *ther aspect of global variable is that is only visible from the point of declaration to the end of the program. &x"

main-. B y>G/ printf-C9dC, y./ fun#-./ E int y/ fun#-. B y>y;#/ printf-C9dC, y./ E $n main function, y is not defined. 'o the compiler will issue an error message. As global variable are initiali4ed to 4ero in fun#-., y>D hence output is #. $n this above program, the main cannot access the variable y as it declared after main.This problem can be ssolved by declaring the variable with the storage class extern.Ta e above example again it can be modified as main-. B extern int y>G/ 87 declaration 78 printf-C9dC, y./ fun#-./ E int y/ fun-. B y>y;#/ printf-C9dC,y./ E 6ow, no compiler time error coccur as y is declared as extern in main function. The external declaration of y inside the functions informs the compiler that y is declared somewhere else in the program. 6ote that, the external declaration does not allocate storage space for variables. $n case of arrays, the definition should include their si4e as well. ,unctions are extern by default, we declare them without the qualifier extern. ,or functions also memory is allocated when it is defined with its parameters and function body. Xoid print-./ is eqivalent to extern void print-.

Re)"ster
The value of the variables are stored in C13 registers. $ts default initial value is garbage value.$ts scope is local to the bloc in which variable is defined.Lifetime of the variable is till the control remains within the bloc in which the variable is defined. $f the variable is used at many places in a program, it is better to declare variable as register as the value stored in C13 register can always be accessed faster than the one which is stored in memory. As the value of variable is stored in C13 registers, accessing the value of that variable is fast Hence generally loop variables are declared as registers to improve the execution- accessing. speed.

&x"

main-. B register int i/ for-i>#/i<>#D/i;;. printf-CSn 9dC,i./ E

*utput"

# ( ) ! G H I R Q #D 'imetimes eventhough the variable is declared as register, if registers are not available -as the number of register are limited in C13. the variable wor s as if its storage class is auto. Fe cannot use register storage class for all types of variables. &x" register float a/ register float b/ register float c/ All above declarations are wrong because the cpu registers in micro computers are usually #H bit registers and therefore cannot hold a float or double -R bytes. or long -R bytes.. Though above declarations are wrong the compiler doesnot generate any error, it declares the variables a,b,c as auto storage class.

W*"!* $o ,se W*en


#.A variable is declared as static if one wants the value of the variable to be persists between different function calls. (.A variable is declared as register storage class if those variables are used very often in program. ).A variable is declared as external, when that variable is being used by almost all functions in the program. !.&xcept all above conditions, we can declare variables as automatic. However default variable declaration of variable as auto.

,n"ons

As array represent group of data items that belong to the same type. C supports a constructed data type nown as structure and unino, which are methods for pac ing data of different types. These are used to organi4e complex data in more meaninigful way. 3nions are a concept borrowed from structures and therefore follow the same syntax as structures and unions arise in terms of storage. $n structure each member has its own storage location. Fhere as all the members of a union use the same location. Although a union may contain many members of different types,it can handle only one member at a time. Ex: union item B int m/ float x/ char c/ E/ union item code/ The word item is called union tag. The union declaration must end with semicolon. The union contain three members each with a different data type. However, we can use only one of them at a time.This is due to the fact that only one location is allocated for a union variable, irrespective of its si4e. Among all datatypes of variables that are declared in union, the variable type that has maximum si4e is the si4e allocated to union. $n above example, the float has maximum si4e ! bytes. Hence the si4e of union item has ! bytes. To access union member -m8x8c. we have to use dot operator code is the variable i.e declared of type item. 2emember that the members of union themselves are not variables.They dont occupy any memory until they are associated with union variable such as code. $n defining union8structure, we have to note following syntax. #.The template is terminated with semicolon. (.Fhile the entire declaration is considered as a statement, each member is declared independently for its name and type in a seperate statement inside the template. ).The tagname code can be used to declare union variables of its type, later in the program. To access union member, we can use code.m>)IQ/ code.x>IGQ.IH/ printf-C9dC, code.m./ A union creates a storage location that can be used by anyone of its members at a time. Fhen a different members is assigned a new value, the new value supercodes the previous value.3nion may be used in all places where a structure is allowed.

En'merate( Data $%pe

This is one of the user defined datatypes. The use of this datatype is to ma e programs more readable.$t allows you to create your own datatype with predefined values. Though its form is li e that of a structure, the values mentioned within its braces do not indicate variables but infact are constant values that are enum can ta e. S5ntax: enum identifier B value #/ value ( . . . . . value n/ E/ The identifier can be used to declare variables that can have one of the values enclosed within the braces - nown as enumerated constants. After this definition, we can declare variables to be of this 0new0 type as below. &num identifier v#,v(,v).....vn/ The enumerated variables v#,v(,.......vn have only values among value#,value(........valuen The assignments of the following types are valid v#>valueG/ vG>value)/ &x" enum rail B firstclass/ secondclass/ ac E/ enum rail person#,person(/ Here firstclass , secondclass , ac are called enumerators, which are the values that the variable of the type enum rail can ta e. The next statement declares that person#, person( are variables of the type enum rail. These variable cannot ta e values other than firstclass, secondclass and ac. $nternally, these values are treated as integers by compiler. Hence, firstclass is interpreted as value D, secondclass as value# and a as (. we can override these values by saying in the declaration. &num rail B firstclass>(D/ secondclass>)D/ ac>!D/ E/ or any numbers we can assign. The enumerated variables suffer from one minor wea ness. The enumerated values cannot

be used directly in input8output functions li e printf-. and scanf-.. This is because these functions are not smart enough to understand that by (D you mean firstclass or vicevera. Ex: main-. B enum code.mB odd,delete modify, unchanged E/ typedef enum code C*@& C*@& c, d/ c>add/ d>modify/ printf-Cc>9d St d>9dC, c, d./ E *utput" c>D, d>( &xplanation" the enumerated datatype code is declared to be capable of ta ing values odd,delete,modify,unchanged using the typedef statement. Two variables of this type c and d are declared and initiali4ed. Cis assigned the value odd and d, the value modify. The printf-. then prints out the values of c and d. Fhen values are defined for enum, they are interpre% ted as integer values D,#,( etc by default.'o odd is assigned D and delete%#, modify%(. Hence the output is D,(. main-. B enum status B low,medium,highE/ enum status rain/ rain>D/ if-rain>>low. printf-Crain>9dC,rain./ E output" rain>D rain is a variable of the type enum status, which is declared to be able to ta e values low,medium,high.$n an enum, the values are interpreted as D,#,( in that order. Hence assigning D to rain is same as assigning low to rain. The if condition is therefore satisfied ? hence output rain>D.

Inro('!t"on $o PrePro!essors
$6T2*@3CT$*6" The C preprocessor is a program that processes our source program before it is passed to the compiler.This is a capability that does not exist in many other higher level languages. ,&AT32&' *, C 12&12*C&''*2" The C program involves so many stages from the stage of writing C program to the stage of getting it executed. The processors used in the execution of C program are

#.Text &ditor (.1reprocessor ).Compiler !.Lin er

PrePro!essor D"re!t"#es
There are four types of preprocessor directives,these are shown below. 1reprocessor directives are" #. :acro expansion (. ,ile inclusion ). Conditional Compilation !. :iscellaneous directives &V1LA6AT$*6 ,*2 12&12*C&''*2 @$2&CT$X&'" #.9+-62 ED"+<SI2<: consider the example given below [define 311&2 (G main-. B int i/ for-i>#/i<>311&2/i;;. printf-CSn9dC,i./ E from the above example it is nown that instead of writing (G in the for loop we are writing it in the form of 311&2, which is already defined before main-. through the statement, [define 311&2 (G The above statement is called ]macro definition0 or ]macro0. The purpose of this macro in the program is it replaces every occurrence of 311&2 in the program with (G during the time of preprocessing. &xample for macro definition" [define 1$ ).#!#G main-. B float r>H.(G/ float area/ area>1$7r7r/ printf-CSn Area of Circle>9fC,area./ E from the above program 311&2 and 1$ are called ]macro templates0, and the (G and ).#!#G are called their corresponding ]macro expansions0. &xplanation" At the time of compilation of program, before the source code passes to the compiler is examined by the C preprocessor for any macro definitions. Fhen it sees the [define directive, it goes through the entire program in search of the macro templates. Fhere ever it finds one, it replaces the macro template with the appropriate macro expansion. *nly after the completion of this procedure the program handed over to the compiler.

6ote" it needs space between macro template and its macro expansion that is separated by blan s or tabs. A space between [ and define is optional. A macro definition never terminated by semicolon. use of [define in the program ma es easy to read. That is it ma es easy to recogni4e constants. ,or example substituting 1$ for ).#!#G ma es the program to read easier. Here it is easy to recogni4e the constant ).#!#G. but there are many instances where a constant doesn0t reveal its purpose. ,or example the phrase CSx#LT(YC causes the screen to clear. Lut it is easier to understand this in the middle of program when we use CCL&A2'C2&&6C as the macro template ? CSx#LT(YC as the macro expansion. therefore the macro definition for this is [define CL&A2'C2&&6 CSx#LT(YC it shows that where ever CL&A2'C2&&6 appears in the program it would automatically be replaced by CSx#LT(YC before compilation begins.$n short, it is nice to now that it is able to change values of a constant at all places in the program by Nust ma ing a change in the [define directive. Conclusion" thus using [define can produce more efficient and more easily understandable programs. $t is used extensively by C programmers. Some examples of usin! Edefine directi,e: #.A [define directive is mainly a times used to define operators as shown below. [define A6@ ?? [define *2 AA main-. B int f>#,x>!,y>QD/ if--f<G. A6@ -x<>(D *2 y<>!G.. printf-CSn Kour 1C will always wor fineC./ else printf-CSn $n front of the maintenance manC./ E (. A [define directive could be used even to replace a condition, as shown below. [define A6@ ?? [define A2A6+&-a=(G A6@ a<GD. main-. B int a>)D/ if-A2A6+&. printf-Cwithin rangeC./ else printf-Cout of rangeC./ E ). A [define directive could be used to replace even an entire C statement. This is as shown below. [define main-. ,*36@ printf-CThe Kan ee diode virusC./ 3se"

char signature/ if-signature>>0K0. ,*36@ else printf-CsafeC./

E :acros also consists of arguments. 9acros /ith ar!uments: :acros can have arguments same as functions. example below shows how the arguments are used within macros. [define A2&A-x. -).#!7x7x. main-. float r#>H.(G, r(>(.G,a/ a>A2&A-r#./ printf-CSn area of circle is>9fC,a./ a>A2&A-r(./ printf-CSn area of circle>9fC,a./

E $n this program wherever the preprocessor finds phrase A2&A-x. it expands it into the statement -).#!7x7x.. here the x in the macro template A2&A-x. is an argument this one matches the x in the macro expansion -).#!7x7x.. The statement A2&A-r#. in the program causes the variable r# to be substituted for x. Thus the statement A2&A-r#. is equivalent to -).#!7r#7r#. After the passing of source code through the preprocessor, compiler wor s on main-. B float r#>H.(G,r(>(.G,a/ a>).#!7H.(G7H.(G/ printf-CArea of circle>9fSnC,a./ a>).#!7(.G7(.G/ printf-CArea of circle>9fC,a./ E The output of this program after the completion of whole process is as shown below.. Area of circle is>#((.HGH(GD Area of circle>#Q.H(GDDD example (" B [define $'@$+$T-y. -y=>!R ?? y<>GI. main-. char ch/ printf-C&nter any digitC./ scanf-C9cC,?ch./ if-$'@$+$T-ch.. printf-CSn digit is enteredC./ else printf-CSn illegal inputC./

E macros with arguments should consider the following conditions.

#.At the time of defining the macro there should not be blan between macro template and its argument. for example in the above program there should not be blan between A2&A and -x. in the definition. i.e [define A2&A-x. -).#!7x7x. if A2&A -x. is written instead of A2&A-x. it causes to some problems. i.e -x. becomes the part of macro expansion this leads to expand macro as shown below. This statement won0t run. -H.(G. -).#!7H.(G7H.(G. (. The entire macro expansion should enclosed within parentheses. Here is an example for enclosing the macro within parentheses. This shows the problems occurred if macro is not enclosed within the parentheses. [define 'P3A2&-n. -n7n. main-. int N/ N>H!8'P3A2&-!./ printf-CN>9dC,N./

The output for this program we will get as N>H! instead of N>! because in the above program as the macro is not enclosed within the parentheses it is expanded as N>H!8!7!/ which gives output as H!. The second preprocessor directive is ,ile $nclusion (. FI E I<- .SI2<: This directive causes one file to be included in another. The preprocessor command for ,ile $nclusion is [include CfilenameC this command inserts the entire contents of filename into the source code at that point in the program. This ,ile $nclusion preprocessor is used in two cases they are #. $f the program is very large the code is divided into several different files,each containing a set of related functions these ,ile $nclusion preprocessor is used. These files are included at the beginning of main program file. (.functions or macro definitions are needed in many programs commonly. $n such situations these commonly used functions and macro definitions are stored in a file, and that file can be included in every program. This will add all the statements in this file to program which is written. $n programs generally files are included with the extension .h, this extension stands for 0header file0. $t contains statements which when included go to the head of program. There are t/o /a5s to /rite Einclude statement. They are" .

[include CfilenameC [include The difference between these two statements is as shown below. [include Cgoto.cC " This command loo for the file goto.c in the current directory as well as the specified list of directories as mentioned in the include search path which have been setup. [include " This command would loo for the file goto.c in the specified list of directories only. The third type of preprocessor directive is Compilation. ).-2<DITI2<+ -29"I +TI2<: Conditional

This Conditional Compilation is used when the compiler s ip over part of a source code by inserting the processing commands. These processing commands are [ifdef and [endif. The general form of these processing commands is as shown below. [ifdef macro name statement #/ statement (/ statement )/ [endif $f the macro name has been [defined, the bloc of code will be processed as usual otherwise the bloc of code will not processed as usual. ifdef processing command can be used in two cases. They are" #.To Ccomment outC obsolete lines of code. This often occurs that a program is changed at the last minute to satisfy a client. This involves rewriting some part of source code to the client0s satisfaction and delete the old code. Lut if the client again needs the old code it is difficult to rewrite the old code in the place of new code. To overcome this problem the old code can be ept in comments i.e 87 78 combination. Lut if we have already written a comment in the code that about to Ccomment outC. This would mean to end up with nested comments. i.e in C we can0t nest comments. Therefore solution for this is to use conditional compilation as shown below. main-. B [ifdef *OAK statement #/ statement (/ 87 detects virus78 statement )/ statement !/ 87 specific to stone virus 78 [endif statement G/ statement H/ statement I/ E $n the above program the statements #,(,)?! can be compiled

only if the macro *OAK has been defined. $f all these statements have to get compiled it needs to delete the [ifdef and [endif statements. (.[ifdef can be used mostly to ma e the programs portable. i.e. to ma e wor on two totally different computers so that it needs to write a program that wor s on both machines. ,or this it needs to isolate the lines of code that must be different for each machine by mar ing them off with [ifdef. &xample for this is main-. B [ifdef 1CAT code suitable for a 1C8AT [else code suitable for a 1C8VT [endif code common to both the computers E After the compilation of this program it would compile only the code suitable for a 1CJVT and the common code. This occurs because the macro 1CAT has not been defined. For ing of [ifdef % [else % [endif is similar to the ordinary if%else control instruction of C. $n this program if the program wants to un on 1C8AT, it is needed to add the statement [define 1CAT in the program. [ifndef directive can be used in the place of [ifdef in some situations. The [ifndef i.e0if not defined0 wor s exactly opposite to [ifdef. &xample for this is as shown below. main-. B [ifndef 1CAT code suitable for a 1C8VT [else code suitable for a 1C8AT [endif code common to both computers

After compilation of this program it gives the output as code suitable for a 1C8AT and the common code. i.e exactly opposite to the [ifdef statement. [if and [elif @irectives"

The [if directive can be used to test whether an expression evaluates to a non4ero value or not. $f the result of the expression is non4ero, then subsequent lines upto a [else, [elif or [endif are compiled, otherwise they are s ipped. A simple example of [if directive is as shown below. :ain-. B [if T&'T<>G statement #/

statement (/ statement )/ [else statement !/ statement G/ statement H/ [endif

$n the above program if the expression, T&'T<>G evaluates to true then statements #,(,and ( are compiled otherwise statements !,G and H are compiled. $n place of the expression T&'T<>G other expression li e -L&X&L>>H$+H AA L&X&L>>L*F. or A@A1T&2>>C+A can also be used. 6ested conditional compilation is also possible. The example below shows such directives. [if A@A1T&2>>:A code for monochrome adapter [else [if A@A1T&2>>C+A code for colour graphics adapter [else [if A@A1T&2>>&+A code for enhanced graphics adapter [else [if A@A1T&2>X+A code for video graphics array [else code for super graphics array [endif [endif [endif [endif This program also can be made more compact by using another conditional compilation directive called [elif. The same program using this directive can be written as shown below. 3se of [elif in this program reduces the no of end ifs. [if A@A1T&2>>:A code for monochrome adapter [elif A@A1T&2>>C+A code for colour graphics adapter [elif A@A1T&2>>&+A code for enhanced graphics adapter [elif A@A1T&2>>X+A code for video graphics array [else code for super video graphics array [endif The fourth one preprocessor @irectives is :iscellaneous @irectives. !. 9IS-E +<E2.S I6E-TI>ES:

There are two more preprocessor directives are used . They are #.[undef (.[pragma

[undef @irective" This directive is used to undefine the directive if it is already defined. i.e if the statement is already used the directive [define to define the directive to undefine this [undef is used. The [undef command id [undef macro template statement for this is [undef 1CAT this statement causes the definition of 1CAT to be removed from the system. All subsequent [ifdef 1CAT statements would evaluate to false. [pragma @irective" This directive is one special directive that is used to turn on or off certain features. programs vary from one compiler to another. There are certain programs available with :icrosoft C compiler which deal with formatting source listings and placing comments in the obNect file generated by the compiler. Turbo C compiler has the pragma which allows to write assembly language statements in C program.

Difference -et+een he Macros &nd Functions


:acros are li e functions but there is difference between those two . #. $n macro call the preprocessor replaces the macro template with its macro expansion. Fhere as in function call the control is passed to a function along with certain arguments, some functions are performed in the function and a useful value is returned bac from the function. (. :acros ma e the program run faster but increases the program si4e, where as functions ma e the program smaller and compact. i.e if the macro is used hundred times in the program , the macro expansion goes into source code for hundred times which increases the program si4e. otherwise if the function is used hundred times in the program from different places it ta es same amount of space. ). $n the functions while passing the arguments to a function and getting bac the returned value does ta e time and slow down the program. where as in macros this problem wont occurs since they have already been expanded and placed in the source code before compilation. At the conclusion it is came to now that if the macro is simple it ma es a nice shorthand and avoids the overheads associated with function calls. *n the other hand if the program consists of large macro it can be replaced by the function.

Solutions For Some Example )rograms


#. [define @&, main-.

int i>(/ [ifdef @&, printf-Csquare of i>9dC, i7i./ [else printf-i>9dC,i./ [endif E *utput" out put of this program is square of i>! &xplanation" 'ince @&, has been defined, [ifdef @&, evaluates to true, hence square of i is calculated and printed through printf-.. $s it not necessary while defining @&, to use a macro expansion following @&,J 6o, since it is not intend to use the value of the macro expansion anywhere in the program. All that we want is to conditionally compile the program subNect to the condition whether @&, has been defined or not. (. [define 6* [define K&' main-. B int i>G,N/ if-i=G. N>K&'/ else N>6*/ printf-C9dC,N./ E *utput" The compiler gives &rror :essage to the above program. &rror message is &xpression syntax in function main. &xplanation" $n the program the values of K&' and 6* is assigned to the N in the if%else, but what are the values of K&' and 6*J They have only been defined as macros without being given any expansions.Hence the error message. ). [define :&''-m. printf-CmC. main-. B :&''-CLut somewhere in my wic ed miserable past..C./ :&''-Cthere must have been a moment of truth5C./ E *utput" *utput for this program is mm. &xplanation" $n this program @uring processing :&''-CLut...past..C. gets replaced by printf-CmC.. 6aturally, on execution this printf-. prints out m. The same thing happens to the next statement, which also prints out an m. !. [define +*T*6&VTL$6& printf-CSnC.

main-. B printf-Cit0s better to eep your mouth shut..C./ +*T*6&VTL$6&/ printf-C..and have people thin you are a fool..C./ +*T*6&VTL$6&/ printf-C..than to open it and remove all doubt5C./

*utput" The output of this program is it0s better to eep your mouth shut.. ..and have people thin you are a fool.. .. than to open it and remove all doubt5 &xplanation" @uring the processing of this program the processor replaces all occurrences of +*T*6&VTL$6& in main-. with printf-CSnC.. Hence during execution, the three messages are output on different lines. G. [define :&''-m. printf-CmC. [define +*T*6&VTL$6& printf-CSnC./ main-. B :&''-CA galaxy of persons were born on this day..C./ +*T*6&VTL$6&/ :&''-CLut somehow you seem to be the best55C./ E *utput" output of this program is m m &xplanation" The preprocessor replaces both the occurrences of :&'' with printf-CmC.. 'imilarly, +*T*6&VTL$6& is replaced by printf-CSnC.. Thus, when the program is sent for execution, it has been converted to the following form" main-. B printf-CmC./ printf-CSnC./ printf-CmC./

E This would output two ms on different lines. H. [define $'311&2-x. -x=>HG ?? x<>QD. [define $'L*F&2-x. -x=>QI ?? x<>#((. [define $'AL1HA-x. -$'311&2-x.AA $'L*F&2-x.. main-. B char ch>0;0/ if-$'AL1HA-ch.. printf-Cch contains an alphabetC./ else printf-Cch doesn0t contain an alphabetC./ E *utput" The output of this program is ch doesn0t contain an

alphabet &xplanation" The first and second macros have the criteria for chec ing whether their argument x is an upper or a lower case alphabet. These two criteria have been combined in the third macro, $'AL1HA. Thus when the program goes for compilation, the if statement has been converted to the form " if-ch=>HG ?? ch<>QD AA ch=>QI ?? ch<>#((. As ch has been initiali4ed to character ;, the conditions in the if fail and the control rightly passes to the else bloc , from where the output is obtained. I. [define TH$' [define THAT main-. B [ifdef TH$' [ifdef THAT printf-C@efinitions are hard to digestC./ [else printf-CLut once mugged up,hard to forgetC./ [endif E *utput" $t gives as 3nexpected end of file in conditional &xplanation" The macros TH$' and THAT have been correctly defined. The error lies in the imbalance of [ifdef and [endif statements in the program. $nserting another [endif would guarantee the output C@efinitions are hard to digestC. This also goes to show that the [ifdefs can be nested the same way the ordinary if statements can be. R. [define TH$' [define THAT main-. B [ifdef TH$' ?? THAT printf-C@efinitions are hard to digestC./ [else printf-CLut once mugged up, hard to forgetC./ [endif E *utput" output of this program is @efinitions are hard to digest &xplanation" Logical operators are perfectly acceptable in [ifdef statements. 'ince both TH$' and THAT are defined, the preprocessor allows only the first printf-. to go for compilation, which gets executed and we get our output. Q. [define :&A6-a,b,c,d,e.-a;bcd;e.8G

main-. B int a,b,c,d,e,m/ a>#/ b>(/ c>)/ d>!/ e>G/ m>:&A6-a,b,c,d,e./ printf-C:ean of the five numbers is>9dC./ E *utput" The output of this program is The mean of the five numbers is>) &xplanation" The preprocessor substitutes the macro :&A6 with its explanation. This expansion is the formula to calculate the average of G numbers. Fith the values of G numbers in the program, the result turns out to be ), Fhich then gets printed out through printf-.. #D. [define C3L&-x. -x7x7x. main-. B int a/ a>(I8C3L&-)./ printf-C9dC,a./ E *utput" The output of this program is #. &xplanation" The macro C3L&-x. is defined to give the cube of its argument. $n the program, the preprocessor replaces C3L&-). by -)7)7). and then sends the program for compilation. The calculations process is as shown below. a>(I8-)7)7). a>(I8(I a># ##.[define C3L&-x. -x7x7x. main-. B int a,b/ b>)/ a>C3L&-b;;.8b;;/ printf-Ca>9d b>9dC,a,b./ E *utput" The output of this program is a>Q b>I &xplanation" $n this program the argument of the macro C3L&-x. is made to be b;;. The preprocessor puts the macro expansions in place of the macro templates used in the program, so that the compiler reaches to a>-b;; 7b;; 7b;;.8b;; As ;; succeeds b, first the value of a is derived using the initial value of b-i.e. ).,after which, the ;;does its

Nob on b. Hence -)7)7).8), i.e. Q gets stored in a. 'ince the b;; is encountered four times in the program, b is incremented four times, results the final value of b as I. Thus a stores Q and b as I. #(.[define C3L&-x. -x7x7x. main-. B int a,b>)/ a>C3L&-;;b.8;;b/ printf-Ca>9d b>9dC,a,b./ E *utput" the output for this program is a>!Q b>I &xplanation" $n this program the macro C3L&-x. is expanded to give the cube of its argument. $n the program, the argument is ta en to be -;;b., having initiali4ed b to ) at the outset. The preprocessor, before sending the program for compilation, converts the statement containing the macro to" a>-;;b7;;b7;;b.8;;b The unary operator ;; has higher priority than that of the binary operator 7 and 8. Therefore at first the multiple incrementation of b ta e place. As ;;b occurs four times in the statement, b is incremented four times. Thus, b will has the value I. This is used to calculate the result as" a>-I7I7I.8I a>)!)8I a>!Q #). [define C*6@-a=>HG ?? a<>QD. main-. B char a>020/ if-C*6@. printf-C311&2 CA'&C./ else printf-CL*F&2 CA'&C./ E *utput" This program gives the output as 311&2CA'& &xplanation" Fhen ]20 is stored in the variable a, the A'CC$ value of 2 is stored in a as R(. 'o a contains the value R( in it. The criteria for the character in a being an upper case alphabet is defined in the macro C*6@. @uring preprocessing, in the if statement, the C*6@ is replaced by -a=>HG ?? a<>QD.. 'ince a contains R( the condition is satisfied and gives the output as 311&2 CA'& from this example it is nown that this macro is without any argument. Hence it will wor only for a variable called a. $f this variable a is replaced by the another variable b in the declaration statement, the error message it gives as ]variable a not defined0. #!. [define C*6@-a. a=>HG ?? a<>QD main-. B char ch>020/

if-C*6@-ch.. printf-Cch is in upper caseC./ else printf-Cch is in lower caseC./ E *utput" ch is in upper case &xplanation" $n the program an argument to the macro C*6@-a. is provided. 'o, during processing the if statement becomes" if-ch=>HG ?? ch<>QD. 'ince ch is stated to be capital ]20 in the program, the output comes as ]ch is in upper case0.

File

anagement

Inro('!t"on
There are numerous library functions available for $8* . These are categori4ed into three" a.-onsole I72 Functions ,unctions to receive input from eyboard and write output to X@3. b.Dis: I72 Functions ,unctions to perform $8* operations on a floppy dis or hard dis . c.1ort $8* ,unctions% ,unctions to perform $8* operations on various ports.

De-"n"n) An( Open"n) A F"le


$f we want to store data in a file in the secondary memory, we must specify certain things about the file , to the operating system. They include" #.,ile name. (.@ata 'tructure. ).1urpose. ,ile name is a string of characters that ma e up valid filename for the operating system. $t may contain two parts ,a primary name and an operational period with the extension.@ata structure of a file is defined as ,$L& in the library of standard $8* function definitions. Therefore , all files should be declared as type ,$L& before they are used. ,$L& is defined data type .Fhen we open a file , we must specify what we want to do with the file . ,or example , we may write data to the file or read the already existing data. ,ollowing is the general format for declaring and opening a file" ,$L& 7fp/ fp>fopen-CfilenameC,CmodeC./

The first statement declares the variable fp as a Cpointer to the data type ,$L&C. As stated earlier, ,$L& is a structure that is defined in the $8* library. The second statement opens the file named filename and assigns an identifier to the ,$L& type fp .This pointer which contains all the information about the file is subsequently used as a communication lin between the system and the program. The second statement also specifies the purpose of opening this file .The :ode does the Nob. :ode can be one of the following"

ode "peration Type 6r6 5earches File . If the file e7ists loads it into memory and sets up a pointer which points to the first character in it , if file doesn8t e7ists it returns null. "perations possible 9 :eading from a file. 5earches File . If the file e7ists its contents are overwritten .If file doesn8t e7ists new file is created .:eturns null if unable to open a file. "perations possible 9 /riting to a file. 5earches File . If the file e7ists loads it into memory and sets up a pointer to point the first character .If file doesn8t e7ists new file is created .:eturns null if unable to open a file. "perations possible 9 4ppending new contents at the end of file. 5earches File .If it e7ists,loads it into memory sets up a pointer which points to the first character in it. If does not e7ist it returns -;11. "perations possible 9 reading,writing,modifying e7isting contents. 5earches File . If the file e7ists its contents are destroyed .If file doesn8t e7ists new file is created .:eturns null if unable to open a file. 5earches File . If the file e7ists loads in to memory and sets up a pointer which points to first of a file. If file doesn8t e7ists new file is created .:eturns null if unable to open a file. "perations possible 9 /riting to a file.

6w6

6a6

6r)6

6w)6

6a)6

Clos"n) A F"le 3 F"le F'n!t"ons


Fhen we have finished all operations the file must be closed . This ensures that all outstanding information associated with the file is flushed out from the buffers and all lin s to the file are bro en .$t also prevents accidental misuse of data. The $8* library supports a function to do this. $t ta es following form" fclose-file%pointer./

The !etc34 and putc34 Functions: The simplest fie $8* functions are getc-. ? putc-.. These are analogous to getchar and putchar-. functions and handle one character at a time.Assume that a file that is opened with file pointer fp#. Then , the statement putc-c,fp#./ writes the character contained in the character variable to the file associated with ,$L& pointer fp. 'imilerly , getc is used to read a character from a file has been opened in read mode. ,or example , the statement c>getc-fp(./ would read a character from the file whose pointer is fp(. The file pointer moves by one character position for every operation of getc or putc. The getc will return am end of file mar er &*, , when end of file has been reached. Therefore the reading should be terminated when &*, is encountered. 88 As a practical use of these character $8* functions we can copy the contents of one file into another. This program ta es text file and copies then into another text file , character by character. 88 [includeCstdio.hC main-. B ,$L& 7fs,7fp/ char ch/ fs>fopen-Cpr#.cC,CrC./ if-fs>>63LL. B puts-Ccannot open source fileC./ exit-./ E ft>fopen-Cpr(.cC,CwC./ if-ft>>63LL. B puts-Ccannot open target fileC./ fclose-fs./ exit-./ E while-#. B ch>fgetc-fs./ if-ch>>&*,. brea / else fputc-ch,ft./ E fclose-fs./ fclose-ft./ E The !et/34 and put/34 Functions: The getw an putw functions are integer oriented functions. These are analogous to getc and putc functions and are used to read and write integer values .These functions would be useful to deal with only integer data. The

general forms of getw , putw are" putw-integer,fp./ getw-fp./ The f!ets34 and fputs34 functions: ,or many purposes , character $8* is Nust what is needed . However , in some situations the usage of functions which read or write entire strings might turn out to be more efficient.2eading or Friting strings of characters from and to files is as easy as reading and writing individual characters .

C4T.<":= 2igh level , Te7t , ;nformatted Character I>"

F;-CTI"-5 <etc?@,putc?@,fgetc?@,fputc?@. 2ere getc?@ and putc?@ are macros where as fgetc?@ and fputc?@ are their function versions.

2igh level, Te7t , ;nformatted 5tring Fgets?@,fputs?@ I>" 2igh level, Te7t , -o standerd I>" 1ibrary Functions ;nformatted int I>" 2igh level, Te7t , ;nformatted float I>" -o standerd I>" 1ibrary Functions

Sol#e( Problems
14 main-. B static char strTU>CAcademyC/ printf-C9s 8n 9sC, str,CAcademyC./ E 2.T".T: Academy Academy Explanation: 6ame of the string-str. yields the base address of the string. Fhen this base address is passed to printf-. it prints out each character in the string till it encounters ]8DZ sitting at the end of the string.A string written in double quotes also gives the base address of the string. (. main-. B float a>).#!/

printf-C8n printf-C8n printf-C8n printf-C8n printf-C8n

a>9fC,a./ a>9H.(fC,a./ a>9%H.(fC,a./ a>9H.#fC,a./ a>9H.DfC,a./

2.T".T" a>).#!DDDD a> ).#! a>).#! a> ).# a> )

88default a float is printed with H decimals.

Explanation: The number that preceeds the f is an optional specifier , which governs how exactly the variable is to be printed . H.( specifies that the field width i.e., total number of columns that the value occupies on the screen ,should be H , and that the value should have two digits after decimal point. ). main-. B printf-C9(Ds printf-C9(Ds printf-C9(Ds printf-C9(Ds printf-C9(Ds E

SnC, Cshort legC./ SnC, Clong legC./ SnC, Cdeep fine legC./ SnC, Cbac ward short legC./ SnC,legs all the same5C./

2.T".T"

short leg long leg deep fine leg bac ward short leg legs all the same5

Explanation: *3T13T" Hello Hello Hi Hillo Explanation: The escape sequence ]SnZ called newline , ta es the cursor to the beginning of the newline. A ]SrZ on the other hand , ta es the cursor to the beginning of the same line in which the cursor is currently present.The first letters of the Hello are replaced by Hi and we get the output as CHilloC. G. main-. B printf-C HelloSbSbSbSbSbC./ printf-CHi5SbSbSbLyeC./ E 2.T".T" Lyelo

Explanation: The escape sequence 0Sb0 stands for bac space , which ta es the cursor to the previous character.$n the first printf-., CHelloC is printed, ,ollowing which the cursor is positioned after 0o0 .6ow the G bac apaces ta e the cursor to the letter 0H0 of CHelloC. $n the way finally the output becomes Lyelo. H. main-. B printf-C$ St am St a St boyC./ E 2.T".T" The message is printed with spaces inserted whenever the escape sequence 0St0 occurred. I. [include Cstdio.h C main-. B static char strTU>CSn $n the country of sna e charmers......C/ char 7s/ s>str/ while-7s. B putch-7s./ s;;/ E printf-CSnC./ s>str/ while-7s. B putchar-7s./ s;;/ E E 2.T".T" $n the country of sna e charmers...... $n the country of sna e charmers...... Explanation: putch-. is an unformatted console $8* function , whereas putchar-. is a macro.However ,their wor ing is same. R. [include Cstdio.hC main-. B char ch/ int i/ printf-C&nter any number......C./ scanf-C9dC,?i./ fflush-stdin./ printf-C&nter any character......C./ scanf-C9cC,?ch./ printf-C8n 9d 9cC, i,ch./ E

2.T".T" &nter any number......( &nter any character......a (a. Explanation: fflush-stdin. %%= this statement empties the buffer before prompting us to enter a character. Q. [include Cstdio.hC main-. B char str#T)DU,str(T)DU/ printf-C&nter a 'entenceSn C./ scanf-C9sC,str#./ printf-C9sC,str#./ fflush-stdin./ printf-C&nter a 'entenceSnC./ gets-str(./ printf-C9sC,str(./ E 2.T".T" &nter a 'entence" 6othing 'ucceeds li e success 6othing &nter a 'entence" 6othing 'ucceeds li e success 6othing 'ucceeds li e success #D.

main-. B char nameT(DU,snameT(DU / puts-C&nter your name and surnameSnC./ gets-name,sname./ puts-name,sname./ printf-C9s9sC,name,sname./ E

2.T".T" &nter your name and surname" Yaspal Lhatti Yaspal Lhatti Yaspal Lhatti fG_`[_fdfg Explanation: gets-. and puts-. cannot ta e more than one argument at a time. Though no error message is displayed , what ever is typed before hitting enter is accepted by the first argument nameTU , and the second argument is simply ignored. ##. main-. B ,$L& 7fp/

fp>fopen-CT2A$L.cC,CrC./ fclose-fp ./ E 2.T".T" &rror"3ndefined symbol ,$L& in the function main. Explanation: ,$L& is a structure that is defined in the header file Cstdio.hC.Hence , for using this stucture , including Cstdio.hC is a must. #(. [includeCstdio.hC main-. B char strT(DU/ ,$L& 7fp/ fp>fopen-strcpy-str,C&6+$6&.cC.,CwC./ close-fp./ E 2.T".T" 6o *utput

Explanation: Fe must open the file in the proper mode li e fopen-C&6+$6&.cC,CwC./ #). [includeCstdio.hC main-. B ,$L& 7fp/ char strTRDU/ 87 T2$AL.c contains only one line $ts a round a round , round , round world578 fp>fopen-CT2$AL.C C ,CrC./ while-fgets-str,RD,fp.5>&*,. puts-str./ E 2.T".T" $ts a round a round $ts a round a round ... . ......... . ... . ......... . ... . ......... . , round , round world5 , round , round world5 .......... ......... .......... ......... .......... .........

Explanation: $n the while loop , fgets-. reads a string of RD characters from the file indicated by fp , and returns a pointer to the string it read. $f it fails to read astring, as would be the case when the end of file is reached, it returns a 63LL , not &*,. Hence , we must compare the returning gets-. with 63LL and not &*, aa the letter never going to be returned. Thus the loop is an infinite loop. #!. [includeCstdio.hC main-.

,$L& 7fp/ char c/ fp>fopen-CT2K.cC,CrC./ if-fp>63LL. B puts-Ccannot open the fileC./ exit-#./ E while--c>getc-fp..5>&*,. putch-c./ fclose-fp./

E a.6ormal &xecution b. &rror message, 63LL pointer assignment. c.Cannot open the file. d.6one 2.T".T" b &rror message " 6ull pointer assignment. Explanation: $n the above program the if condition ,instead of comparing fp and 63LL , what the single > does is assign 63LL to fp.2eplacing > with the comparision operatoe > > would eliminate the bug. #G. [includeCstdio.hC main-. B ,$L& 7fp,7fs,7ft/ fp>fopen-CA.cC,CrC./ fs>fopen-CL.cC,CrC./ ft>fopen-CC.cC,CrC./ fclose-fp,ft,fs./ E a.&rror b.6o *utput c. ,ilename is printed d.6one 2.T".T" b

6o *utput. Explanation: The fclose function can close only one file at a time. 'o after ta ing fs, the first argument in line it pain no attention to the remaining two. The CA.cC gets closed while files CL.cC , CC.cC remain open. ,or closing these three files , we have to call fclose for ) times. $f we want to close all files in one call then fcloseall-. function is called.This function closes all the files open , except the standerd files li e stdin,stdout etc. #H. [includeCstdio.hC main-. B char nameT(DU,name#T(DU/

int age,age#/ printf-C&nter name and AgeSnC./ scanf-C9s 9dC,name,?age./ printf-C &nter name and ageSnC./ fscanf-stdin,C9s 9dC,name,?age#./ fprintf-stdout,C9s 9dC, name#, age#./ E 2.T".T" &nter name and age" 2aN #R 2aN #R &nter name and age" sonia (# sonia (#

Explanation: fscanf-. , li e scanf-. is used for formatted reading of data . The only difference is that the former ta es additional argument that of a file pointer . This pointer indicates to the fscanf-. from where the datHa is to be read , whereas scanf-. is capable of reading data only from the eyboard . 'tdin stands for standerd input device i.e from the eyboard . 'tdin stands for standerd input device i.e., from the eyboard . 'imilerly fprintf-. which ta es argument stdout standerd output device which is X@3. #I. [includeCstdio.hC main-. B char nameT(DU>CsandeepC/ int salary>#GDD/ printf-C9s9dSnC,name,salary./ fprintf-stdout,C9s9dC,name,salary./ E 2.T".T sandeep #GDD #R. [includeCstdio.hC main-. B static char strTU>CtripletC/ char 7s/ s>str/ while-7s. B putc-7s,stdout./ fputchar-7s. printf-C9cSnC,7s./ s;;/ E E 2.T".T: ttt sandeep #GDD

rrr iii ppp lll eee ttt #Q.87this program is stored as a file called prob.c78 main-arg,argv. int argc/ char 7argvTU/ B printf-C9dSnC,argc./ printf-C9sC,argvTDU./ E 2.T".T: # c"Sprob.exe argc%=number of arguments.'ince the only program name. argvTU%=vector of arguments.'ince argvTDUU prints filename. (D. main-. B char ch>Z4Z/ static char,strTU>C4ebraC/ putc-ch,stdprn./ fprintf-stdprn,C9sC,str./ fwrite-str,G,#,stdprn./ fputs-str,stdprn./ E -a.44444 -b.4444 -c.4WebraWebraWebra -d.none. 2.T".T:4 WebraWebraWebra -appears on the printer. this program assumes to have printer attached to it. stdprn-. is standard printer device. (#. [includeCstdio.hC main-. B struct a B char cityT#DU/ int pin/ E/ static struct a b>BCudaipurC,(DE/ static char cTU>CbangloreC/ ,$L& 7fp/ fp>fopen-CtrailC,CwbC./ fwrite-?b,si4eof-b.,#,fp./ fwrite-c,Q,#,fp./ E 2.T".T: no output on the screen this highlights the fact that fwrite-. is not only capable of writing structures,but strings as well.All u have to provide to it is base address of data to be written ,the number of bytes to be written ,number of timesit is to be written and file to which it is written.

((. The requirement is that the program should receive a ey from eyboard.however the ey that is hit should not appear on the screen.which of the following functions would u useJ -a.getch-. -b.getche-. -c.getchar-. -d.fgetchar-. 2.T".T: -a. 7getch-. is the only function that doesnot echo the typed character.7getche-. and fgetchar-. as well as the macro getchar-. will print the typed character.7getchar and fgetchar-. suffer from one more restriction while using them,having entered a character,it has to be followed by hitting enter ey. (). which of the following function is most appropriate for storing numbers in a file(. -a.putc-. -b.fprintf-. -c.fwrite-. 2.T".T:- c . putc-.,fprintf-. are text mode functions .$n text mode numbers are stored as strings.*nthe other hand fwrite-. is a binary mode function. (!. which of the following functions is more versatile for positioning the file pointer in a fileJ -a.rewind-. -b.fsee -. -c.ftell-. 2.T".T: fsee -. fsee -. allows us to position the file pointer at the beginning of the file,at the end of the file or at anyother intermediate position which we specify. (G. which of the following functions are ideally suitable for reading the contents of file record by recordJ -a.getc-. -b.gets-. -c.fread-. -d.fgets-. 2.T".T: - c . 7getc-. can read only one character at a time from a file. +ets-. accepts a string from the eyboard and not from the file. ,gets-.would certainly allow us to read as amny bytes as we specify.

Ran(om A!!ess F"les


2andom access to files are required when we want to access only particular part of a file instead of reading and writing data sequentially.This can be achieved by using the functions li e " fsee ,ftell, rewind. Ftell: #.This function is used to find the current position of a file. (.$t ta es file pointer as an argument. ).$t returns a number of type long. n>ftell-fp./ where fp is a file pointer !.This ftell is used to save the current position of a file which can be used for later use. G.Here n returns the relative position of a file in bytes i.e., relative offset. This means that n bytes have already been read or written. 6e/ind: #.$t ta es the file pointer as an argument and resets the position to the start of a file. (. rewind-fp. n>ftell-fp. The above two statements result the value of n to be 4ero, since the rewind function has set the filepointer to start of the file,where first byte is set to D. ).rewind-fp. function is used to reading and writing afile more than once without having to open and close a file. !.Fhen a file is opened for reading and writing rewind is done implicitly. Fsee:: #.This function is used to move the file position to a desired location within the file. fsee -fileptr,offset,position. fileptr is pointer to the file concerned offset is a number or variable of type long .$t specifies the no.of positions-bytes. to be moved from the location specified by position.

1osition is an integer number.$t ta es one of the three values. Xlaue D # ( :eaning beginning of the file. current postion. end of file.

).The offset may be positive or negative .$f positive move forwards else move bac wards. !.&xamples on ,see " fsee -fp,DL,D. %%%= +o to the beginning. fsee -fp,DL,#. %%%= 'tay at the current position. fsee -fp,DL,(. %%%= +oto the end of the file,past last character of file. fsee -fp,m,D. %%%= :ove to the -m;#.th byte in the file. fsee -fp,m,#. %%%= +o forward by m bytes. fsee -fp,m,%#. %%%= +o bac wards by m bytes from current position. fsee -fp,%m,(. %%%= +o bac wards by m bytes from end of file. *pening a file under 2andom access" fp>fopen-C2andomC,CwC.

Comman( L"ne ar)'ments


Definition: $t is a parameter supplied to a program when the program is invo ed.These are the arguments passed to the main at commandprompt. Explanation: main-. function in 0c0 ta es two arguments called argc,argv. The information contained in the command arguments ,when main is called up by the stream. argc" The variable argc is an argument counter that coumts the number of arguments on the command line. argv" The argv is an argument vector and represents an array of character pointers that point to the command line arguments.The si4e of array will be equal to argc. &x" c"S= program x%file y%file here argc>). argvTDU> program. argvT#U>x%file. argvT(U>y%file. i.e.., here argvTDU contains the base CprogramC argvT#U contains the base Cx%fileC argvT(U contains the base Cy%fileC Therefore arguments that we pass to

address of string address of string address of string main at command

prompt are command line arguments. +d,anta!es of command line ar!uments: #.There is no need to recompile the program everytime we want to use this utillity.$t can be executed at command prompt. (.*nce executable file is created nobody with malicious intention can tamper with your source code program. ).Fe can pass source file name and target file name to main-., and utillise them in main-..

&'est"ons An( Ans1ers


#.$n the code given below [ include Cstdio.hC main- . B ,$L& 7fp/ fp>fopen-CtrailC, CrC./ E fp points to.. a. The first character in the file b. A structure which contains a char pointer which points to first character in the file. c. The name of the file. d. 6one of the above. Ans"L (.1oint out the error ,if any in the following program" [ include Cstdio.hC main- . B unsigned char/ ,$L& 7fp/ fp>fopen-CiegC,r./ while--ch>getc-fp..5>&*,. printf-C9cC,ch./ fclose-fp./ E 'olution"&*, has been defined as [define &*, %# in the file Cstdio.hC and an unsigned char ranges from the file it cannot be accomodated in ch.Therefore solution is to declare ch as int. ).1oint out the error,if any in the following program" [ include Cstdio.hC main- . B unsigned char / ,$L& 7fp/ fp>fopen-CiegC,r./ if-5fp. B printf-Cunable to open fileC./

exit- ./ E fclose-fp./ E solution" no error. !.$f a file contains the line C$ am aboySrSnC then on reading this line into the array str using fgets- ..Fhat would str containJ a. b. c. d. C$ C$ C$ C$ am am am am a a a a boy boy boy boy SrSnSoC SrSoC SnSoC C

ans"C G.point out the error in the following program" [ include Cstdio.hC main- . B,$L& 7fp/ fp>fopen-CtrialC,r./ fsee -fp,(D,'&&OM'&T./ fclose-fp./ E 'olution" $nstead of using (D using (DL since fsee - . needs a long offset value. H.To print out a and b given below ,which printf- . statement would you useJ float a>).#! double b>).#! a. printf-C9f9fC, a,b./ b. printf-C9lf9fC, a,b./ c.printf-C9lf9lfC, a,b./ d.printf-C9f9lfC, a,b./ Ans"A,$t is possible to print double using 9f. I.To scan out a and b given below ,which scanf- . statement would you useJ float a>).#! double b>).#! a. printf-C9f9fC, ?a,?b./ b. printf-C9lf9fC, ?a,?b./ c.printf-C9lf9lfC, ?a,?b./ d.printf-C9f9lfC, ?a,?b./ Ans"C R.1oint out error if any in the in the following program" [ include Cstdio.hC main- . B ,$L& 7fp/ char strTRDU/ fp> fopen-CiegC,CrC./ while-5feof-fp.. B fgets-str,RD,fp./

puts-str. E fclose-fp. E solution" The last line from the file CtrailC would be read twice .To avoid this use" while-fgets-str,RD,fp.5>63LL. puts-str./ Q.point out the error in the following program" [ include Cstdio.hC main- . B char ch/ int i/ scanf-C9cC,?c./ scanf-C9dC,?ch./ printf-C9c9dC,ch,i./ E solution" Kou would not get achance to supply a character for the second scanf- . statement .solution is to preceede the second scanf- . with the following statement fflush-stdin./ This would flush out the enter hit for the previous scanf- . to be flushed out from the inputstream ,i.e., eyboard. #D.Fhat would be the output of the following programJ main- . B printf-CSn999C./ E Ans"99 ##.point out the error if any ,in the following program J [ include Cstdio.hC main- . B unsigned char / ,$L& 7fp/ fp>fopen-Cc"StcSiegC,CwC./ if-5fp. exit- ./ fclose-fp./ E Ans" The path of filename should be written as c"SStcSSieg #(.Fhat would be the output of the following program " main- . B int n>G/ printf-CSnn>97dC,n,n./ E a. 2untime error b. compile time error c. G d. some garbage value. Ans"G The 7 in the printf- . indicates the width . #).Can we specify variable field width in scanf- . format string J Ans" 6o.A 7 in scanf- . format string after a 9 sign is

used for suppression of assignment .That is ,the current input field is scanned but not stored #!.To ta le a double value we use 9f in printf- . .Fhat is that we use in scanf- . a. 9f b. 9d c.9ld d.9lf Ans"@ #!.According to Ansic specification which is the correct way of declaring main- . when it recieves command line arguments" a. main-int argc,char 7argvT U . b. main-argc,argv. int argc,char 7argvT U c.main- . B int argc/ char 7argvTU/ E d. 6one Ans"A #G.Fhat would be the output of the following programJ 87sample.c78 main- int argc, char 7 argv. B argc> argc%-argc%#./ printf-C9sC,argvTargc%#U./ E Ans" c"Ssample.exe

#H.$n the following program -myprog. is run from command line as myprog # ( ) what would be the output J 87consider lessthan sybolically78 main- int argc,char 7argvT U. B int i/ for-i>D/ i lessthan argc/i;;. printf-C9sC,argvTiU./ E Ans" c"Smyprog.exe # ( ) #I.$n the following program -myprog. is run from command line as myprog # ( ) what would be the output J main- int argc,char 7argvT U. B int i/ i> argvT#U;argvT(U;argvT)U/ printf-C9dC,i./ E a. #() b. H c.error d. C#()C Ans" C #R.$n the following program -myprog. is run from command

line as myprog # ( ) what would be the output J main- int argc,char 7argvT U. B int i,N>D/ for-i>D/ i lessthan Margc/i;;. N>N;atoi-argvTiU./ printf-C9dC,N./ b.H c.error d.C#()C

a. #() Ans"L

#Q.$f the following program is run under command line arguments as myprog Nan feb march Fhat would be the output" [ include Cdos.hC main- . B fun- ./ E fun- . B int i/ for-i>D/i lessthan Margc/i;;. printf-C9sC,MargvTiU./ E Ans"C"8:K12*+.&V& Nan feb mar (D..$n the following program -myprog. is present in the directory c"8bc8tucs then what would be its outputJ main- int argc,char 7argvT U. B E printf-C9sC,argvTDU./

a. :K12*+ b. c"8bc8tucs8myprog c.error d.c"8bc8tucs Ans"L (#.Fhich of the following is true about argvJ a. $t is an array of character pointers b. $t is an pointer to an array character pointers c.$t is an array of strings d.6one Ans"A ((.f the following program is run under command line arguments as myprog Nan feb march Fhat would be the output" B main- int argc,char 7argvT U.

while-int argc,char 7argvT U. printf-C9sC,7;;argv./ E a. Nan feb mar b. myprog Nan feb mar

c.Loth d. none Ans"L

Ran(om A!!ess F"les


#.Fhich $8* function is used to receive input from eyboard and write output to X@3 a.@is $8* b.port $8* c. Console $8* d. 6one Ans" C

(.Fhich $8* function have been categorised into formatted and un formatted $8o functions a. @is Ans" C $8* b.port $8* c. Console $8* d. 6one

).Fhich of the following is formatted $8o functions used for input a. gets-. Ans"L !.Fhich of the following is formatted $8o functions used for input a. getch-. Ans"C G.Fhich of the following functions is used to output a single character a. puts- . Ans"@ H.Fhich of the following is used as unsigned character format specifier a. 9s Ans"L I.$dentify the following is used as unsigned character format specifier a.9d Ans"C R.9* a.*rganised format specifier b.9$ c. both a and b d.none b. 9c c.9uc d.9d b.putch- . c.putchar-. d. b and c b. getche- . c. both a and b d. 6one b. scanf- . c. both a and b d. 6one

b. signed octal format specifier c. 3nsigned *ctal format specifier d. b and c Ans"@ Q.$dentify the long signed format specifier a. 9lu b. Ans"C #D.9#Dd would print the output exactly as" a. print the variable as a decimal integer in field of #D columns. b.print the output. c.print the variable as a decimal integer in field of #D columns as right Nustified. d. print the variable as a decimal integer in field of #D columns as left Nustified. Ans"C ##.9%Gd will print output with a. output padded with blan s in right. b.output padded with blan s in between. c. output padded with blan s in left. d. 6one Ans"A #(.main-. B char f#T U>CiegC/ char f(T U>CscioC/ printf-C9GsC,f#./ printf-9%GsC,f(./ E Here the output in first and second printf statements would start printed rom which column of outputJ a. !,( Ans"L Explanation: $n first printf is right Nustified ,padded with blan s on left.$n second printf is left Nustified ,padded with blan s on 2ight. #).Fhich of the following are escape sequences a. Sn Ans"@ #!.To print S-bac slash. at the output ,which of the following is used as an escape sequence in printf a. 0S0 b. CSC c.SS d.none b.Sb c. Sf d. all the above. b.(,D c.!,# d.),( 9ls c. 9ld d. 6one

Ans"A #G.Fhich of the following used as alert escape sequences a. Sa b. SA c.SSa d. 8a

Ans"A Sa %%=alerts the user by sounding the spea er inside the computer.*ther sequences are Sr %%= carriage return SC%%=@ouble quote SS %%=Laclslash S0 %%=single quote Sb%%=Lac space #H.main-. B char ch>0 W 0/ int i>#(G/ printf-CSn 9c 9dC,ch,ch./ E what is the ouput of following program a.error Ans"L Expalnation: when a character is printed using 9d, it will print its ascii equivalent. #I. low%level dis $8* uses" a. 36$V system calls b. c0s standard $8* library c.both a and b d. 6one Ans"A #R.Fhat is that fprintf- . used for a. reads a set of data values from file b.Frites a set of data values from file c.Frires only a character to a file d. none Ans"C #Q.putc- . is used for" a.reads a character from memory cache b.reads a character from file. c.both a and b d.6one Ans"C (D.write the syntax for opening a file" a.fp>fopen-CmodeC, CfilenameC./ b.fp>fopen-CfilenameC,CmodeC./ c.fp>fopen-Cmode, filenameC./ d.fp>fopen-Cfilename,modeC./ Ans"@ (#.Fhich mode of file opening is used to open a file for adding content to a file with current contents being safe" b. W #(( c. #(( #(( d. W,W

a. a Ans"d

b. a;

c. w

d. both a and b

((.A file must be closed as soon as all operations on it have been completed because" a. 'o that all outstanding information associated with files is flushed out from buffers ,all lin s to file are bro en. b. Fe want to open file in different mode. c. To prevent acci dental misuse of file. d. All the above Ans" @

(). Fhen getc-file%pointer. is used for reading data from file,readind should be done until" a. file%pointer points to null b. 3sing some 6ull values c. Fhen the &nd%of%filemar &*, has been encountered d.All the above Ans" C (!.Fhat is syntax of putw- . function a. putw-fp. b.putw-fp,integer. Ans" L in files"

c.putw-integer,fp. d. none

(G.'yntax of fprintf- . a. fprintf-fp,Ccontrol stringC,list./ b.fprintf-Ccontrol stringC,fp,list./ c.fprintf-list,fp,Ccontrol string./ d. none Ans"A (H.Fhich of the follwing are error handling conditions during $8* a. b. c. d. @evice overflow writing to a write protected file both a and b 6one

Ans"C (I.Typical error situations during $8*" a. d. c. d. Trying to read beyond &nd%of%filemar Trying to use a file that has not opened opening a file with invalid filename All the above

Ans"@ (R.ferror- . function a. Ta es no arguments b. Ta es pointer as an argument

c. Ta es filepointer as an argument. d. Ta es structure as an argument. Ans"@ (Q.Fhenever a file cannot be opened using fopen a. Xalue D is returned b. Xalue # is returned c.6on%4ero value is returned d. 6ull pointer is returned Ans"@ )D.ferror function returns a. 6on 4ero integer if an error has been detected b.positive integer if an error has been detected c. 6egative integer if an error has been detected d. 6one Ans"A )#.ftell returns a.6umber b.6umber c.6umber d. 6one Ans"A )(.fsee -fp,m,D. a. :ove to -m;#.th byte in the file d.+o forward by m bytes c.+o bac wards by m bytes d.:ove to the mth byte in the file. Ans"A )).fsee -fp,DL,D. a. +o to the &nd%of%file b.+o to the beginning c. both a and b d.6one Ans"L )!.fsee -fp,%m,(. a. +o bac wards by -m;#. bytes b. +o to the -m;#. th byte c. +o to the m th byte d.+o bac wards by m bytes from the end Ans"@ )G.MMMMMMMMMMMMMM command line a. argv b. argc Ans"L )H.Command line argumens in C are a. Arguments on C editor counts the no.of arguments on the c. both a and b d. 6one function ta es file pointer as an argument of type long that corresponds to current position of type int that corresponds to current position of type float that corresponds to current position

b.1arameters supplied to program when the program is invo ed c.These can be passed as an arguments to main- . d. Loth b and c Ans"@ )I. argv represents a.An array of integer pointers that point to the commandline arguments b. An array of long pointers that point to the command line arguments c.An array of character pointers that point to the commandline arguments d. 6one Ans"C )R.MMMMMMMMM ta es a file pointer and resets the positions to start of file a.fsee -fp,DL,D. b.rewind-fp. c. both a and b d. 6one Ans"C )Q.$f statement on the command line is program x%file y%file the value in argvT#U is a. program b.x%file c.y%file d.none Ans"L

You might also like