4.2 I ()~ CProgramming v1a10N 9< d is ~ega t i ve" ' nurn); o . f ("The number pri nt . eve n"' nurn ); 9.c 2 ;::::: 0) dis % r be num 1· f(nu m ("The • pri. ntf · dd" num ) ; ' %d is o er " he numb else -------~ j__ _:pr: in:t~ f(~T= - - - - - - - else 0 of two numbers Maximum , e have to use the relational operator :::. to c °llip, f two numb ers, w . To find the maximum o two numbers. Q - -- - - - - - - - - #inc lude<std io . h> •,oid ma i n () ( numbers : ") ; int a , b ; prin tf ("\ nEnter t he two sca nf( "%d%d ", &a , &b) ; b) intf ( "\ nThe maxi.mum 1·s %d ", a ) ; i f (a ,pr else ; prin tf( "\ nThe maxi·mum is %d ", b ) r) Maximum of two numbers (using conditional operato use lhe condi ti ona1 oper ator ?: To find the maximum of two numbers, we can also ~ -- -- -- ---- -- -- -- -- -- -- - • - -~J~ <s:J l~ . h> • "'::. r. .. :- . . ::, :. -. , , -ax; , • " " ·i:::i::.er the cw "·: •~j,: :: • ,~a, ;r1; numbers : " ) ; max1m~m 13 %d ",na x); ~ • -- - - -.,.... ...-~. 4.L.L:. .~-. A I • j.,;, ;-x., .._.-..~ - - - ,\ ' Programs through Conditional.. . prograrn utf.:.11 \ 0 4-3 to calc ulate the max imum of three numbers. maximum of three numbers, we have to use the relational oper ator > to compare two . f at a ume. ...,bers o find the otJw . g de< stdi o . h> #J.· ncll l . ( ) ·d rnain vol. int a , b , c , max ; r int f ( 11 \ nEn ter the th ree num bers : •q; p f ( 11 %d%d%d ", &a , &b , &c); s can if(a >b) rnax =a ; else rnax =b ; if( c> rnax) ma x= c ; pr in t:. f ( \ nThe maxi mum is %ct ", max ); 11 ~------------------Q Program ro calc ulate the maxi mum of three numbers (using conditional operator). We have seen how to use conditional operator to find maximum of two numbers . This can be used in the same way to find the maximum of three num bers. Q- - - - - - - - - - - - - - - - - - - - win c l ude <st:.d i o . h > vo id main () i nt a , b , c , ma x; pt i nt f ( \n Ente r the t hree num bers : "); s can f( " ~d%d%d " , &a , &b , &c) ; ma x -=(a> b)?a : b ; ma x = (c> max ) ? c : max; pr1 ntf ( " \n Th e max imum is %d ", max ) ; 11 l 4-4 3. I 0 l) UISIOft C Programming ing statements Programs using Loop +2+3+ ... +n Sum of first n numbers l loop statement to start frorn 1 a e us we , rs be m nu n first and g0 To calcul ate the sum of . 0) ly al llpt to sum (which is initi 0 ~Each number is added Q------~ #i nc lu de <s td i o .h vo i d main () { > in t n, i, s um=O ; ); th e va lu e of n :" p ri n tf ( "\ nEnt er sc an f ( "%d ", & n) ; i++) fo r( i= l; i< = n; su m = su m + i; numbe rs is sum of fi rs t %d he "T ( tf n ri P 0 '5 d" , n, sum ) ; Q rs Sum of given n numbe T n numbers from the use r. o dot~ pt ce ac to ve ha e w , rs be given n num ch number .is added t~ Ea . rs To calc ulate the sum of be m nu e th pt ce ac d 0 t to count from 1 to n an we use a loop statemen . sum (which is initially 0) ---Q- - - - - - - - > # in cl u de <s td i o .h v o i d m ai n () { = O; in t n, i , num, sum nu mbe rs ? ") ; p ri n tf { "H ow many sc an £ ( " %d ", &n) ; i++) :- :: ,r (i =l ; i< = n; t h e number : " ) ,· t E er \ " n n ( tf ~ ri n ); ss an f( "l d ", &nu m m; s ..:~ = su m + nu ,..,.. , .. &, : , - - · , ..... 0 sum); ...,h"" sum is %d ", .L - \ 1Jonaf.. Programs through Cond1 . ..j{.~ \ 4-5 I of a number . ctorlO ed as n! = I x 2 x 3 x n. This can be done using a loop lat lcu ca is r be m nu a of ·aJ .... fO to n. ,rne fact011 1 . b goes from wbic JJl de <s td i o .h > •n cl ll #J. . cl 111 vo J. . a in ( ) pr od uc t =l , i ; . nt n, nu m be r:" ) ; J. . f ( "E nt er th e 0 nt f (" % d" ' &n.); . p . sc an , J.++) J.< =n · :::1 ' f or ( J. * i; pr od uc t= pr od uc t · %d ", pr od uc t); t o rJ..a l is 1 f . tf ("·"\ n Th e ac prJ.D 0 Cr nCr::: n! / ( r! x (n -r) !) To calculate the factorials we have to use a loop. g #i nc l ud e< st di o. h> vo i d m ai n () =1 , rf ac t =l , nm i i nt n , r , nf ac t e va lu es of n p ri nt f (" En te r th &r ) ; sc an f( "% d%d " , &n , +) fo r {i =l , i< =n ; i+ nf ac t= n f ac t * i; +) fo r {i =l , i< =r ; i+ rf a c t= rf ac t * i; i+ + ) fo r (i =l , i <= n- r; us rf ac t nm in us r fa ct =n m in sw er is %ct", pr in tf ( " \ n Th e an ) nu s rf a ct =l , i an d r: ") ; * i; rf ac t) ); nf ac t / (rf ac t* nm in us 0 4-6 / VISIO~ C Programming Digit Reve rsing Example: Input 978 output reverse=879. To reverse the djgjts of a number. we appIy the % and / operators succe ssive ly tO get th one by one till the number becomes 0· For example, if the numb er is 978 . ' We first e di&1~ apply ina 978% 10. Further 978/10 gives 97. 97%10 gives 7 97110 and gives 9. 9%10 g· get 8 by 0 ¾9 9/ 10 gjves 0. illid JQ - - - - - - - - - - - - - - # i nclu de<s t d i o . h> void main () { int n umb er, re v=O; prin tf( "Ent er the numb er scan f( " %d",& numb er); wh ile (num ber > 0) "); { re v = rev* 1 0 +num ber % 1 0 ; numb er= numb er / 10; p r intf ( " \ n The re vers e is %d", rev) ; Table generation tor,n (first l O multiples) To generate the first 10 multiples of any number, we use a loop for the multiplier which runs from 1 to 10 and multiply the number with the multiplier. Q #inc lude <std io .h> void main () { int n , i; prin tf( "Ent er the va lue o f n "); scan £ ( " %d" , &n) ; f or(i =l ; i<= 10; i++) prin tf( " %d X %d = %ct \n ", n,i, n*i ); _1_ _ _ _ _ _ _ _ __ _ _ _ __ _ _ _ __ __ g Programs through Ccn<fflicnaJ _f.!_\ -- 4-7 fa number ctors o of a number are all the numbers which di vide the number. For lhi~. we have co check · der 1·s 0, the number is a factor. The loop goes from 1 If th e remam · · · factor 'file ainder after d1v1swn. we re01 fCl 5 t0 Jl - 1. g de<stdio . h > •ncltJ . () #l. d rna i n "ol- illt n,i; . tf(" \nE nt er a number :"); prl-n " %d ", &n) ; . scan f( · -1· i < n; i++) f o r (i- ' /* * i is a factor** / if(n % i ==0 ) printf("%d is a factor o f %ct", i , n) ; _L- ---- ---- ---- ---- ---- ---- ~ GCD of 2 numbers To calculate the greatest common divisor of two numbers, we repeatedly subtract the smaller number from the larger till both numbers become equal. The result is the GCD. Q---------------------#include<s tdio . h > void main () int a , b; p rint f ( " \ nEnter the numbers : "); scanf("%d%d ",&a , &b) ; while( a !=b) if(a >b ) a =a-b; else b=b-a; } Printf( " \n\ nThe GCD is %d ", a); - - - - - - - - - - - - - - - - - - -Q 4-8 I or;, C Programming UISIOft to accept a number and check whether it is a perfect number (i .e., the ProQTam ::, 8 1.ltn factors=number itself). Gf . l[I To find the sum of factors. we repeatedly divide the number n by all numbers fro 1 the remainder is O, it is a factor and we add it to sum. If the sum and· numberareIo. l<h·1-! eqllaJ, it .· 11 perfect number. lj . I Q - -- - - - - - - - - - - - - - ~ #i nc lude <s tdi o . h> voi d mai n () { int num, i,sum=0; printf (" \ nEnter a number sca nf ("%d" , &num) ; f or (i =l ; i < num; i++) ; II ) j { if (num % i ==0 ) s urn=surn + i ; / ** i is a fa ctor** / if (s um == num) pri ntf (" %d is Perfec t ", nurn) ; el se pri ntf ("%d is not Perfec t ", num) ; Prime number To check if a number is prime, we successively divide it by 2 to number -1. If it is divisible ilii number is not prime. Thus, as soon as we get a Oremainder, we have to break out of the loop. Q- -- -- -- ---- -- -- -- - ,: r.c~ude <stdio . h> ·;,:, _ d :nain () :~: f.j:nber , i , flag =l ; 1., .c: :-. '::: ( "enter the nurnbe r : " ) ; .s ::::-c1r.: 1 %d " , &number) ; :=L ; i<numbe r;i ++) =~: • c 11 - ,"L'::I %i == 0) I Program:J lhrougn Cor.d,:h,..~ } · f(fJ.. 0 4- 9 g====O) f(" \ n The number is n o t prime " i ; pLint se f(" \ n The number is prime " ) ; e ).. . nt J.. p rl· --- --- --- --- --- --- --- --- -.,~ ~ ca1cu1ate 3 sine x using Taylor series x5 )( + - - ...... ". 3! 5! . r series to calculate sine(x) has n terms. Each term has a numeraw r and deno~r cr. the fay 1o . . numerator, we can use the standard function pow. For the denomm a10r. we have w for the the factorial using a loop. Even terms are subtracted and odd termS are added . calculate g void main () fl o at x , sum=O , numer; i nt i, n , p = l ; l ong int deno ; printf( " How many terms: "); &n l ; 5 canf ( " %d" , printf ("e nte r the va lue o f x : " ) ; s c an f (" %f" , &x ) ; f or ( i= l ; i<=n ; i++) { numer= pow(x ,p ) ; /* calcula te numerat o r* / /* ca l c ulate denomi nat o r * / den o = 1 ; f or(j = l ; j< =p; j++) deno = deno * j; if ( i % 2 == 0) sum=s um - numer I deno ; e lse sum= sum + numer I deno ; p =p + 2 ; } p rintf( " \ n The sum is % f" , sum); ~TS Q I (_)., 4-1 0 VIIIOII C Programming in th The Taylor series for cosine( x) is given below. Cosine(x) can be calcula ted e salh nl · • . . •qe \v numbe even Y o s cont.am senes the that 1s ce differen only ai,. sine(x). The rs as 0 P wer8 . ' factorial. <11\j x6 xs = J - 2! + 41 - 6 ! + g ! - ... x2 x4 COS X *, I, % Progra m to calcula.te multiplication, divisio n and modulu s withou t using 0 Perators . calcula te x * y, xly and x%y 1,t #inclu de<s tdio . h> #in c lude< math . h> void main () int x ,y , i , prod=O , quo=O , rern,s ignx= l , signy =l ; print f ( "Ente r the value s of x and y " ) ; scanf ( "%d%d ", &x , &y) ; if( x<O) signx=O; / **xi s negat ive** / if(y<O ) signy =O; x=abs ( x); y=abs (y) ; / *** ca l cu late x * y *** / f or(i =l; i<=y; i++) prod= prod+ x ; i f(sign x != signy ) prod= -prod ; / *** c al c ulate x/ y and x % y *** / whi l e (x >=y) I x=x- y; quo+ +; :em=x ; 1f(si gnx' =s1gn y) quo= quo ; i: s1gnx ==O) ~• x 1 s negat ive*~ / r<::m• - x ; ·r. ~f "n nThe produ ct 1s %ct", prod ) ; Or;, \ Programs through Conditional... 11111011 4-11 quo) ; 11 \n \nThe quotient i s %ct", •ntf ( ptlf( " \ n \ nThe remainde r i s %ct ", rem); ,int p - - - - - - -- - - - - - - - - - - ] ; i to display the first n terms of the Fibonacci series, i.e., J J 2 3 5 8 ... ram g pro . . . th the fibonacc1 senes 1s e sum of the previous two terms. We initialize fust two f 0 term Bach l and 1 respeeti vel y. __,._ to te11,.... ,g cte<stdio . h> #incll.l . d main() vo l { · f l= O, f2=1 , f3 ; int n , 1., c irscr () i rintf( " \ nHow many terms ps e a.. nf( " %d ", &n). ; for(i=l ; i< = n ; i++) ; II ) j f3=fl+f2 ; printf( " %d\ t ", f2 ) ; fl=f2 ; f 2=f3 ; ) __.!... l ____________________ .QJ. To display 'n' lines of Pascal triangle 1 1 1 1 1 1 1 4 6 10 15 1 3 3 5 6 1 2 1 4 10 20 1 5 15 1 6 1 The Pascal triangle contains the coefficients of binomial expansion. g ____________________ ~include <stdio . h> void main () { inti , j,spaces = 39 , num , n ; Printf( " \ nHo w ma ny lines : " ) ; ~ ~ ,:.. i,; ..... ~ .- ;.~ ~ ~ ~k~;...~~... w. 8fTV71fng c Pr 09~ c.,J. ,,_ 12 I v,,,o• . f/ "% d se a •', = ( " \n p: 1. -..,_-~1 ;1 iS \ n \n "); T ri a n '. < -n , " ") ; a ce s , " sp " % -, s , 1 ; e sf{ r:. ~1 .n ++ ) es = sp ac F. ·<-. i ; J sp ac J r- or {- -L ; &n J pA SC r> e T n_i + + ! " g .1 e (J. fo rr j- 0 , ! (, f( :; -- 0 4, I ) nu m -l ; j ; ~ (i -j ~ I) / ~ is e nu m = nu m f ( " %d p ri. n t 1) J. ! ( i -- " nu m ) ; ' b re a k ; ! n"); _· _( " _rt _. .! ... ~~p_r_i _n - -- - ----- m W nt. e a 'C ' p r og ra I 0 - ---- ---- t E x e r c is e LO p n n .c l n u m b e rs . tiirst JO n at u ra e ic is n eg a ti v a n u m b er if d isp la y , -~~ ------ ra m LO e ven Write a 'C ' pr og g er is o d d o r te in an er th e h ra m C h ec k w J s y m bo l W ri te a 'C ' pr og g = , > o r< n i s u rs e g ce two in te le B y 4 g ra m l o re fa I 0 0 D iv is ib W nt e a ·c p ro o T I n e e m b ers B e tw o H n d A ll N u T n u rn b e r. m ra g m p · c · Ie o f a g iv e n Wnte a b ta n o ti a c li e m u Itip d co d i, p lay <h ;e u " m rn og pc ip le s o f 5 . w ri te a C ' ..,c JO m u Jc fir c n n p tu ro g ra m Wme a C p z e ro e U -' e r e n te rs th l u n u er b num g ra m co a d d rs \I nee a r p ro o f Io n u rn h c rn u n ,r .a m a the su m o f m <o c a k u /are ra g ro P C 1 ,e n • \\ m e "- h e th e r !h e G k c e h C to m ra PaJinctronuc g ra m C P ro g ., :u m b e r 15 a \I n ,, ,' C P ro Arrays and Strings Unit 1. introduction we have used variables to store a single data item in memory However in many so f ar · . t.ons we need to store a large amount of data. apphca 1 ThUS, we would have to declare and use a large number of variables, which is very inconvenient. . Moreover, these variables are independent and unrelated to each other. Many applications ·requ1·re multiple data items to be grouped so that it becomes easy to manipulate them. This can be done using an array . Definition An array is a collection of data items of the same data type referred to by a common name. Individual data items can be accessed by the name of the array and an integer called the 'index' or ·~ubscript'. These items occupy contiguous or Oct. 2016- 2M What is an Array? Give an example. consecuti\'e memory locations. An arra) i, L1h o called a 'subscripted variable'. Slngle and Multidlmensional Arrays An arra) ha\lng only a single subscript is referred to as single subscripted, linear or one- dimen,1onal .irray. 5-1 5-2 o® I UIIIOII C Programming . , subscripts is a two-dimensional arr An array whose elements are specified by l\\ 0 ay (also cai1 a matrix). qJ Conceptually. an array can have any number of dimensions, limited only by the ava·1 table memory. 2. Array Declaration An array has to be declared before it is used in a C program. The declaration tells the c . ornp1ler I 1. the type of the array, 11. the name of the array. lll. the number of dimensions, 1v. number of elements in each dimension. Syntax: data -t ype array - name [ size l ] [ size 2 ] ............ • • [ size n ) ; • • • data-type specifies the data type of each element of the array. array-name is a valid C identifier. [size 1] .. ......... [size n] are the n dimensions of the array size 1. .. ..size n are positive integers indicating the maximum number of elements in each dimensions. rr~ Example: For each dimension, an array subscript begins from Oand has a maximum of size-1. i nt a [ 10 J; char name[8 0j ; In addition, a storage class can also be specified for the array (default is auto). Example: s ta t. ic i nt x [ 20] ; j //~ /. " t.J/ ., ~l/: ~:rr,r: ,, one Dimensional Array 1 3. . ensional array is declared as follows. one d1rtl A array-name(size) data_type le . int n [ 1 0 l ; exarnP . 5-J WJJIII '.JEf'A~ t-2, 'J .~ e-am~ cJ ,:;~, G-tr ~ ~~,..a e:,.'ra ________ p t . ·s a declaration of an array n of 10 integers. When an arra, b ~ '.Med. :rce ~, ::-.:= •• .::-:-- rtus 1 • or allocates a block of memory large enough to slore the enure arra\ reserves . number of bytes allocated is: '[he to tal rotal bytes = length of array * size of (data-type) 'fhUS, for the above declaration, 20 bytes will be allocated (considering thar an int..eger re:if.!.!:-es .: bytes) . I~ Address---+ 1000 e;; GD············· ·······@ 1002 1004 101 8 Figure 5.1: One dimensional array 3 .1 Accessing Array Elements To access a particular array element we have to specify the name of the array folJo,;\·cd by the index in square braces. The index indicates the particular element we wam to access. Syntax array -name [ integer- express ion] Example: n[O] refers to the element at position 0, i.e .. the first element. n[2] refers to the element at position 2 which is the third element. An integral expression can also be used as a subscript. E.mmple is as follows: n[5-2] n[i++] n[i-2] n[--i] n[i+j] are all valid. 5-4 / 0 UISIO~ C Programming Assigning Values to Array Elements Values can be assigned to individual elements by using the assignment operator (==). Syntax arr a y_ name [ index ]=value Example: n[0] = 20: n[2] = 35; Entering Data into an Array In most of the cases, the values are not known in advance. In such cases we can accept th e da~ from the standard input device (stdin) and store it in the array. This can be done in the following manner. The following code accepts ten numbers from the user and places them into the array. fo r (i =O; i <l O;i++) print f (" \ n Enter t he value f or p osit i on %ct", i) ; scanf( " %d", &n (i] ) ; The value of i goes from Oto 9. Initially i=0 and the scanf statement will cause the integer read from the keyboard to be stored·at the location (address) of n[0]. This process will be repeated for the entire array. Warning C does not perform bound checking for an array, i.e., it does not check for the validity of the subscript. This responsibility is of the programmer. Hence the programmer should ensure that the array length is not exceeded. Otherwise some other data may be overwritten. Example : in t n [ 5] ; f~r(i =O; i <lO ; i++ ) ssanf f"%d ", &n[i]) ; 'f hJ !j c;<)(Je 1i, pcrfeclly valid in a C program. / / hra;; W-rJ :,'J ''11 tLPta \ 5-5 oata frorn an Array eodlng ~ arraY elements can be read (accessed ) from the array u~ing c1 for lo<Jp a, lh"J~·. r p.ll the - i<lO ; i++) (i~o , .. for , f( " \ n The value at positi o n Id is Id" ' -, ··- .··-.· , print ffl1 .--:::. gram to read 10 integers in an array, display them and calculate their a"eraet " ~/* pro #incll.l cte <s tdi o .h> ma i n () int n (l O) ' i, sum = O; fl o at averag e ; / * ;,,.cc ept data and ca l cu l a t e sum* / . - o · i<lO ; i+ + ) { for(i ' . t f( " \ n Enter element prin %d", i ) ; s can f( " 9.°c d " ' &n[i)) ; sum = sum + n [ i ) ; } / * Display data* / f o r (i = O; i<lO ; i++) printf~" \ n Elemen t %dis %d", i , n [i ] ) ; /* calcula te averag e* / average = (float)s urn / 10 ; printf( " \n The average is %f", average ) ; ...;}------------------------ □ An operation cannot be performed on a numeric array as a whole. The operation has to be performed on individual ele1:1ents. Examp le: An array cannot be directly copied into another by using the assignme nt operator. Individual elements of the array have to be copied one-by-one. {)0 5-6 / u1s1on C Programming 3.2 Initializing an Array . • ·a1·zed when it is declared. Just like ordinary variables, an array can be mitl 1 The entire array or a part of it can be initialized. · An array can be initialized by the declarauon . f II Owed by an = sign and a list of val ° Ues en 1 COsed m braces and separated by commas. The values are assigned in order, to array elements from SUbscript O. Examples 1. int num[S] (10 , 1s ; 2s , 90 , 100) ; num ~r rj'fs tfC: tJ J 10 15 [O] [1] [2] [3] [4] Figure 5.2 2. char c[5] = { 'a', 'b', 'c', 'd', 'e'}; • During initialization, it is not necessary to specify the array size. The compiler allocates memory to hold the initialization values. int num[ ]= { I0, 15, 25, 90, 100}; • If less number of initialization values are specified, the remaining are initialized to 0. int a[lO]= I 1, 2, 3}; Here a[O], a[ I] and a[2] are initialized to the specified values and the rest contain 0. • If more initializers than the specified number of array elements are specified, the compiler gives an error. Arrays and Strings . (.,}e \ lttltOII 5-7 s . ~oJT'I~ . ~ ~ 1, ;\n example to find the largest and smallest number from an array of n integers. 1fJ1 --- gest and smallest number from array */ t* Laf ~ #).·nclll . de<stdio . h> )110.if1 () i nt i, n, num[SOJ, largest , smallest; ·ntf(" \ n Ho w many numbers") ,· p:r1 f ( " %d", &n) ; /1' scan ept numbers*/ ACC . tf ( " \ n Array elements prJ.D f or(i==O ; i<n ; i++) scan f( \ n "); " ~d" ° ' &num[i]); / *Initializat i on * / 1···~:;;:;·····························......., ~ ! How many numbers: :: _5 I :~ray elements : : largest== smallest = num[ OJ ; / *Comparing with remaining elements* / f or(i==l ; i<n ;i++ ) ; l :: : j ! -9 120 Q ! 36 if(num(i] > largest) largest = num[i] ; The largest is 120 The smallest is -9 ....................................................... else if(num[ i ]< smallest) s ma 11 est = n um [ i ] ; pr in t f( " \ n The largest is %d" , largest); p rintf ( " \ n The smallest is %ct", smallest); Q 5-8 I {}'9 C programming UISIOII rraY· Reversing an a ►► 2. ray */ - Reversi.ng ""D ar ' lnl t* }E:!, # in cl u d e< st d m ai n () ]; [SO] ' re v[ S O a nu m be rs " ) ; in t 1 , n, y an How m p ri n tf (" \ n n) ; s ca n f ( "%d" , & \n "); m be rs *I / * A cc ep t nu ts en em el y ~ .r ra p ri n tf ( " \ n .r ;i + + ) fo r( i= O ;i <n & a[ i] J ; sc an f( "%d" , a rr a y * I / *Rev e rs in g ;i + + ) fo r( i =O; i< n a [i ]; re v fn -i - 1] = :" ) ; d a rr a y is se er v re he T p ri n tf ( " \ n ; i+ + ) fo r (i=O ; i< n ", re v [i] ) ; p ri n t f ( " %d\n . ►► 3. Q from d prime numbers an en ev d/ od ng Displayi * :-:m-;b~er-s - : : : v ::n:--;a::n:d-:; p:ri~m:-:e:-:n:-:u /~*:'°iO~d;:;:d/'.ii:e:e • - :. ~ l ud e < s r d i o . h> a[ S O ], fl ag ., .: -, r., ,,,.. ...- ,... ... F ( " ,_ - · · - - n ; How many nu m be rs " ) ; • ~r~~y . . . . . . ··; r;utp~t i o . r.> el em en ts \n " ) ; mbers : 5 ! Array elements : / 25 i -9 nu j How many i 120 ! ! I r / / i ! 0 36 j ! ! is • reversed array 120 I -9 j I I 2s ....................................... : : ..................... I 1Q an array ------/-;------ - - - - - -- - Arrays and Strings s c an f( " %d", &a[ i)) ; •ng odd- even and prim e* / · splaY J. ; t Dl· "<n· i++) (i==O, J. ' f or: if(a [i]% 2== 0) prin tf( " %d is odd" , a[i] ) ; prin tf( " %d is even ", a[i] ) ; flag = l ; / * chec king prim e* / for( j=2 ; j <a[i ] ; j++) if(a[ i)%j ==O ) flag= O ; brea k; if (flag == l., prin tf ("%d is prim e", a[i) ) ; Q ~ 4, To conv ert a decimal number to binary, the decim al number is successively divided by 2 till the number becomes Oand the remainder s of each division are displayed in the reverse order. .C, /* Decimal to binary conversion */ #i nc lu de< stdi o .h> main () te!I unsi gned in t de c _num , rem( 16] ; i nt i ; / * I nit i a lize rem aind er arra y* / f or(i = O;i <1 6 ;i++ ) rem ( i) = o; pr i n t f ( " \ n Ente r the decim a l numb er : ") i scan f( " \% u",& dec_ num ); (),) I 5-10 UISIOII i= O; C Programming / * sec i cc 0 th element o f r emainder array " / * divide numbe ::- succe ssive l y by 2' wh ile (dec_ ~~m >Ol rem[i] = Output a .......................... Enter the ···, number: 25 deciniai !he binary e . is: 1100100006u1va1en1 00000o Output b dec_ num % 2; i++; de c_ num = dec_ num / 2; . } /* Di splay remainder array in rever se order* / l printf( " \ n The bina ry equivalent is : \ n" ) ; f o r (i =l S; i> =O; i - - ) .............................................~.~.' ...] print f (" %d", rem [i ]) ; ►► 5. To merge two sorted arrays into a third array such that the third is also. 1n the sorted order. Al A2 A3 [J Enter the numb~r: 65535 decinia1 ,The binary e . l is: 1111111~~,~~~e,ni \ 10 25 90 9 16 22 26 100 9 10 16 22 25 26 90 100 /* Merging two sorted arrays of m and n elements respectively into a third array*/ #include<stdio . h> - main () int m, n, i,j , k , al[20) ,a2[20 ],a3[4 0) ; p rintf( " Enter the length of the fi rst array :" ) ; scanf (" %d ", &m) ; /* Accept elements of first array* / pr i nt f ("Enter elements in the sorted order \ n"); fo r(i =O;i <m; i++) s,:;anf (" %ct", &al [ i)) ; pr1ntf( " \ n Ent er the length of second array :" ) ; ssar,f 1"%d", &n) ; ! /. " ,J1 ~ ,, :;: : / ' ·,, ; ✓- 'iJSU.a :5-,-, 1 element s o f ses0~d arr~; · ccePt .A · ot p rlf or sc lG t~~ f( " \ n Enter e l ement s . · <n ; i++) ( i ""o , 1. 00 f (" %d " ' &a2[i]) ; int o the t hird arr ay as . . 0r.g ~ ::, . t-1er-g1.n9 . _ O· k== O; ' . ,,,, O; J( ( i <rn) & & ( j < n) ) 1- . wn1- l e 1* / * In itiali21;-.g • if(al[i] < a2[j]) a3[k] == al[i) ; i++;k ++ ; else a3[k] == a2 [ j l ; j++ ;k++ ; rrayl has not ended, copy its eleme nts~ , / * if a whil e (i<m) a3[k] == al [ i]; i++;k++ ; / *if array 2 has not ended, copy its elements * / while ( j <n) a3[k] a2 [ j] ; j++ ; k++ ; / *Display merged array* / printf(" \ n The merged array is \n" ) ; for (i=O ; i <k ; i++) 1 Printf("%d\ t ", a3 [i )) ; ----- ---- ---- ---- ---Q 5-12 I CJ., UIIIDII C Programming :····················································································································· l 1 Enter the length of the first array : J ! I Enter •~ements in the sorted order : j I Enter ttw"°length of the second array:§ Enter e~ements in the sorted order: 1 I I I § I f~ I : 19 l I : 19 : / The merged array is 3 5 5 7 9 10 15 19 19 , ! l Output a I ............................................................................................................................... 4. Two-Dimensional Arrays Most often we need to store and perform operations on matrices and tables. For this, we can use a 2-D array. A 2-D array has 2 subscripts - one indicating the row and the other indicating the column. Example: , .......' ,' 1'. : ' \ ~ _<,,. 'Oct. 2017·..:'2u · ,, __,, Define 2-dimens·1 ona1 • array. Give exampl e. int m [ 3 J [ 2 J ; mis declared as a 2-D array having 3 rows (0-2) and 2 columns (numbered 0-1). The el emen~ are m[O][O], m[O][l ]...... m[2][1]. 4. 1 Initializing the Array A matrix can be initialized in two ways: int m(3 ] [ 2) = { {1, 2 } {3 , 4 } { 5 , 6} }; J Arra;a and St11r.g:, === i.Z .. \ 5,-13 {1 ,2, 3 ,4, 5 , 6} ; m RowO rv,eni 0 (/ llJlll col O col 1 1 2 Row 1 3 4 Row2 5 6 ry Repr esen tation (Physical View) . linear. Hence even multidimensional arrays are ytefllorY · A 2 _D array can be stored in memory in 2 ways. ·nearlY • red ll ;to 11..t"ajor Representation: Elements are stored rowgo\\7 1n . . e elements of row O are stored first, row 1 next j, wise, i. ., 2-0 array can be stored In memo ry in 2 ways. 15 i. Row Major Repres entatio n: ii. Column Majo r Repres entatio n and so on. Example Row0 m u. Row 1 Aow2 1 2 3 4 s 6 m[O][0] m[0][1] m[1 ][0] m[1 ][1] m[2][0] m[2][1] Cohunn Major Representation: Elements are stored column -wise, i.e., eleme nts of column O are stored first, column 1 next and so on. Column 0 m\ 1 m[O][0] I Column 1 3 s 2 4 I s I m[1 ][0] m[2][0] m[0][1 I m[1 ][1] m[2][1] Address Calcu lation Address of any elemen t m[i][j] in a matrix of r rows and c columns can be calcula ted as i. Row major representation: Address of m[i] U]=base address + (i*c+j ) * elemen t_size ii. Column Major: Addres s of m[i] li]=base addres s+ G*r+i) * elemen t_size 0-, 5-14 / UIIIOI C Programming 4.3 Accepting Matrix Elements We have already seen how data for one-dimensional array can be accepted from the User A similar method is used for a two-dimensional array except tbat we will now ha · one for the row subscript and the other for the column. "' lo, Ve l\ 0 For every value of row subscript, the column subscript has to increment from 0 to nu columns-1. illbe1 Examples The following program illustrates matrix addition. .. 1. [CJ /* Program to add two matrices */ #inc l ude <std i o .h> ma i n () int matl [l 0] (1 0] , mat2[1 0] (1 0] , mat 3 [10 ] [10] , r l , c l , r2 , c 2 , 1· , J. ; printf( " How many rows and co l umns in mat r ix l ? : " ) ; s c a nf( "%d%d" , &rl , &c l); p rint f ("How many r ows and columns in mat rix 2? : " ) ; sca nf (" %d%d ", &r2 , &c 2) ; i f ( (rl == r 2)&& (c l==c2 )) / *chec k if they can be added* / { printf( " \ n Addi tion pos sibl e \ n") ; printf (" \ n I nput Mat rix 1 : \ n"); f or (i=O;i <rl;i ++ ) fo r ( j =0 ; j <cl ; j ++ ) / * r ow subscr ipt */ / * col umn subsc ript */ sca nf (" %ct", &matl [i ] (j ] ); print f(" \ n Matrix 2 : \ n) ; for (i = 0; i <r 2 ; it+) f o r(j=0 ; j <c2 ; i++) sca nf ( "%d" &mat 2 [ i ] [ j ]) ; / *add co rre sponding e lements of both ma trices */ ma t 3 [ i l [ j l = ma t1 [ i ] [ j ] + mat 2 ( i ] ( j ] ; , ,.. mi•• ' r es ul t I 5-1 5 1r ; ;, o i s p la.Y f(" \ n The s um i s . rl-n t . o · i < rl; i+ + ) P f o !' (1== ' n ,, I i for (j= = O;j <c l ; j++ ) ; pr in tf ( " %5 d", ma t 3 [ i ) [ j l) · tf( " \ n") '· pr in Of. */ e nd if }/ * els e ~~ 1 e ("\ n Ad dit i on not pos s i· b l \ ::" ) ; P rin tf . *I / * end ma in . :!!: , ................ r·..;~~;~~·~····........................................................................................... ix 1? : HoW many rows and column~ in ma~ rix 2? : HoW many rows and columns in mat i,,,i . I ~ ~ Addition not possible. , Output b i rix 1?: How many,;cws agd columns in mat rix 27 : How many~ows a~d columns in mat Addition possible · l Input Matrix 1 :·,• . I , I :.!, i,.! I I Input Ma J 2 ii 1 The sum i1 l I I : .! ············ ····························································································. ............................ : 5~ 16 I V" VIIIOII .,. 2. c Programming Transpose of a matrix Transpose is a matrix with the rows and columns of the original matrix interchanged . .QI /*Transpose of a •in2lude<s t d i o . h > :r.a.1n ( J 1.nt ml[lO] [10 ], tr a ns [ lO ] [1 0 ] , i , j , r , c ; 2lrsc r() ; print f ( " \ n Ho w ma ny r o ws and c olumns i n t he matri x :" ) ; scan f ( " %d%d", &r , &c ) ; ")i print f(" \ n Ent er the e l e ments /* r ro ws* / f o r ( i=O ; i< rl ; i++) / * c c o lumns * / f o r(j=O ; j<c ; j ++ ) I scan f ("%d" , &ml [ i] [j ] ) ; trans[j ] [i]= ml[i ) [j] ; \ n" ) ; pr.1ntf (" \ n The trans p ose i s / * c r ows * / f o r(i=O ; i<c ; i++) / * r columns * / for(j=O ; j < r ; j ++ ) printf( " %5d" , tra n s( i ] [j ] 1 ; pri n t f(" \ n " ) ; ·································································•·... . Output Hvfl _man; rows and columns in the matrix: ~ ... rte· g •rs e'em ents -7 -4 : I ,..~ ''af S.½$':: 5. 7 4 ~ 2 i .................................... ···································--···j Cbeeking uppe r/\ower Arrays and Stri ngs triangular and sy mmetric O~\ """ 5-17 tt 3· matrix. . matrix is suc h th at ati1G1 = aG1U1 J1111letfl . ln an upl)er trian f. s~ . d. Cgon gular matri x all a l are 0. elements below in ia U\e¢ - p01, i , j , r , c , f l ag in t a l 1 01 ; t" \ n Ho w many rows p r int f a n d column s i.n th e m at r ix : n ) ; f l " %d%d " , & r , &c) ; scan . f l" \ n En t e r t h e p rJ.n t e l e me n ts ") ; fo r ti.=0 ;i . <r ; i+ + ) o f O f \'J·- '· J' < c ; j ++ ) s c a n f \, 11 9.cd " &al i. 1 lj 1 ) ; nag = 1 ; 0 ' : or (i = 0 i i< r ; i+ + ) f o r l j =0 i j< c ; j++) i fl al ii l j i \ =a l j i l i 1l l f la g =0 ; b re a k ; } if ( fl a g = = l ) p r in tf l " 'I he mat r i x is symme t r ic") ; e ls e p r i:Yc.f t " T h e ma tr ix is n o t sym roetric u) ; f la g = l ; fo r( i=0 ; i< r ; i - +) :o r ( j=0 ; j< i ; j+ + ) if ta ll .i l j i \ =0) lf la g =0 ; b re a k ; ) i f l f la g == l) p r in tf t " T Y tr h e m a tr ix is uppe - ia n g ula r " ) ; e ls e P r in tf t " T e r t r ia n g u h e ma t r ix la r " ) ; is no t upp 5-18 I ()., VISION C Programming for (i =0; i <r ; i++) for( j=0 ; j>i ;j ++ ) if ( a [ i l [ j l ! =0) (fla g =0; brea k ; ) i f ( fla g== l) lar" ) ; prin tf(" The mat r ix is l ower tri angu els e ngu lar " ) ; pri ntf( " The mat rix is not l ower tria retu rn 0; 5. Multidimensional Arrays . However common programs do not ne Multidimensional arrays have more than one subscript to use arrays more than 3 dimensions. Exa mple : int rn[3) (4) (2) ; arrays having 4 rows and 2 columns each. Here m is an an·ay consisting of 3 two-dimensional col 0 col 1 ~ 2D array 2 . 2D array 1 2D array 0 . 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Figure 5.3 17 18 row O 19 20 row 1 21 22 row 2 23 24 row 3 :ed Arrays and Slt1ngs .. \ VlllOI () ; 5-19 Memory Map 20 array 0 --.i.-- 2D array 1 - - 1M4--- 11 1002 14 1008 I 2D arra12 ~ 8 1920 2122232:4 • 1014 Figure 5.4 Apf. 2018- 2M Limitations of an Array· 6. What are limitations of Array? The compiler uses static memory allocation for an array, i.e., we have to specify the array size in advance. It is not possible to increase or decrease the array size at runtime. l. 2. Elements cannot be inserted into an array. 3. we cannot delete elements into an array. 4. If the number of elements to be stored is not known in advance, there may be memory wastage if an array of large size is specified. s. If a small array size is specified, there may not be enough memory to place all elements. 6. C does not perform bound checking on an array, i.e., it does not check for the validity of the array subscript. Hence, if the array range is exceeded, some other data may ge~ overwritten. 7. Arrays and Functions Arrays can be passed to a function in two ways. 1. ii. Element by element Passing the entire array When the elements are passed to the function, their value is copied into the corresponding fun ct·10n parameter and cannot · . be modified by the function I 5-20 I (.}0 UIIIOII C Programming · ai,·ay can be passed An entire as an argument tO the function. The function gets coIUplete aec to the original array rather than a copied array. Before we see how it n~e. 7. l can ess be done, it is important to underStaod th e importance of th ea ~ Name of the Array Consider the declaration int n[lO) ; The name of the array is n. The name n without any subscript refers to the starting add . ress or base address of the array in memory, i.e., it refers to the memory locat10n of the Qth element of the array. Thus, n is eq uivalent to & n[O] . It is a constant pointer and cannot be changed (' I.e., incremented/ decremented, etc.) When we want to pass the array n to a function sum_of_elements, the call wi ll be given as surn_ o f_elements(n) ; This makes the complete array available to the function and the function can make modifications to the original a.ITay. This is so because by specifying only the array name, we are in effect sending the base address of the array to the function. Thus, the name of the array can be used effectively as any other pointer to the array in accessing the array elements. This is illustrated below. Example /*Illustrate array name as a pointer to the array */ _ ·.: 'Cl • ' 51 i fi!i;~~~:~:~~:~ l = ( 1 0 , 2 0 , 3 0 , 4 0 , 5 0 }; r c::iins %d \n ", (al+i), ~ (al+i)) ; .:.~ 65494 65496 i 65498 1 65500 contains 20 contains 30 contains 40 contains 50 :i, i i i....................................................... Arrays and Strings {)e \ UIIIOII 5-21 contains the base address, al+O points to the 0th element and *(al +O) gives the valu e of ·oce a 1 s1 Ul elernent. weO . wes ha11 7,2 . see rnore about arrays and pomters m the next section. passing the Array Element By Element 'fhe arraY '[be f un elements can-be passed one-by-one to the function. ction thus gets acce ss only to one element at a time and cannot modify this valu e. le as f ollows: ExamP main () int n[S) ={l 0 , 20 , 30 , 40 , 50) ; vo id d ispl ay( int) ; / * func tion prot otyp e* / int. i ; f or( i=O ; i<S ; i++) ctis play (n[i )); vo id disp lay( int x ) p r intf ( " %d " , x ) ; 7.3 Passing the Entire Array In orde r to pass the entire array , we just have to send the name of the array to the function. Since the nam e contains the base address, we are effectively sending the entire array . The function gets access to the original array (since it has the base address). It can mod ify the array contents. {)0 5-22 I u1s1on C Programming Eram ple is as follows : ma i n () int n[S] = {10 , 20,3 0,4 0, 50} ; / *Fun ction decl arat ion* / vo id mod ify(i nt b[S) ) ; modi fy(n ) ; void mod ify(i nt b[S] ) int i; for( i=0 ; i <S ; i++) b[i) = b[i) * 2 ; the array n, they are changed to In this exam ple, the function modifies the contents of 20,40,60,80 and 100. LNote I l e b stores the base address of n b is not a new array created but it is the same as n becaus (Covered in detail in the next chapter). 7.4 Passing Dimensional Array to Function l array to a function to find the The following program illustrates passing of an one dimen siona largest number from the array. C /*Passing an array to a function */ ~~nc lude <std io . h> -~L array (SO] , i,n ; :r.: ... arge st ( int x [] , int n) ; / * func tion prot otyp e * / ~r.~ :~I" ~ How many elem e nt s? :" ) ·1a • ..ies • / f-, _; · : " - :np' r ·;al Jes n" ); ' ► Arrays and S1rings (_}£ \ VISIOII 5-23 • / n ·i++) ( i;:::: O'• ).' ' f0' n.d" &array[ i]); f ( ,, "6 ' 00 sc . o n call and display result * / I * ftlnct J. f( " \n Largest number= %d", largest (arra y , n )J ; rint . P est(int x[] , int n) a r g l iI1t 1arge = x[ O] ; int j' ·-1 for ( J - '· j<n ; j++) / * initializ e Tl / * compare remainin g eleme n r.s " / if(x [j] > large) large = x[j]; return ( large) ; _1-,;,__---------------~ ,.................................. 1 l l ! output \ How many elements? : §. \ Input values: 100 : 0 \ :90 \ i 48 1 : 1 1 2000 ! l Largest number= 2000 j i.......................................................................................................................: Note: The function header could also be written as i nt large s t ( i n t * x, int n) In both the cases, i.e., int x[] and int *x, x means a pointer to an int. The loop inside the function could also be written as for(i=l ; j<n ; j ++) if (* (x + j )> l a rge) large = *( x+ j) ; I 00 5-24 UISIOII C Programming In the above program, we have passed a 1D array to the function. In the same way , We c an Pa a 2D array to the function as shown below. 81 Program to accept, multiply and display matrices using functions. Example Q/*Illustration of 2D Arrays and functions */ #i nclude <s tdio . h> ma i n( ) int ver i fy(int x , int y) ; vo id readmat( i nt x ( l 0 ] (10), int r , int c ) ; vo i d multma t ( int x( l 0) [l 0] , int y[l 0 ] [1 0) , int z [1 0 ) [10 ) ; vo id dispmat(in t m[ l 0 ] [1 0] , int r , int c) ; i nt a [ l 0 ] [10 ], b[l0] [10] , c[l0 , 10], rl, r2 , c l , c2 ; pr i ntf( " \ n Number o f r ows a nd co l umns i n matrix A:" ) ; sca n f( " %d %d", &r l , &cl) ; prin t f (" \ n Number of r ow s a nd co l umns in matr i x B:" ) ; scan f (" %d%d " , &r2 , &c2) ; if(verify (c l , r2) == 1 ) printf( " \ n Mul tipli c ati on Possible \ n" ) ; printf(" \ n Input Matr i x A \ n" ) ; readmat(a , r l ,c l ) ; pri ntf(" \ n Input Mat rix B \ n " ) ; readmat(b , r2,c2) ; / *Multip ly A and B givi ng C */ mul tmat(a,b , c ,r l , cl , c2) ; / * display result* / printf(" \ n The resultant matr ix is \ n " ) ; 11spmat(c , rl, c2) ; } /* end if * / J • ► Arrays and Stflngs ns o f A must be equa l t o r o ws ). . tf{ " \ n Mul tipl icat ion not .Pos sibl e" ' . tf(C olum pr 1n R • _ 1r. O• \ 5-25 lftllO I n u J ,· pr1n a dma t ( int x [ 1 0 l [ 1 0 J , int r, int c ) re void int i, j; for(i === O;i< r;i++ ) for(j === O;j< c;j++ ) scan f ( " %d", int ver ify( i nt x, &x [ i l [ j)) ; int y) retur n(x= ===y ) ; } vo1'd disp mat (int m[l OJ (1 0 ] , i nt i, int r, int c) j; f o r ( i= O; i < r;i+ +) f o r (j = O; j <c ; j++) p rin tf("% 5d" , m[i] ( j]); p r in tf ( " \ n"); (1 0] , vo i d mult mat (int x [ l O] ( 1 0 ], int y [ lO] int z (10] (10] , int rl , int cl , int c2) int i , j , k ; for( i=O ; i< rl,i+ +) for( j = O; j<c2 ;j++ ) z[i) (j]= O; for( k = O; k <cl ; k++) z[i] (j] = z(i] [ j] + x [ i ] [ k l * y[k ] ( j] ; - -- - -- - - - - - - - - - - - - -Q. 5-26/ VI~~ C Programming Output a Number of rows and columns is matrix A : 2 ~umber of rows and columns in matrix B : g ol~m~s of A must be equal to rows in B Multrplrcation not possible. g Output b Number of rows and columns in matrix A : 2 Number of rows and columns in matrix B : 2Multiplication possible Input Matrix A g 1 1 1 Input Matrix B - 2 - g J 1 4 5 The resultant ~atrix 6 1 i; 8 2 10 13 3 . . •·········•·············............................. .............................................................................J 8. String r--::::----...!.: 4 A string is an array of characters terminated by a special character called NULL character ('\O'). Strings in C are enclosed within double quotes. Example: "Welcome to C" is a string and it is stored in memory ~pr.18,0ct.16- 2M ',. __ Define string with example. Oct., Apr. 17 - 2M · Define string. Give example . · as: w 1000 e C 1002 j 0 1004 m e 1006 t 1008 C 0 1010 \I 10 Each character is stored in 1 byte as its ASCII code. Since the string is stored as an array, ii possible to manipulate individual characters using either subscript or pointer notation. f.rra; s ar.1J Stnr~ fl•\ 11S1U 5--27 ring and Initializing Strings .1 6 'flee 0 ·og is a . ng n st! J. 8'! d - ame[length) ; • .-rllines the maximum number of characters in the string ~d~~J•- file }etlg tes: c,,:ClrrlP P fher . . character array, 1t 1s eclared as follows. . 8 s~ 51 ~ eclO a r cit Y [ 1 o) . ; cl:1 r name [ 2 O) ; cna.,,. message [ 80) ; cha .I,. ays to initialize strings. . e are ewo w char city [] = { 'p', 'u', 'n', 'e', ' \ 0 ' } ; j, Bowever, C offers a beue·r way to initialize strings. char ci· ty [] ="Pune" ,· ,· The compiler automatically stores the null character at the end of the string . the following two declarations. But are valid however there is a distinction between the . consider tWO, \ I ,' char amessg [] ="C programming language"; cha r *pmessg=" C programming language "; / *arra y"' / / *poi nt.er~ amessg is an array big enough to hold the sequence of characters and '\O'. Even if the characters are later changed, amessg will always refer to the same storage. On the other hand, pmessg is a pointer, initialized to point to a string constant. pmessg may be later made to point elsewhere. The result is undefined if we try to modify the string contents. D 12 l is amessg \ C programming language \0 \ .,_____.. C programming language \0 Figure 5.5 I 00 5-28 u1s1on C Programming 8. 2 String Inpu t/ Output Similarly the functions printf and scanf can also be used wi th th e format specifier o/, . os. 1'h function does not allow a strino with embedded spaces. gets() allows a stnng to co e Sc~. e . ntajI) " I( We shall see an example of usino the printf function to display chara cters of a string. Spac. , e 1n th •s. of a kite. e Sha1x; Although this can be obtained by different methods, the easieSt of them is to use th . e fo11n . features provided by the printf functi.on. attin~ If the string is abed, the required output is aa abab abcabc abcdabcd abcabc abab aa It] ~ ;*~'7: D~i-=-sp~l:""'a_y_s"."" tr".in ""-g-:i-n""'t:.'he---:sh_a_p_e_o-::-f-a":"'ki"."t-"e --::*'."/':" - - #inc lude <std io . h> main () -------------...... { char s[80 ) ; puts ( " Plea se ente r the strin g" ) ; gets (s) ; I * Uppe r tr iang le * / for( i=l ;i <=st rlen (s) ; i++) { prin tf( " %40 . *s "i , s) ; / * Disp lays i c hara cter s fr om stri ngs in a tota l o f 40 cha ra c ters .De faul t is righ t just ifi cati on* / prin tf(" %-40 . *s ", i , s) ; /*D isp lays i char acte rs left justi fied */ i I , , Lowe r Tria ng le * / for( i=st rle n(s) -1; i> =l; i--) prin tf( " %4 0 .*s" , i , s ) ; pr:n tf("% - 40 . *s ", i,s) ; _,;,___ __ __ ____ __ __ __ __ _ g ~ ( Arrays and St"r.gs stondar d Library String Functions prov1·des a large number of functions in the header tile string•h for the han dlir.c0 ,' , 1at1guage (>f . / ,triJlg 5 nly used functions are: · ,.,i0st corn,rno rh8 ()· . . This funct10n returns an mteger corresponding to the number of characters in the strJen . . •fied stnng. spec1 :' size_t strlen (char * s) syntax,: , -- . - - - - - - - ---- , 1 \ ,' Apr. 2016- 2M Give syntax and use of strlenO and strcat(}. char str[20] ; gets (str); printf("%d", strlen(str)) ; Example: ,. If the user enters C language, the output will be 10. . This function is used to concatenate Uoin) two strings It concatenates a copy of ii, strcat() · . · the second string to the first and returns the first. The second remains unchanged. Syntax: · char * strc at(char * s1 , char* s2 ) Example: c har s1[2 0 )= "Pune ",s 2[2 0 ] =" Murnbai "; st rcat (s l, s2) ; puts( sl ) ; p uts (s2 ) ; The output is: PuneMumbai Mumbai · ·u" I ' strcmp(): This function is used to compare two strings. It returns an integer. which is -ve ~ if string 1<string 2. 0 if string l is equal to string 2 +ve if string 1 > string 2. Syntax: Example: i nt strcmp(cha r * s1, char • s 2) ; Oct. 2016- 2M What is the prototype and use of strcmp() ? c har sl [lO)=" ABC", S2[10]="abc "; p rintf(" %d" , strcrnp (s1 ,s 2)) ; The output will be - ve. Since "ABC" is less than "abc" because the ASCII value of 'A' is<ASCII value of 'a'. 1%2~~ The fu nction strcmpi is used to compare two strings ignoring the case. 5-30 I o., VIIIOII C Programming . iv. t of string 2 to string 1 and retu ms string . strcpy: This function copies the conten s l. \ original contents of string are lost. Syntax: Example: r *s2) char *strcpy (char *sl , c h a 20 ) =" Mumb a i. " ; c har s1[ 20) ="Pune", ? 2 [ strcpy(sl , s2 ) ; puts (sl); ii. strlen puts(s2) ; iii. tolower iv. strrev V. strcpy The output will be Mumbai Mumbai The following are other string handling functions: Name Prototype Description strlen size_t strlen(char • s) Returns the length of the string (numbe~ characters excluding the NULL character)o strcpy char • strcpy(char *d, char *s) Copies the contents of string s to d and r~ urns Pointer to d strcat char • strcat(char* s1 ,char *s2) Concatenates a copy of s2 to s 1 and terminat es s1 with a null. Returns s1. strcmp int strcmp(char *s 1,char *s2) Compares s1 and s2 and returns , -ve if s1 is less than s2 0 if s1 is equal to s2 +ve ifs 1 is greater than s2 strcmpi int strcmpi(char *s1 , char· s2) Compares s1 and s2 ignoring the case and returns similar results as strcmp. strlwr char *strlwr(char *s) Converts a string pointed to by s to lowercase. strupr char *strupr(char *s) Converts a string pointed to by s to uppercase. strncat char • strncat(char *s1,char *s2, int n) Concatenates first n characters of s2 to s1 and returns 7 s1. s2 is unchanged. I r-- I strre, - char 'strrev(char 's) Reverses the string s and returns the reversed string. str~rir char 'strchr(char ·s,char ch) Returns a pointer to the first occurrence of character ch in string s. l,; 1 f6l/ i:.11ar ·sustr(chars·1 ,char *s2) Returns a pointer to the first occurrence of s2 in s1 . Returns null of no match 1s found . . . - r:.har .. ,;i' a, . strsetlchar .s.char ch) ~ Sets all characters in pointed to by s to the value ol ch • :.tm;;.et 'char 's char ch, int n) / Sets the first n characters of string s to the value?' ch Arrays and Strings 5tr mp(char•s1 ,char*s2,int n) ...1 crTlP • char •strdup(char *s) • strchr(char •s, int c) char Compares first n characters of s1 and s2. Returns<O if s1 is less than s2,0 if they are the same, >0 if s1 is greater than s2 . Duplicates a string at another location and returns NULL if space could not be allocated or returns a pointer to the storage location containing duplicated string. strdLlP char 5-31 Conv~rts a string pointed to by s into an integer, returning the result. Similarly there is atol and atof. i(char •s) int a to int strnc Oe \ VJIIOI Returns a pointer to the last occurrence of character c in string s, NULL if not found. --i by Searches s1 for tokens that are separated delimiters specified in s2. Returns the pointers to the first character of first token in s1 . ~---------t---.::...______::. .:. . _:,. : .__::.:_________ •strtok(char •s1 ,char *s2) strtOI< . tf and sscanf • tf is the same as printf except that the output is written into a string rather than sprtr"I . spr1n . layed on the output device. The return value is equal to the number of characters • d1SP actually placed into the array. The string is terminated with '\0' and it must be long enough to hold the result. Prototype: int sprint f ( char * buf, char * format, Example: cha r s ( 80 l ; spri ntf(str, arg_l ist ) ; " %s %d %f", "Hello" , 2, 5.0); This will result in the data. Hello 2 5.0 to be put into the string str. • sscanf is identical to scanf except that data is read from the array pointed to by buf rather than stdin. The return value is equal to the number of fields that were actually assigned values. Prororype: int sscanf (cha r *buf , char format , arg_list) Example : char s[20] ; 1.nt nl , n2 ; sscan f ( " hello 1 0 20 " , " %s %d %d ", s, &nl, &n2); Thi<; assigns hello to strings and 10 and 20 to nl and n2 respectively. 5-32 / v1?o'11 C Programmmg 10. Array of Strings • · al array. This is often required in applicatio An array of strinos is a two d1mens10n ns dealin ~ a list of names, etc. lw % An array of strings can be initialized. Example: 11 char c i t i es ( 4 ] [ l 0 ] = ( "Pune , "Mumbai", "Delh i ", " Ch e nnai " ); They are stored as: O 2 3 4 5 6 \0 cities [OJ p u n e \0 cities [1] M u m b a i cities [2] D e I h i \0 cities [3) C h e n n a i 7 89 \0 In the following program, we will accept 'n' names and sort them alphabetically: Q Ii;*;";ni71'us."'.': :t:rat::-e::-:s'."'a:=-:arr n = a:-:-y'."'o:~f~s=tr1-:-.n:-:g:-:-s-:*-; / - - - - - - - - - - -- - --------.. #include<s t dio . h> main () { char names [ 2 0) [ 3 0 ) , temp [ 30) ; int i , j , n ; print f (" Ho w many na mes ? : " ) ; sca n f (" %d" , &n) ; I* Accept names */ for(i =0;i<n ; i t + ) / *list o f 2 0 na mes */ { p r intf("Ente r name %d ," i+l) ; gets (list [i)) ; /* li s t [ i ] i s the name o f the Fh st ri ng */ ) I* Sor ting* / f o r(i=0 ; i<n-1 ; i++) for(j=i+l ; j<n ; j ++ ) ; i f(strcmp(name s[i] , names[j]> 0) ~tr c py(temp , names[i]) ; ','"u:py /names[i), names(j]); / ,) 6 \ Afra; s ar.d S:r ".•;p l'IIJH \ 5-33 strcpy (n ames [j] , temp ) ; sort e d List r / } ·sp l aY / "' DJ. " The s o rted name s are" ) ; p\JtS ( . <n . i++ ) ' r ( i === Oi i fo (names [ i]) ; -=- pt.1tS - - - - - - - - - - - - - - - - - - - - - - - - - :'ir: 11. implementation without Standard Library Functions d pointers are very closely related, since a string is an array the name of the srrirnz is a strings an · ointer to the string. In this section we will see some functions on strines. constant P ... Find the length of the string. g int 1ength(cha r *s) int count=O ; while (*s! = ' \ 0 ' ) count++; s++ ; re turn count ; main () char str[80] ; gets (str) ; Printf( "The length i s %d" , lengt h(s tr )) ; -}- - - - - - - - - - - - - - - - - - - - - Q 5-34 I 00 UISIOII C Programming st Copy one string to another and return the copied ring. .. 2. Q -- -- -- -- -- -- -- -- - char* scopy (char * s2, cha r* s1) char *t=s2 ; while (*s1 ! = ' \ 0 ' ) { *s2=* s1 ; s1++; s2++; *s2= ' \ 0 '; I termi nate copie d s tring * / } retur n t ; / * return copied strin g* / main ( J { c har sourc e[20] , targe t(20) ; gets( sou r c e) ; puts( scopy (targe t , sou rc e )) ; Convert a string to uppercase and return the converted string. .. 3. Q- -- -- -- -- -- -- -- ---- c har * suppe r(cha r *s ) c har *t =s; while (*s ! = ' \ 0 ') { if (islow er (*s)) t o upper (*s) ; s ++; retur n t ; J main () I c har s tr ( 8 0 ] ; g ets (str) ; pu t s (suppe r ( st r)); ~--- -- ---- -- -- -- -- --, V Arrays and Stnngs 5-35 111~•1 \ d progra ~m :..:.::... s_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ __ soive~ ~ 1 -w--'-r:i~t·e a C program to find the largest number from 3 x 3 t . . ma nx. ~g Jtit"lcl ll cte<std io . h> !1lait1 () I . nt m, O , c , d , mat r ix [ 3 ] [ 3 ] , maximum ; l. . f ( " Enter the elemen ts of matrix \ n " ) ; rJ..n t P -o ,· c<3 ; c++) f or (c- ,' 1 \ I I ...--_-A_pr ___2_0_1_8___4--,/>- j \ I .{ for (d= O; d<3 ; d++) scanf( " %d ", &matrix [ c][d)) ; !., ~a x imum= matri x[ O] [OJ ; for(c = O; c<3 ; c ++) for (d= O; d<3; d++) f ~E~he elemenffi of , 1 45 56 I 2 56 48 : l 10 15 98 Maximum element l matrix is 98 l 1.,, , l : l in j l ~ ................... ................... ........-- ·-----~ ~ - if(mat ri x[c] [d) >maximu m) max imum = matrix [c ] [d); printf ( " Maxirnu m elemen t in matrix is l d \ n ", maximum) ; return O; ....:........:....___ ___ ___ ___ ___ ___ ___ _ Q ~ 2. Trace the output and justify: main() { static char str[ ] = "Malayalam"; char * s; s = str + 8; while(s >= str) { printf("o/oc", *s); s- - ; , --- ' ,' 1 \ ______:, j' ' , Apr. 2018- 4M ,_ -: 5 3 / ()4, - s VIIIOII C Programming 51>/1aion str [ M / a I I / I Y / a a str(?] str[6] str[S] str[4] str[3] str[2] str(1] str[O] I I I a str[9] str(8] I m I ~ · · '==~Lr+ 8 poims to last locati on. i.e. str[8] A\ 111 while loop character is displayed by every iteration and s is decrememed by one lo Ourpur: .,. J. , ma layalaM :' Trace the output and justify: ma111( J Apr. 2018- (Apr.20 18) I char* a(5 ] = {"GOOD", "BAD", "UGLY". "WICKED", "NICE"); prim!'(" % s\n", al0JJ; prilllf( " '½ <;\n ", ·• ( a+ 2)); print! ('''½ c\n", * (a[2 1+ 2)): pnntf( " 1k ..,\n", * af3]); pnnlff'% c\n", ... (a[J j + 2)); Solurw11 Arr.t) of ..,tnng.., 1:-. g1vi:n as a[OI a[ 11 ! G I O I O I D I \0 : B D \0 A 1 I a[2] L1 G L af 3] W af➔ ] Ju• ur . cation GOOD I ( ,I 'r Y.f( Yf [) ( ~ ----K E C E \0 C _... Y 1 \0 ' D \0 _, , 1 '-: 4M'. __ ,, Arrays and Strings ~ write a Oe \ UIIIOII 5-37 'C' program for multiplication of p x q matrix. 4. , ... --,, ,_________, , 1 \ \ Oct. 2017- 4M' .. ___ ., p , q ' c , d , k , sum=0 ; n . t rn ,· r s t' [ l O] [ 10) , seco nd (l0J [ 1 0) , multiply [ l 0J (10).' 1n ,int fJ. ( " En ter n o . o f r o ws and columns o f fi r st matri x \ n " ) ; print f ,, %d %d " ' &m, &n ) ; scanf ( ( " En ter elements o f first mat r ix \ n " ) ; nr.i.ntf . c<m ; c +T ) ) (c::: O, rf o r ::: O; d < n ; d ++ f o r (d ( " %d " , &f i rst ( c l [d ] ) ; f \ ri" ) ; scan . t: f ( ,, w~nte r no . o f r o ws and columns o f second matrix po n f ( " %d %d ", &p , &q ) ; scan \ ") · b , · f ( n ! ==p) e mu 1 t1plied with each other n ; 1 . _ f ( " :-h e mat. rice s c a n t. o r1 nc. e lse r·" - -&( "E ~ ~ e r e l e me n t. s o : second mat rix \ n " ) ; ·· P-c ++ ) .: - y (~-. ..._ - ....,, ,• c<p ; , ; : ; ('.:i==v ; d< q ; d T+ ) d] ) ; . econd[c] &s ", ~d " ' sea .. -& : c.:-(:: == ; ::<~ ; c -- ) : :.r ~ = 8 ; k <p ; k -- ) s~~ = surn- :~ !" st.'.:: J [k l ~ seco nd [k ] [d] ; p:::..:"'-:1 " ?:-duct. o : the matri c es : \ n " ) ; . ! (~c ; ~,r ; c -- ) : :: d= ; d<q ; d· - ) p ! :. :1 t. !: " ~ j t. " , r:-:.: : t. .:. p l y [ c ) [ d ) ) ; , I {),:, 5-38 / UISIOII C Programming ······················································································································1. Outpur Enter no. of rows and columns of first matrix 23 Enter elements of first matrix 159785 Enter no. of rows and columns of second matrix 32 Enter elements of second matrix 459873 Product of the matrices: 112 72 135 114 • ••• • • ••• ••••• • • • • •••• •• •• ••••• •• • •• • • ••••••••• • •••••• • ••••••• • • • • •• •••••• •• • • • ..... ... . . ... . .. .. . ...... . . . ...... . . . . 1 » 5. Trace the output and justify: --, ' ,' 1', , main() I I I { r - - - - - - -_.:_I \ char s[]= "Happy New Year"; printf("%s", s); printf("\n%c", s[3]); printf("\n%c", s[8]); Solution String s is stored as, s[O] s[1] s[2] s[3] s[4] s[5] s[6] printf("%s", s) displays - Happy New Year ~[3] - p 1., !8] - w Output · Happy New Year p w s[7] I Oct. 2017- 4M '~--· s[8] s[9] s[10] s[11] s[12] s[13] s[1 4] Write a program to concatenate two strings. 1 strl[25] , str2[25] ; . ' == o, J == 0 ' iI1t l . f{ " \ n Enter first string :" ) ; print ets(s tr l) ; g ·ie(strl[i· 11.- ' \0 ' ) cna r . Apr. 2017 - 4'/ whl i++ ; while( st r2 [ J') I. == ' \0 ' ) s trl [i] == str2[j) ; j++; i+ +; s t rl[i) == ' \0 '; printf ( " \n concate nated string is %s ", strl) ; return 0 ; ...:..--------- ---------- ---------- --g r,==- .. 7. Trace the output and justify main() ,,- 1-- \ ... I -r--A-pr-._20_1_7__-4--~ - char sl [] = "Kolkotta"; char s2[] = "Pune"; strcpy (sl, s2); printf("o/os", sl); ... -j I 5-40 o~ I u1s1on c Programming Solurion Output: Pune strcpy(s 1. s:2) copies second string into first string. :. Output is Pune . .. 8. Trace the output and justify main() --- r - - - - - - 1: 1\ I ' I \ I Oct. 2016 - M,, __ ,, 4 char string[] = "HELLO WORLD"; int m; for(m = 0; string [m] ! = '\0'; m++) if((m % 2) = = 0) printf("o/o c" , string [m]); Solution In this program all odd numbers alphabets in the string are skipped • Output is HLOWRD Trace the output and justify main() { int c, d; char string []= "A BC D"; printf("\n\n "); for(c = O; c <= 11; c++) { d= c +l ; printf("o/o-12,* "s\n", d, string); } printf("\n"); for( c = 11 ; c >= O; c- - ) { \ Oct. 2016-4M ', . . , I d== C+ l ; printf( "- 12,* "s\n", d, string); } . f("\n")· print ' ·on Sol,,tz · f statement m · b rogram , pnnt oth loop is not proper k-. . , • ai ven P . . ~a use n prr,·.iue r ,l, o ~ ar.:..: .:: 1" we r, d string out of one 1s mteger and other is characte b w _ entifier , . . r ut comro1~tnngder-,;-::?=' ·. . ::-:: or 1d . d o/os for stnng also control stnng fonnat is not given p nt an rope rl ". ~~1 . ~ 10, Trace the output and justify: #includ e<strin g.h> #includ e<ctyp e.h> int rnain(void) :1 ,______ ____\ ,1• Apr. 2016- -!.I.'· - - - , int length i; char string[ ] = "This is A string"; length = strlen(s tring); for(i = 0, i < length; i + 1) { string[i ] = to lower(string[i]) ; } printf(" o/os\n", string); getch() ; return 0 ; Solution The given code will display "this is a string" (i. e. all characters of given string will be displaye d in lower case). strlen() functio n will give the length of string and toLower0 function converts the characte r to lower case. In for loop each character of string is converted to lower case using tolower O function . So the output. 5-42 I (},, UISIDn C Programmmg Exercises A. Short answer questions: I. What i-. row major representation of an array? List an)' four standard string library functi ons. 3. What is the difference between array and ordinary variable? What i-. the use of strrev and strcmpi ? 5. Define row major and column major. 6. Li-.t -.tring manipulation fu nctions. 7. Define string. Which character is used to temlinate the string? 8. What i-. an array? Give an example. 9. Define '> lring with an example. 10 Whai 1·s 1hc difference between the S's in these two expressions - int num [5] ·, nurn [5 : . I I .! II f:.xplarn strlen() and strcpy( ). 12. Define array. How is it declared? What 1.., the Prototype and use of strcmp()? 1-l. What are the advantages of Array? 15 \\ hat 1.., ..,tnng > State at least -l function!) of ,tring with c;ymax 16 What t'> -.,1r,tr( l function ·> 17 l::x pl..1111 ~pnntl anJ ,..,cant \.\- 1th example. H. Long anliwers questions: /~ Marl. Deline arr,1} Hl \\ 2D arra)" are repre~enteJ m memor}' \\ me 1 ( prol!ntm h> ,h.Lept IO number, from u,er. ,tore the-.,e numtier.., m ,111 JIT:J~ Jr. m.ille I number ffl)ffi ,IITcl) Arrays and Strings 111~•11 \ 5-43 'C' pro gram to calculate length of string w·th . 1 · out usmg standard library function . . an arra y? Wh at are the limitations of array? What is .. wnt. e •C' pro gram to calculate sum of non-diagonal e1 . ements of n 'i'. n matnx. . d the outp ut Write a 5. f10 6- rnain O cha r S 1[] = "FY BCA SYBCA TYBCA"; cha r S2[ 20]; cha r S3[ 20]; sscanf (S l ,"% S %S" , S 1. S2, S3); printf< "o/oS, %S, %S", Sl, S2, S3); 7. Explain memory representation of two-dimensio nal array. Explain U!,e of followin g standard library func tion s: strlen(), strcmp(), strcatO, strcpy(), strre v( ). 9. Write a 'C' program to print arra y elements in reve rse order. 10. Write a 'C' program to calculate sum of majo r and minor diagonal elements of m x n matri x. 11. Write a 'C' prog ram to check if given string is palin dro_me or not. 12. Write a 'C' pwg ram to displa) transpose of a matr ix. 13. Write :i program to :iccept two strings and print common characters from both the strings. 5.4 4 I ('.'./@ UISI OII C Programm ing ed in Previous Exams sk . tions a Ques PJMffftffl What are lim itat ion s of array? 1. 2. De fine stri ng with exa mpl e. 3. mpl e. Define 2-d ime nsio nal array. Gi ve exa 5. De fine st1ing. Give exa mpl e. arrays in memory? Wh at is array? Ho w to represent 2D- 6. Wh at is an array? Give an example. 4. 8. mp()? Wh at is the prototy pe and use of strc strcat(). Gi ve syn tax and use of strlen() and 9. ensional array. De fin e array. Giv e exa mp le of one-dim 7. O•Mtatffl num ber fro m 3 x 3 ma trix . Wr ite a C pro gra m to find the largest 1. Tra ce the out put and jus tify : main() { "UGLY", "W ICK ED ", "NI CE "}; cha r* a[S] = {"G OO D", "BA D", pri nt[ ("% s\n ", a[O]); pri nt[ ("% s\n ", *(a + 2)); pri nt[ ("% c\n", * (a[ 2] + 2)); pri nt[( "% s\n", * a[3 ]); pri nt[ ("% c\n ", * (a[ 3] + 2)) ; } 3. Trace the out put and justify: ma in( ) ' sta tic cha r str[ ] = ''M alayalam" ; char* s; str + 8; while( s >= str) >= ( pn mf r %c", ~s); 1,,- - , (Apr. 20 y . a 'C' program for multiplication f O p )( q lllatrix . write J · the output and justify: frace rnainO Arrays and St . nngs o.\ 5.45 v11101 ~ IQ_ct. 201Zl { bars[ ] = "Happy New Year"; " s)· crintf( "m ' -10s ' printf("\n%c"' s[3]); ~rintf("\n%c"' s[8]); Q } n 6. 1. 8. .§] Explain the meaning of the following functions: strstr ll. 1, strlen tolciwer IV. iii. strrev strcpy v. {Apt. 20111 Write a program to concatenate two strings. Trace the output and justify: LApt. 201_Zl main() IAp1. 20,n ( lfil char sl [] = "Kolkotta"; char s2[] = "Pune"; strcpy (s l, s2); printf("%s", sl); 9. Trace the output and justify: : main() ( LOct. 2016J char string[ ] = "HELLO WORLD" ; int m; for(m =O; string [m]! ='\O'; m++) if((m % 2) = = 0) printf("% c", string [m]); lll ) lO. Trace the output and justify: main() ( int c, d; char string []="A BC D'.'; (Oct. 2016) 5-46 / 00 UIIIDII C Programming printf("\n\n"); for(c = O; c <= 11 ; c++) { d = C + l; printf("o/o -12,*" s\n", d, string); 11. Trace the output and justify: #include<string.h> #include<ctype.h> int main(void) { int length i; char string[ ] = "This is A string"; length= strlen(string); for(i = O,i < length; i + 1) { string[i] = to lower(string[i]); } printf("o/os\n", string); getch(); return O; 12. [Apr. 20l!J Trace the output and justify: main() { char *m = "ABCD"; printf("o/oC .. .", ++ *(++p)); printf("o/oC ... ", * ++P); 00 UISION unit 1' Functions introduction . . are the buildi ng block s of C and are central td C programming and ro the philos opny funcuons . am design . of C pro gr . the functi on where execu tion begins. The other functions are execu ted when c.he\· arc rnainO 18 . ~ ·rectly or indire ctly by mam. called d1 . mandatory to have a single main() function in every program. It IS What is a Func tion? The program develo pmen t cycle includes problem analysis, problem definition, design and coding. The code is a set of instructions in a logical sequence, which perfor ms the specif ied task. 'Real world' applic ations progra ms are large and _complex. Therefore it is more logical and convenient to break -up the task into smaller, compact and more manag eable modules. called functions. ~-- ' ,' 2 \ ,. Definition I A function is a named , independent or self-contained block of statement s that perfor ms a specific, well defined task and may retum a al . g progra v ue to the callm m. 6-1 r--------, Ocl 17116 - 2M I ' Define function. Give example. I ' - - ~,. ,