C Material - Ratna Reddy Sir PDF

You might also like

Download as pdf
Download as pdf
You are on page 1of 59
UNIT -i Assembler, Interpreter, Compiler, Loader, Linker aAssembier: ‘Assembler is software that converts a program written in assembly language into machine code. ‘There is usually one-to-one correspondence between simple assembly statements and machine language instructions. Since the machine language is dependent on the processor architecture, assembly language programs also defer for different architecture. Interpreter: Interpreter performs line by line execution of the source code. Interpreter reads source code line by line, converts it into machine understandable form, executes the line, and then proceeds with the next line. Some languages that uses interpreter are BASIC and PYTHON Compiler: ‘A program written in high level language has to be converted to a language that computer can understand i.e. binary form. Compiler is software that translates the program written in high level language to machine language. The program written in high level language is called source code and the compiled program is called object code. The compilation process generally involves two parts. Breaking down the source code into small pieces and constructing the abject code. The compiler also reports syntax errors, if any in the source program. Source code > inceneege Object coule Caspr Linker: A linker is a program that link several object, modules and libraries to form a single executable program. Loade Loaders are a part of operating system that brings an executable file residing on disk into memory and starts it running. Source program Object ie] Compiler |=] code Jy Unter Memory F Loader Notes Prepared by T.RatnaReddy. Associate Professor, CBIT Mol le No: 99866 66778 Page 3 There are four types of number systems ,depending on the number of digits used(radix), to represent a number. The base or radix of a number system is defined as the number of digits that it uses to represent the number. ‘sno_| Name of number system Numbers used Radix or base 1. Decimal number system Otod 10 2. _| Binary number system Oand i 2 3.__| Octal number system. Oto 7 8 4. [Hexadecimal number system {0 to 9,A,B,C,D,E,F | 16 Decimal binary octal hexadecimal 0 ‘00007 [o 0 1 0001 1 1 2 oo10 [2 2 3 oot [3 3 4 0100 [4a 5 0101 [5 5 G 0110 “16. 6 Z Otit 17, Z 8 1000/10 | 8 9 i001 [aif 9 1c 1010 12 A a toil 43 [8 12 1100 14 Cc 13 1101 1s oD 14 1110 16 E ] 15. ait [a7__[F Notes Prepared by T.RatnaReddy. Associate Professor, CBIT Mobile No: 99856 66778 Page 4 Binary todecimar — | _1010142 = {ho 4x20=4 4X22 Ox2=0 axp=8 Ox2=0 41K 25=32 Octal to decimat 724% =( ho Hexadecimal ts decir! ABCs = (ho representation 2 0 AF 0001 0000 1010 1111 Technique: Covert each hexadecimal digi to a 4-bit equivalent binary LOAF yg = OOOLOOPOACIONL 12, Technique: Convert each Octal digit so ee 3-bit cequivaient binary representation se A1L G06 64 Notes Prepared by T. Ratna Reddy. Decimal to binary Decimal to Octal Decimal to Hexadecimal 2125y0 = (1211101) 2 123440 = { 2322)s 12349 = (402) is “ 8| 1934 16 [1234 i : S| 4¢ 2 1e6|_ 1 2 5 las s|_ 33° 2 16 13=D eg) EES | pecs) wwe fk ° 2 n Hexadecimal to Binary Octal to Binary Octal to Hexadecimal 7059 (), 1076s = he Technique: Use binary as ‘an intermediary Associate Professor, CBIT Mobile No: 99856 66778 Pages UNI Number systems - There are tour types of number systems ,depending on the number of digits used(radix), to represent a number. The base or radix of a number system is defined as the number of digits that it uses to represent the number. sno_| Name of number system Numbers used Radix or base i. | Decimal number system Otod 10 2. | Binary number system Oand 1 2 3. Octal number system. Oto 7, 8 4. [Hexadecimal number system {0 to 9,A,B,C,D,E,F | 16 Decimal [binary | octal__{ hexadecimal 0 0000 "| 6 0 1 001 | 4 1 2 oo10 | 2 2 3 oo11 [3 3 4 0100/4 4 5 o1o1 5 5. 6 0110 6 6 7 o1it [7 7 8 1000 [10 [8 3 1001 fit [9 1C 2010 [12 [A aa 1011/43 [Bb 12 ai00 [44 c 13 a0. [a5 Oo : 14 iiio [16 15 aii1 [17 Notes Prepared by T. Ratna Reddy. Associate Professor, CBIT Mobile No: 99856 66778 Page + UNIT -I Binary toueuima | Octal to decimal | Hexadecimal ts devionst 30101) = (is a= he ABC = (ho 7x20=4 1x2=2 ox2=0 4x20=8 ox2o 1x28 32 mL Decimal to binary Decimal to Octal Decimal to Hexadecimal 125, = (1111101) > 123410 = ( 2322)e 1234, = {4D2) as 8 1as4 16 [1234 : 5 s{ 184 2 we, 7 2 : : #138 2 16 a i3=D , tLe 3 eo 4 nl ° 2 q Hexadecimal to Binary ‘Octal to Binary Octal to Hexadecimal AOAF 16 = (2 7055= (ez 1076s =( is Technique: Crnvert each hexadecimal | | Techniques Convert each Technique: Use binary 2s digit 0 a 4-bil equivalent binary Octal dig to a Shit vpresentaton “ equivaient bonary an intermediary representation 1 0 AF ce 400 164 fm 4 0003 G000 1010 4111 LOAF {g = QOOLOCPACIONLII, ea Notes Prepared by T.Ratna Reddy. Associate Professor, CBIT Mobile No: 99856 66778 Page 5 F Peat yin To coment fecinu faction 10. Freciautl to binary Multplication process integer pact & Oy “ + ‘ 6 o! - e oe OSX ISLS ba s, + yy OSX 2= 10 1 . : we Therefore 0 6875,.= 0 10N © Algorithms and flow charts: SED IN Algorithm is 2 step by step process to do a particular task. The steps must be clear and definite. By following the steps one should get the final result. Flow chart is the pictorial representation of ani algorithm. Flow chart uses various geometrical figures to represent the operations and arrows to ‘show the direction of flow. Following are the commonly used symbols in flowcharts. Startystop Cc / 7 inputyoutput Processing S ‘Checking/decision making oO ey t | Arrows to represent cirection — of flow Looping Connector Aphabets: Uppercase letters A to Z Lowercase letters a toz Numbers: 9 to 9 Special characters: tS NMI? 1,. rp eCdLILC it fost Sar euble —tone shot signed amined while do for ask caminue ach case sto sale entern goto etm dint won che eal vote dfs wkd contrat enum + Keywords serve as basic building blocks fer Program statements. + Each keyword has a special meaning in C, + All these keywords are in lower case letters. ‘As capital or upper case letters and lower case letters are significant in C, all these keywords must be used in lower cases, + These key words names should not be used in function names or variable names or identifiers. Keep this list with you for reference, whenever you write programs. + __No gap should be left in between the letters of a single key word, while using. + These key words are also called as reserved words or vocabulary for the language. Notes Prepared by T. Ratna Reddy. Associate Professor, CBIT Mobile No: 99856 66778 Page 6 The words, winel: ave defireu by user, are user defined words. They can be for variable name function name 1. Itmust start with an alphabet. 2. Maximum number of characters should not excess 8 (excess are ignored) 3. Second character on wards alphabets, digits or underscore’s can be used, 4. No special characters are allowed expect underscore. 5. It cannot be a reserved word. Valich Invalid ‘abhilash ape sum ded product PVN. P20 abe123 Rama rao ab_12_cd abcd hyderabad abcd (first Bare recognized) | suo MEMORY CONCEPTS AND DATATYPES Data type 1s defined as the (ype of valle that can be stored in a variable EXAMPLE int as vi ‘values in “abut not float float b; Variable ’b is oftype float we can store only integer values in ‘a’ but not int There ure several data f int inf Jong unsigned @B) 4B) 2B) Aint: Wakes 2B of memory space that is 16 bits. First bit is sign bit and remaining 15 are magnitude bits iT} sign mageitude the sign bit is zero it -ve magnitude, ‘tve magnitude. f the sign bit is 1 itis Maximum integer value is 2'°— 1 = 32767. Minimum integer value is-2"° = 22768 “Ths integer ranges om 32768 to 32767 2 long int: To representa value more than 12767 ‘omg is nse C15 estension to leper i takes 4B of amemory spce tha s 32 bts. Ftst bi ssh bi at ren Tracie tetas Mananonun value of fang uneyer vale 1s 2° ~ 1 3 unsigned int It takes 2B of memory space that is i bits. There is no sign bic is sign bit. AML 32 bits ate rnagnitude bits ‘Maximum value unsigned integer is 2" ~ 1 = 65535. Minimum value of unsigned integer is 0. ‘We cannot represent -ve values in unsigned character float float double long double (48) (8) (108) 4. float : 1 takes AB of memory space. First 26 buts ‘are integer pant and next 6 bits are for fractional part. Decimal point isassuned after 26" bit, [tis not stored in memory 2XXHHONK JX * 390 x9 0001 26 s Notes Prepared by T. Ratna Reddy. Associate Professor, CBIT Mobile No: 99856 66778 Page 7 UNIT-I eg ati ' Fir 2 bits are rekeger part and Heat 12 tts a for fra tial part. Decimal point is assumed after 52" bit. tis not stored in memory Sf ‘i . S.long double: It takes 108 of menue see, First 65 bits are integer part and next 15 bits are for fractional part. Decimal point is assumed after 65" bit, char signed char unsigned char (18) (1B) Zeunsianed chor: 1 rakes 18 of memory space that is bits. There iso sign bit, all 8. are magritude bits. Maximum value is 2° ~1= 25S,minimum value is 0. Range of ASC! values is from 0 t0 255 B.signed charfor} char: It takes 18 of memory space that is 8 bits. There is one sign bit and 7 are magnitude bits are magoitude bits. ‘Maximum value is 2” ~ 1 = 127. Minimum value is ~2” = 128 e casti Conversion of one data iype ta same other datatype is knew as type castung. That is Conversion of int 10 float float to ant to char so on is called type casting, L. implicit type casting “Tepe casting is dane by system, 1 inta = 10.8; float value is type casted to int so a= 10, Bis ignored. 2 Bloat b = 25; int value és type casted to float so b= 25.0 int value is type casted to charso that ch = A. Aint ="2'; character is type casted to int sok = 90, ASCH value of 2 2. Explicit type casting, Type casting is done by programmer. 4inta=7,d=2; printt (%f, (floatja/b); = 7.012 35 Variable ais of type, its type casted to float so ‘a’ becomes 7.0 . The value of ‘a’ continues to be 7 in the rest of the program ‘Thus type casting is not for entre _prograttr albis 3. 7 (loatjalb = 3.5 al(foal) b = 7/2.0= 3.5 be sole Seo ge . 2 floata=9.8.b=5.9; printt C%d", Gna GND); =9%5=4 Variables a and b of type float They are type casted to int They become @ and 5. 8 % bis error since %is integer operator. So they must be type casted to int. int a; + itis declaration statement, (int) a is type casting, Basic Input and output functions ‘etinsf) Function print() function Is used to display a string or values of variables using the standard output device(monitor). It has the following forms printf(“control string”); printf("control string” vi,v2,..vn); where vi,v2 are variables whose values are to bbe displayed on the screen. Control string is the format string which represents the format specification datatype format specifier int %d . float xe ae) char %e a string Hs 4 Notes Prepared by T. Ratna Reddy. Associate Professor, CBIT Mobile No: 99856 66778 Pages Examples 1. print ("5id"x); to display integer value 2. printf("%"" a}; to display float value 3. printf(“the result is %0".x); scanf()_ Function sscanf() function is used to readinput values of variables. Using the standard input device(keyboard). {is an input function. It is cal by address function. We must send address to scanf but not variable 1Whas the following form scanf(‘fonmat string’,8v1,8v2,... &vn); Where v1, v2... are variables whose values are to be read from the keyboard. fxemples 1. scanf("%d",8x); to read integer value scanf("%f",Ba}; to read float value scanf("%c",&ch); to read char value scanf{"%s"name); to read a string scanf{"%d9it" &x,8a); to read an integer value. and a float value. Uf To find the sum of two numbers yn include void main() ( : int x,y,sum; printft" Enter two numbers\n" scant" %d%4d" Bx By); sum =x4y; printf("the sum of 26d and %d is %d\n", xy,sum); 1 s. Format | Remert No | Type specifier 1 | cher et | Signed character 2. [int Ki Signed nteger 3 int ed Signed integer in decimal numiber 7 system _ 4. [unsoned [%o Unsigned integer in int ‘octal number system 5 Fursigned | Su Unsigned integer in int decimal number system & [unsigned | x Unsigned integerin int hexadecimal number system 7 [unsigned | %X Unsigned integer in int ‘hexadecimal number system, &_[Teng int | a Signed long 9. | shortint | séhd____| Signed short 10. [unsigned | %ku Unsigned long: long a - 1 unsigned [hu | Unsigned short short . - float = Sigsedinge prociion | float Re Signed singie precision - ine formai{exoonent| 14. | ftoar RE Signed single precision in_Efermatiexponent) 18. | float % Signed value either in e orf format a 16. [float %G Signed value either in E or Format 17 [double |S Signed double 2 precision float 18) sting % sting type Notes Prepared by T.Ratna Reddy. Associate Professor, CBIT Mobile No: 99856 66778 Page? "lev. Chart for if Snark tos fe topo Flow Chart for ifelse t L___T ‘ Flow Chart for while loop CT Flow Chart for do while loop Notes prepared by T. Ratna Reddy, Associate Professor, CBIT Mobile 99856 66778 Page 10 Flow Ghart for break Ie digits of given number (START) "Notes prepared by T. Ratna Reddy, Associate Professor, CBIT Mobile 99856 66778 Page 11 wl Ap START To DISPLAY | NO = peo ose fe 2. == and != are aiso calied equality operators 3. Relational’ operators are used to compare arithmetic, logical and character expressions. 4. Each operator compares its left hand side with the right hand side. The whole expression involving the relational operator then produces .a logical value. A togical value is either true or false. it evaluates to zero if the condition is false and one if true, /! To demonstrate relational operators #include void main() int a=20.b=10: printf("a= “id b=%din"a.b). printf" value of expression (a>b) is %d\n".a>b ). printf(" value of expression (ab) is %dln".asb ), ~soaypeintf(" valié of expression (a—=b)is %od\n". ab): OUTPUT: value of expression (a>b) is. 1 valve of expression (acb) is 0 value of expression (a=biis 0 Notes Prepared by T. Ratna Reddy. Associate Professor, CBIT Mobile 9985 666778 v 7 is stored in‘a’ and Value of a is compared result is 7. to 7 and result is true or talse. 3 ‘Operator behind ="is | Operator behind copy that is RHS is compare that is RHS is, copied to LHS variable | compared to LHS vanable Results are true or false. a™= band! same a=bandh=aare different = aare Logical Operators: 1. These are also called Boolean operators. There. are three logical operators && ||! 3. A logical operator is used to compare or evaluate logical aitd relational expressions ie these are used in combing one or more conditions. 4. && and || are binory operators and ! is a unary operator. 5, truth table for && tue && tne is true. If any expression is false 1t 1s alse. 6. truth table tor |j false || false is false. If any expression is true it is tme, 7. | operator is called negation operator. It negates 1c tme to faise and false to true Example for relational void main() \d logical Operators. int x=10,y= p= x>9; g = x>3 && y!= printf(“p=%d q: ( in tf“ %d\n",q); (x==10) && (y==10); “print %d\n "ai ouTPUT: q=l Page 14 rem 1. ++ and - -are calfed increment and decrement operators. 2. Increment operator add one and decrement operator subtract one, 3. These will operate only on variables. i.e. S++ is not valid. 4. If the operator appears after the variable, it is called postfix, then the value used is the value before it is updated, 5. If the operator appears in front of the variable, it is called prefix operator, then the value used is updated value. 6. Example x=at++ means x= a a= atl; x=++a means atl; ‘These are extensively used in for and while loops. When increment and decrement operators are not in an expression postfix and prefix have same meaning; ad Program 1 void main() t ‘ int i=Ly x=. + ist printt('Yod\n" a): ttt. printfit’'ed\n" i). yetx: printf("Yed %d\n"x.y) od Yod\n" x.¥). * printf("%ed\n".x): Program 2 Void main() intel printf("%d Sod Yod Ye ud Hod Wa" ARLE ELLE) & We printt("%d Yd %d Yd odin" LI i i HY Program 3 void main(), int a,b,c; a=b=c=0; cm ates ttb; printi("%d %d %d\n"abQ); OPERATORS i i | we obeae hy printf("%d %d %d\n",a,b,c); Output 1 cattat +b; printi("%ed tod %d\n",a,b,c); c=tta-b-; printf("%d %d %d\n"a,b,c); } it 02 14 03 Program 4 void main() { int x=Ly; YEH ox bx ec bat printh(od %dy,x); } ! The conditional operator contains a condition followed by two'statements or values. if the condition is true first statement is executed otherwise second statement is | :executed. The conditional operator is also called ternary operator because there are three arguments. Syntax: Condition "(expt (esp?) Example t to find the largest of hvo numbers #include void main() { int x,y, big; printf("Enter two numbers\n"); scan{{"%d%d" ,&x,&y); big = (x>y) ? x: y; print{(""big =%ed\n",big); } Example 2 dio find absolute value of a number #include void main() t int x; printf("Enter a number\n"); scanf{"%d" &x); X= (x>0) 7? x: -x; printf{"%d\n",x); } _acammamammmmnsammmmmnianmemammmammmmmimamaeieamnEE Notes Prepared by T. Ratna Reddy. Associate Professor, CBIT Mobile 9985 666778 Page 15 Example 3 ‘to display the rest: #include void mainQ) { int mark; printf("Enter your marks\n"); scanf("%d",é&mark); printf("you secured %s mark", mark>=60 ? "FIRST CLASS" :"NOT A FIRST CLASS"); 3 Example 4 /1 to find the largest of 3 numbers Hinclude void main() t int xy,z,big; printf{"Enter three numbers\n"); scanf("%d%d%d",&x,&y,&z); big = (x>y)? (x>z ? x:2) : (y>z Py 2); printf{"big =%d\n",big); } Comma operator: Comma operator is used to separate two or more expressions. The comma aperator has the lowest priority among ail the operators Ex: a=2,b=4,c=ath; Example 1 void main() ¥ , printh("%d %d",x,y); 1 } Example 2 “to swap two numbers by using comma operator #include void main() ‘ { int x,y,temp: x=20,y= Notes Prepared by T. Ratna Reddy. Associate Professor, CBIT Mobile 9985 666778 The order in which various operators are performed is known as hierarchy of operation or operation precedence. Someof the operators of the same level precedence are evaluated from left to right or right to left. This is called associativity. Precedence | operator assoctativity order i O_LL= Left to Right 2 ++ - unary) | | Right to Left ~ * & sizeof 3 *7 % Left to right 4 + Left to right 3 <> Leff to right 6 < Se = Left to right 7 Left to nght 8 Left to right 9 Left to right Lo Left to right ui Be, Left to right 12 ui Left to right 13. 2 RtoL 14 eS R tol Is . (comma Left to right operator) 1 a=b= Right to left evaluation for assignment operators. “0° is stored inc .b . a. This is called multiple assignment Le. same value stored in different variables. ‘This equivalent to a= 0: b= 0: ¢=0: 2. a%vm=3+4*2; a=a%(3+4*2) = 20 % (3+8) =20%11 =9 3.if a=4, b=5, c=6 evaluate a t= b += ct+=7; 0 b 22} (18) Page 16 Control! structures Control structures conditional unconditional co i . break continue goto selective iterative THE if STATEMENT Introduction ‘The if statement is the first selection structure. ifis used when a question requires a yes or no answer. Syntax ‘The general format for an if statement is: if ( condition ) simple or compound statement, Following are the properties of an if statement: 1. If the condition is true then the simple or compound statements are executed. 2. if the condition is false ii dues not do anyihing 3. The condition is given in parentheses and must be evaluated as true (nonzero value) or false (zero alue). 4. Ifa compound statement is provided, it must be enclosed in-opening and closing braces. “THE if-else STATEMENT Introduction . When we want to take actions based on the outcome of the conditions. (true or false}. then we can use the if-else statement. syntax The general format for an if-else statement is. it (condition) simple or compound statement #/ s1 else simple or compound statement. H!s2 If the coladition is true then the s1 part is executed and if the condition is false then the s2 part is. executed. For example. if (a>) print ("big numberis %d’, a); //s1 else printf ("big number is %d", by, 1/52. : if ais greater than (b) then s1 is executed. Otherwise s2 is execute —————————————— Notes prepared by T. Ratna Reddy Associate Prof. CBIT Mobile : 9985666778 Page 17 I odd or even *] #include main() { printf("Enter a numbern"}; scanf("%d", 8x), if(x%a==0) printf("EVEN\a"}; else printf("ODD\n"); 3 P* largest of twonumbers */ Ainclude main() { int xy, bigs printf ("Enter two numbers\n" scani("%d2d",8x,8y) ifGoy) big =x; cise big = yi printf("bigexd\n", big }s } [* absolute value *) & finctude main() { int x printf("Enter a integer\n”), scanf("%d"Bx), if(x mainQiays { int %Y5 printf("“Enter x and y coordinate\n"); scanf("%d%d",Bx,8y) if(x>0 && y>0) printf("FIRST QUADRANTIN"}; Notes prepared by T. Ratna Reddy Associate Prof. CBIT tures: Haro && you) printf("SECOND: QUADRANT"); if(x main() { int x,y,2,big, printf("Enter three sides\n"); scanf("%dxd%a", Bux, ey, 82); if(xeyoz &&y+>K BE Z+K>y) iuspringf("torm a triangle\n" else print#("does not form a triangle\n"); } I alphabet or not */ #include main : { char ¢by printf("Enter a characterin"); scani("Ec" Sch if(cho= "al && che"2!) printf("alphabet\n"); else printf("not a alphabet\n"}; } }* vowel or not */ #include main() { char ch; printf(""enter a alphabetin"); scanf("%c",6ch}, (ches "a" I] ch=s'el|ch=="jch=='olfeh==u") printf(*vowel\n"); else printf(""not a vowel\n" } Mobile : 9985666778 Page 18 Control structures THE if-else if STATEMENT Introduction If we want to make many decisions, then we can use the if-else if statement. Syntax The general format for the if-else if statement is: if (condition 1) c i ‘simple or compound statement //'st 3 else if (condition 2) simple or compound statement i! s2 else if ( condition 3) simple or compound statement # s3 else if {conditon n ) ™ simple or compound statement sn a bbe If condition 1 is true then s1 is executed. if condition 1 is false and condition 2 is true then s2 is executed. The else clause is always associated with the nearest unresolved if statement. ._¢ Points to Remember ay We can use if-else if when you want to check several conditions but still execute one statement 2 When writing an if-else if statement. be careful to associate else statement to the appropriate if statement. 3. We must have parentheses around the condition. 4. We must have a semicolon or right brace before the else statement. THE switch STATEMENT Introduction We can use a switch statement when we want te check multiple conditions. It‘can also be done using an if statement but it will be too lengthy and. difficult to debug. Syntax ‘The general format for a switch statement is switch(integer expression) f case %: statement; break; case 3 statement; break; Example of a case constant expression and column: switch (10) case 0: printf ("Number less than 10"); 7A break; case 1: printf ("Number less than 20"), B break; ee Notes prepared by T. Ratna Reddy Associate Prof. CBIT Mobile : 9985666778 Page 19 Control structures case 2:printf (Number lees than 30"! 4 break default: print ("Number greater than or equal to 40"), D break; } Explanation 1. ‘The switch expression should be an integer expression and, when evaluated, it must have an integer value. 2. The case constant expression must represent a particular integer value and no two case expressions should have the same value. 3. The value of the switch expression is compared with the case constant expression in the order specified, that is, from the top down. 4. The execution begins from the case where the switch expression is matched and it flows downward. 5. In the absence of a break statement. all statements that are followed by matched cases are executed. 6. If there is no matched case then the default is executed. You can have either zero or one default statement. 7. In the case of a nested switch statement, the break statements break the inner switch statement. Point to Remember 1. case constructs need not be serial. 2. characters can be used. 3. combination of integers and characters is possible. 4. default is optional. 5. Brace in case block is optional Hswitch 1 // to disrlay name of the day finclude void main() 4 int day; printf{‘Enter day number\n"): scant("%d", &day); switchiday) case l: ptinti('monday\n"): break: case 2: piintf("tuesday\n"): break: case 3: piinit('Wwednesday\n'); case 4: printt(‘thutsday\n"); break; case 5: printi("friday\n"); break; Notes prepared by T. Ratna Reddy Associate Prof. CBIT we . O M4 ¥), printt('saturday\n"}: beck: case 7: paintt(’sunday\n'}: break: default printf Wrong entry\n"); } a ) . ¥ T/switch 2 a 110 display the gender #include void main() S ( y char ch; printf("Enter your gender\n'); scanf|"%c",&ch); switch{ch) { case 'm': case 'M" printf("so you are a male\n"}: break; Page 20 “shesiiniaiine vielen tine lasioesinn a ao i { une F printf{’'so you are a female\n“} break; default: printf(’‘Wrong entry\n"); } } Hswitch 3 // to display the given number in words include void main() { int num digit.temp.rev=0; printf(’Enter a number\n"}: scanf['%d",gnum); temp=num; while{num|=0) { digit=num%10; rev = rev*10 + digit: num=num/10; } while(revi=0) : digit=rev%10: print{((ONE "): break; case 2: printt(TWO"}, break: case 3: printt( THREE "); break: case 4: printt("FOUR "}; break; printf ("FIVE"); break; case 6: printf("sIX "}: break: case 7: printf{'SEVEN "); break; Control structures - san soit . case @: printf((EKGHT "): break; cose 9: printf("NINE “); » break: case 0: printt('ZERO "}: } rev=rev/10; } while(termp%10==0} { ‘printf('ZERO"): temp=temp/10; yo ie } Lswiteh 4 | 11 to-do mattemattcal operations Hinclude void main() { int option.x.y do { printf(’Enter two numbers\n"): scant("%d%ed".8x.8y}: printi("l adition\n2.substract\n3.muttiply\n4.divide\, . ns.exif\n"): printf("Enter your option : "}; scant("%d".&option); switch{option) { case |: Printt(‘%Sd + %d = %d\n".xy.xt+y]; break; case 2: plinti('%d - Sd =%d\n"xy.x-y}; break; case 3: printf("%d * Sd = Bd\n"xy.x*y}: break; case 4: printf("%d /2d =%d\n".xy.x/y); break: Jwhile{option!=5); } Notes prepared by T. Ratna Reddy Associate Prof. CBIT Mobile : 9985666778 Page 21 Control structur es THE while LOOP tatroduction The while loop is used when we want to repeat the execution of a certain statement or a set of statements (compound statement). Syntax ‘The general format for a while loop is while (condition) simple or compound statement (body of the loop) For example, i=0; while (i<5) printf(* the value of i is %din", i}; +4, } Explanation Before entering into the loop, the while condition is evaluated. If it is true then only the loop body is executed. 2. Before making an iteration, the while condition is checked. If it is true then the loop body is executed. 3. It is the responsibility of the programmer to ensure that the condition is false after certain iterations; otherwise, the loop will make infinite iterations and it will not terminate. 4. The programmer should be aware of the final value of the looping variable. For example, in this case, the final value of the looping variable is 5. 5. While writing the loop body, you have to be careful to decide whether the loop variable is updated at the start of the body or at the end of the body.” THE do-while LOOP Introduction The do-while loop is used when we want to execute the loop body at least once. The do-while loop executes the loop body and then traces the condition. Syntax The general format for a do-while loop is do simple or compound statement while (condition); For example, i= 0; do printi{" the value of i is %el\n". i) izith: while (i<5); Explanation 1. The loop body is executed at least once. 2. The condition is checked after executing the loop body once. 3. If the condition is false then the loop is terminated. 4. In this example, the last value of iis printed as 5. rn Notes prepared by T. Ratna Reddy Associate Prof. CBIT Mobile : 9985666778 Page 22 _ Control structures THE for LOOP Introduction ‘The for loop is used only when the number of iterations is predetermined, for example, 10 iterations or 100 iterations. Syntax The general format for the for loop is for (initializing; continuation condition; update) simple or compound statement For example, for (i= O;1 < 5; i++) 4 print{("value of i’); ) Explanation > 1. The for loop has four components; three are given in parentheses and one-in the loop body. 2. All three components between the parentheses are optional. 3. The initialization part is executed first and only once 4, The condition is evaluated before the loop body is executed. If the condition is false then the loop body is not executed. : 4 i The update part is executed only after the loop body is' executed and is generally used for updating the loop variables. . The absence of a condition is taken as true. It is the responsibility of the programmer to make sure the condition is false after certain iterations. : y NO THE for LOOP WITH A COMMA OPERATOR Introduction We may want to control the loop variables in the same for loop. We can use one for loop with a comma operator in such situations. Syntax for (i = 0,j = 10; 1 < 3 G8 j > 8; i++, j-) printf (" the value of i and j %d %d\n' Explanation 1. First iis initialized to 0. and jis initialized to 10. 2. The conditions i<3 apd, 78 are evaluated and the result is printed only if both conditions are true. eee ik 3. After executing the loop body, i is incremented by 1 and j is decremented by 1. 4. The comma operator also returns a value. It returns the value of the rightmost operand. The value of (i= 0, j =-10) is 10. ‘THE break STATEMENT Introduction break is used to break any type of loop. Breaking a loop means terminating it. A break terminates the loop in which the loop body is written. Example is example: while (1) { iiets print the valle of ts %chn"); it (5) break: lanation 1. The while (1) here means the while condition is always true. 2. When i reaches 6, the if condition becomes true and break is executed, which terminates the Joo re Notes prepared by T. Ratna Reddy Associate Prof. CBIT Mobile : 9985666778 Page 23 Lonirobstmpuctures: Introduction The break statement breaks the entire loop, but a continue statement breaks the current iteration. After a continue statement, the control returns to top of the loop, that is, to the test conditions. Switch doesn't have a continue statement. Example Suppose you want to print numbers 1 to 10 except 4 and 7. You can write: for(i = 0, i< 11, i+) 4) | | (i == 7)) continue; the value of i is %d\n", i} Explanation Ifiis 1 then the if condition is not satisfied and continue is not executed. The value of i is printed as 1. gs When i is 4 then the if condition is satisfied and continue is executed. After executing the continue statement, the next statement, {printf}, is not executediinsigad, the updated part of the for statement (i++) is executed. Examples for forloop yo 1, Program to find the factorial of a number #include main0 { long int fact=15 intin print factorial\n seanft" “edt kn): Enter a positive number to find print((The factorial of %d is %td" in fact): 2# mainO { int i. f1. 22. £8. fl=f2=1 print#("\nHow many Fibonacci numbers required ? ": seanf("%d", &n): printf(\nThe first %3d Fibonacci numbergy are\n". n) A printf{('%5d\n x) printf(" vi, mS Mor(i=? 6 t e R= fl +f printf d\n", £3: 1 =f: Notes prepared by T. Ratna Reddy Associate Prof. CBIT < main. 1/3. Sine serie vo 7*. sin(x) =x-x3/314x5/5! °° ‘’ #include yet Hinelade = i { int i float x.denom. term. sum.deg: printi Enter value of sin deg and namie of terms: \n"}: sean %obod", °. Sa): og. AVIS: : denom = 2 7B icp term *=* denom} sum += term; roy } printf"\ndeg =%.1f, 3 end of main */ Sum = %.2f", deg, sum); 4 ato | » \ + Le £ sine series a . mainO ¢ a7 ( . int i,m . float x,denom, term, sum,deg; Mobile : 9985666778 Page 24 Control structures peal borers alnes ndeg and member ol terms: \n"); scanf("%f%d", °, &n); x=deg*3. 14/180; sum = term = 1} for (i= Li <= nj i++) 1 denom = (2 *i)*(2*i- Ds -(x*x)/ denom; sum += term; printf"\ndeg = %.1f, 3 end of main */ Sum = %.2f", deg, sum); Nested for loops PROGRAM 1 oe 12 123% #include void main) { int line ,n; for(line=1line<=5iline++) { for=1in<=line:n++) printf%2d".n): printf\n"): } 3 PROGRAM 2 * 1 I 2 1 203 ” include void main int line gay for(ine=1lines=filine++) { for(gap=1:gap<=20-lineigap++) printf” "); for(a=1in<=linein++) Notes prepared by T. Ratna Reddy Associate Prof. CBIT printf dd" nn): printi("\n"); } 3 PROGRAM 3 * 1 12 123 1234 12345 *y #include void main0 { int line .nigap: for(line=1:line<=5:line++) t for(gap=1gap<=5-line:gap+4) inth" ") n<=Linein++) printf’ prin snd. } , : PROGRAM 4 1 121 12312 1234123 123451234 include void main) t int line ,n,gapi for(line=1;line<=5:line++) { for(gap=1igap<=20-lineigap++) print” "); for(n=1:n<=linein++) printf("%2d",n); for(n=1in void main) { int binom,n,q,g,x; binom=1; g=0; printf("enter no of rows\n"); seanf("%d",&n); while(q mainO { int n,sum=0,digits; printf"Enter a number\n"); scani("%d",8n)s while(a!= { eT: sum=sum+digit: neni 10: } printi "od" sum) ¢ f given two numbers #include main int manr.ged: hrs print{("Enter two numbers\n"): seanft"%d%d" im. Sa): do { Notes prepared by T. Ratna Reddy Associate Prof. CBIT ahd uctul es wate ‘ ede forky 40-8% 4:8 =0%% printf" "); for(x=0:x: { if((x==0) | | (q==0)) binom=1; else binom = Chinom™(q-x+ Ds: printf(%6d",binom): 5 whe 3 printf"\n"); att acy) 11 to convert decimal number to binary, #include mand) t “ ) / int n.sum=0.digit.i=0: —~ printf"Enter a munber\a"!: seanft%d" &n) whileda!=G) - ) digi ind: stm=sum tbat pow 0.0: n=n/2i ih } printf("%d",sum); } le for do while r=m%v: if(r!=0) { 6 m=ni peri }while(e!=0); ged=n; printf("GCD = %d" ged); } Mobile : 9985666778 Page 26 ee FUNCTIONS Bl wrod) . FUNCTIONS inition: A function is a set of instructions under a name that carries out a specific task, assigned to it. . CLASSIFICATION of functions: 1. User defined ‘functions (UDF) 2. Library functions USER DEFINED FUNCTIONS —+— Without arguments With arguments HY Without retum Withreturn = Without return With return Example: vale? Bum) function without arguments and without return value int sum() function without arguments and with return value void sumf{int ,int) function with arguments and without return value int sumtint int} function with arguimerits and with return value Advantages: 1. ttavoids the need for redundant programming of the same instructions. 2. Logica? clarity of the programming will be clear. 3. Easy ta debug. 4. Alibrary with user defined functions can be created. Function prototype: 'f we use any variable in the program, we declare that variable in thre declaration section of the program. Similarly any function that is to be called should be declared before its cali in the calling function. This dectaration of a function is called function prototype. Function declaration should be done either in the declaration section of caling function or before it. The function prototype should agree with definition of that function. Prototype contains the data type returned by the function followed by the name of that function and a pair of parentheses enclosing the data type of each parameter separately. Optionally the name of each parameter may be given. Ex: int fact(inty; or int fact(int n); If there are no parameters, void should be shown in parentheses. Similarly if there is no retum value, return value type should be indicated as void. Function definition ‘Writing code for the function is calied function definition. Function definition contains function header + body of function. Syntax of function header retum type name of the function ( arguments) Example : int sum{intx, int y) Notes Prepared by T. Ratna Reddy. Associate Professor, CBIT Mobile 99856 66778Page 27 FUNCTION-CALL Function call means, accessing a function. A function can be called by specifying its name, followed by a list of arguments enclosed in the parentheses, and separated by comma. Example: f=fact(n); If a function call does not require any arguments, an empty pair of parentheses must follow the function name. A function call may appear itself or it may be one of the operand within a expression. Example: printi(“%d" fact(n)); Arguments in function call, and formal parameters in function | declaration must be same ins number, type and order. ae Difference between actual and formal parameters Variables used in function calling are called actual parameters or arguments Variables used in function definition are called formal parameters or dummy parameters or Place holders. Parameter passing mechanisms There are two parameter passing mechanisms 1. call by value. Or passing by value 2. call by reference or passing by address or cali by address. Call by value: Passing arguments by value means , the contents of the arguments in the calling function are not changed , even if they are changed in the called function. ‘This is because the content of the variable is copied to the formal parameter of the function definition, thus preventing the contents of the argument in the calling function. _/Call by reference: Cal! by reference means sending the address of variables as arguments to the function. When addresses are sent, the changes occurred in the called function can also effect in the calling function. /* example to illustrate call by value and call by reference*/ Hinclude void main() { void makezero(int,int*); /*function prototype*/ int x=50,y=100; makezero(x,&y); /* function call by value and referene */ printt("x=%d_y=%d”, xy); } /* function makezero */ void makezero(int a,int *b) a Notes Prepared by T. Ratna Reddy. Associate Professor, CBIT Mobile 99856 66778Page 28 “FUNCTIONS int i, ft, f2, £3; EXAMPLE PROGRAMS ON FUNCTIONS fi=fr=4 #include printf("%5d\n", 1); void main() printf("%5d\n", f2); { for( i= 3;i<=n; i++) long int fact(int); int n; 3 =f1 + f2; long int f; printi("%5d\n", £3); printf("Enter a number\n"); fi=f2; scanf("%d",&n); f2 = £3; - f= fact(n); } printf("The factorial of %d is #ld",n,f); } }i*end of main */ of two numbers by function /* function fact*/ void main() long int fact(int x) { { int m,n,g; inti; int ged(int,int); Jong int f1=1; printf("Enter two numbers\n"); scanf("%d%d",&m,&n); return(f1); g=ged(m,n); printf(“GCD of d and %d is Zd", mang); Fibonacci series by function void main() 3 /* End cf snain() #4) { int gcd(int m,int n) intn;, void fib(int); int rg; do printf( "\nHow many Fibonacci numbers { required ?"); r=m2n; scanf("%d", &n); if(ri=o) printf("\nThe first %3d fibonaccinumbers { are\n", n); m=n; fib(n); n=r; ; Jwhile(r!=0); void fib(int n) Brn; return(g1); } /* End of tunction ged */ rr Notes Prepared by T.RatnaReddy. Associate Professor, CBIT Mobile 99856 66778Page 29 FUNCTIONS Ea SO /* tofind-sumof digits recursively */ /* to find the sum of two numbers recursively #include af #include i#include void main() #include ° void main() int rsum(int n); { int ns; int rsum(int,int); printf€"Enter a rumber\n"); int m,n,s; scanf("%d";&n); s=rsum(n); printf("Enter two numbers\n"); printf("sum of digits =%d\n",s); scant("%d%d",8m,&n); s=tsum(m,n); } printf("sum =%d\n",3}; int rsum{int n) } if(n==0) int rsum(int m,int n) return n;. { else return(n%10+rsum(n/10)); } return m; else return{rsum(m+2,n-1)}); } Difference between iterative and recursive functions Iterative Recursive : _ 4, Function call leads | 4. Function call leads | to value to another function call | 1. Function calls some j 1. Function calls some Eg: fact(4) = 24 Eg: fact(4)= 4x | other fiinctions itself fact(3) | | ! 2. while loop, do while | 2, if statement is i loop or for loop is necessary in recursive 5. We require 5, We require a necessary in iterative | function mathemati -ps or | formula to write a function procedure to write an | recursive function 3. Slow in execution iterative function 3. Fast in execution _| since several function since one function call | calls are involved to 6. Stacks are not used | 6. Stacks are used is enough to get the —_| get the result, as during execution during execution of result number of function recursive functions increases execution will slow down. Notes Prepared by T.RatnaReddy. Associate Professor, CBIT Mobile 9985 666778 Page 31 STORAGE CLASSES | Auto Static Extern Register ‘ Normally the life of a variable is limited to a function as long as the function is alive. How to make it alive in a file or throughout the program or limiting only to:a block inside ‘a function or to make common to a desired couple of functions etc., The answer lies In “STORAGE CLASSES” or “VARIABLE TYPES”. There are four types of storage classes. 1. Automatic variables. 2. External variables. 3. Static variables. 4, Register variables. AUTOMATIC VARIABLES: Automatic variables are declared inside a function, in which they are to be utilized. They are created when the function is called and destroyed automatically when the function is exited. By default all variables are automatic variables. These are also called local or internal variables. EXTERNAL VARIABLES Variabies that are both alive and active throughout the entire program are called external variables. These variables are available to ai! functions in that program. Whatever changes that occur in a function, will effect the value of that variable. STATIC VARIABLES When a variable is declared as a static variable it is assigned the vaiue zero. Static variables are initialized only once. They will not be initialized for second time during the program. When stalic is applied to a global variable, the global variable becomes inaccessitle outside the file. ee eee REGISTER VARIABLES © This is local to a function or a block. « Ifa compiler finds a physical register in the CPU free for the time being, and aiso big enough to hold the value, then it may stick that variable in that register. Otherwise the compiler treats that variable as ordinary. It is machine dependent. but compiler will not give elor messages even if nO regeie Avuilulie in ieserve. « Ifwe know that a particular variable will be used often inside function-say the variable inside a loop-then we can declare that variable with class register. So thal the interaction. willbe wens fast Notes Prepared by 7. Ratna Reddy. Associate Professor, CBIT Mobile 99856 66778 Page 32 "y casiinar ‘f FUNCTIONS {Write a program to demonstrate life cycle of auto variable in nested blocks. void main() { auto int x=T; ( auto int x=2; auto int x=3; printf("%d\n", x); } printf(“%d\n"x); printf(" %d\n",x); Output 3 2 1 ¢/ program to illustrate automatic and external variables tt sclude. ini xed; int fun() 42x40; oIUFT X; wot fun2() { int x; x=20; return x; 3 nt fun3() i x=1000; return x; . y- void main() { int x=101 printf("% d\n",fund()); printf("%d\n",fun2()); printf("% d\n" fun3{)); x=0; printf("%d\n",x); printf("%6.d\n" fund); printf("9d\n",fun2()); printf("% d\n",fun3()}; } OUTPUT u 20 1000 oO 1010 20 1000 // program to itustrate static variable #include void main{) { int fun(); inti; for(i=1;i<5;i++) printf("%d\n",fun()}; } int fun() { static int x=0; xt]; return(x); t OUTPUT 1 2 3 4 // program to illustrate register variable #include void main() { register int i; inti; forli=1;i<1000;i++) printf("9% a",i); } rt RE Notes Prepared by T.RatnaReddy. Associate Professor, CBIT Mobite 9985.666778 Page 33 automatic variable | "static variable 1 T.It is declared by 1. It is deciared by auto int a = 10; static int a = 10; 2. It must be 2. It can be declared declared inside the inside or outside function the function 3. If itis not 3. If itis not initialized, garbage _| initialized, zero is value stored is stored 4. It is initialized every time function | 4. It is initialized once is called that is and only one but repeated notevery time itializatis when function is 5. It is lost when called function terminates 5. It is lost when program terminates but not when function terminates Stroge | Type | Oefautt | Place of Scope fe Class Initial | declaration value auto [local | Garbage | Within ‘Only Until value | function or | within | function block the block is function -| no orblock | longer where it | active is declared Static | local | zero = * Untit program ends [extern [global | zero Headofall | Alifiles | White functions | including | any file within file { other is active. files where aeciared extern Notes Prepared by T. Ratna Reddy. ‘Local variable 1. It is declaration inside the function 2.1t is declared by auto int a=10 or int a = 10 (auto is default scope) 3. If it is not initialized garbage value is stored Eg: int a; ais garbage value 4. It is created when the function starts execution and lost when the function terminates 5. It is visible in only one function. 6. It can be accessed in | only one function that is the function where it ! is declared | 7. Data sharing isnot. | possible that is data of loval variable | can be accessed. by only one function 8. Parameters passing is required for local variable that is local variable of one variable 9. If value of local variable is modified in one function changes are not visible in another functions Associate Professor, CBIT Mobile 9985 666778 Global variable ‘Lilt is declaration outside the function 2. Ttis declared by int | a=10 . 8, fitis not initialized | zero is stored Eg: int ai a=0 4, It ia created before program execution starts and lost when program terminates 5. Itis visible through out the program. 6. It can be accessed in more than one function. 7. Data sharing i possible that is multiple functions can access the same global variabl: 8, Parameters passing is not required for global variadle since global variable is visits: throughout the program 9. If value of global variable is modifier! in one function changes are visible ir rest of the progran TEST YOUR UNDERSTANDING 1. Write a program to print CBIT by using printf function. Write a program to accept an integer number, float number, character and to display x Write a program to accept a string and display it. Write a program to find sum of any two numbers. Write a program to find area and perimeter of a circle. Write a program to find components of a force. Write a program to find the last digit of number. Write a program to convert an integer number to no. months and days Nanay 8. 9. Write a program to find sum of digits of a given integer number. 10.Write a program to print the given integer number in reverse order.. 14.Write a program to check whether the given number is palindrome or not, 12.Write a program to find largest of given two numbers. 13.WAP find largest of given three numbers by using simple if, nested if, else if ladder 14.Write a program to check whether the given triangle is right triangle or not 15.Write a program to find the quadrant position of given coordinate. 16.Write a program to check whether the entered character is vowel or not. 17.Write a program to print CBIT twenty times by using for loop. 18.Write a program to find the sum of first n natural numbers. 19.Write 4 program to find the sum of first n even numbers, 20.Write a program to find the sum of given n numbers. 21.Write a program to print n™ table upto 10. 22.Write a program to print the following triangle of numbers by using nested loops. Nw w pe wee re we we Re we we we 23.Write a program to print the sum of first n terms of sine series. 24.Write a program to print the sur. of first n terms of cosine series. 25.Write a program to print the Pascal triangle. 26.Write a program to find n™ Fibonacci number. 27.Write a program to generate first n terms of Fibonacci series. 28.Write a program to find factorial of a number. 29.Write a program to check whether the given number is prime or not. 30.Write a program to print first n prime numbers. 31.Write a program to print prime numbers upto n. reer Notes prepared by T. Ratna Reddy. Mobile: 99856 66778 Page: 37 DEVENS G pIUy ute Ge pris pereee 33.Write a program by using a function to find the sum of two numbers. 34.Write a program by using a function to find factorial of a number. 35.Write a program by using a function to find n™ Fibonacci number. 36.Write a program by using a function to generate Fibonacci series. 37.Write a program by using a function to find GCD of given two numbers. 38.WAP by using a function to swap the values of two numbers.( use cail by reference method) 39.WAP by using a function to swap the values two aumbers. (use call by value method ) 40.Write a program by using a recursive function to find the sum of two numbers. 41.Write a program by using a recursive function to find factorial of a number. 42.Write 2 program by using a recursive function to find n™ Fibonacci number. 43.Write a program by using a recursive function to generate Fibonacci series. 44.Write a program by using a recursive function to find GCD of given two numbers. 45.WAP to display menu for selecting addition, subtraction, multiplication and division and compute according to menu chosen. (Use do-while). 46.WAP to addition, subtraction, and multiplication of two complex numbers (a+ib) and (xtiy). 47.Using while loop, write a program to print all Armstrong numbers between 1 and 500. If sum of cubes of each digit of the numbers is equal to the number itself, then number is called Armstrong number. For example: 153 = (1*1*1) + (5*5*5) + (3*3*3) 48.WAP to find whether the given number is strong or not using functions. (Example: 145 = 1! + 41+ 5!=1+4 24+ 120 = 145) 49.Input a year from keyboard and determine whether it is leap year or not using the conditior:al operator. 50.Accept three numbers from user and determine which of the two numbers or all three numbers are equal or not using logical operators. 51.WAP to take student roll no, five subjects marks and display total marks, percentage and result by taking following conditions into consideration. a. 50 is the pass mark in every subject b. if student secure percentage >=70 First Class with Distinction >=60 and <70 First Class >=50 and <60 Second Class <50 FAIL 52.WAP to calculate nPr= n!/(n-r)! 53.WAP to calculate nCr =n! / n!*(n-r)! 54,WAP to find whether the given number is perfect or not Example (6 is perfect number since 6 = 1+ 2 + 3) 55.WAP to convert given decimal number to binary number by using a function. ee er Notes prepared by T. Ratna Reddy. Mobile: 99856 66778 Page: 36 10. 11. 12. ‘Notes Prepared by T. Ratna Reddy Mobile: 99856 66778 Objective type questions in C What is a compiter? A compiler reads the entire program and converts it to the object code. Name any five versions of C compilers. Turboc ,boroland c,.ansi c,C99,win4S Give the charagter set-of C language. Letters, Digits, White spaces, Special Characters. What is an identifier? Identifiers are names of variables, functions and arrays. They are user defined names, consisting of letters and digits, with the letter as the first character. What are the rules to be followed for forming identifiers? It must start with an alphabet. It should not be a reserved word. Should not start with digit. Second character onwards alphabets, digits or underscore can be used. What are the key words in C? auto, break, case, char, const, continue, default, do, double, else, enum, extern, float, for, goto, if, int, long, register, return, short, signed, sizeof, static, struct, switch, typedef, union, unsigned, void, while What is the difference between a constant and variable? What are the various data types available in Cc? Fundamental or scalar or primitive or basic data types: int, char, float, double derived data types: arrays, Functions, pointers, structures, unions. What is a derived data type? Derived data types are derived from the collection of bas'‘c data types. Explain the qualifiers with examples. Short, tong, signed, unsigned identifiers may precede some of basic data types to specify the number of bits for representing the respective type of data in memory. they are known as qualifiers or modifiers. Example: long int, short int, unsigned int, signed int, unsigned long int, unsigned short int, signed Jong int, signed short int, signed chr, unsigned char, long double. How is character constant specified in C? It should be within single quote. Differentiate between character constant and string constant. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. String constant should be within double quote. What are escape sequence? \O, \a, \b, \t, \a, \v, VF \r What are white space characters available in C? In C, blank and some of the non graphic characters are known as white space characters. They are blank, new line, horizontal tab, vertical tab, carriage returnand form feed, How are comments intraduced in C? A comment explains briefly what a program does. In C programs, the characters between /* ard */ are treated as comments and are ignored by the compiler. What is the significance of semicolon in C? It is a statement terminator. What are C tokens? Give examples? A compiler identifes and splits a program into a number of tokens. A token may bea single character or a group of characters which has.a specific meaning. Various C tokens are identifiers, keywords, constants, operators, separators. Explain the structure of C language. Write a program that does no eperation. Name various types of operators in C Differentiate between binary and unary operator. What is an expression? Any valid combination of constants , variables and operators constitute an expression. Is there any exponential operator in ¢? What is a numeric expression? Arithmetic expression is called numeric expression Discuss pre and post increment operators. What is a relational expression? Differentiate between relational and logical expressions? What is the difference between & and && What is the difference between = and == Classify bitwise operators. Explain compound assignment expressior? What is a ternary operator in c? What is type conversion(type casting) in c? What is the result of each of the following (float)5/3 (float)1 +1/3 What is precedence and associativity of operators? “C is rich in operators *. Justify the statement. Page: 39 Nope ee Find the values of following expressicns a=b++ +++b; where b=15 a*= b= c=5; wheres = 20 x=(y*=2) + (z=a=4); given y=5; a*=b/=c-= d+= 6*2 What is purpose of induding stdio.h in a program? How is stdio.h file included in a program? Name the character-oriented I/O functions. What is formatted io. and explain? What Is-the vate returned by getchar() How is EOF entered from the keyboard? What is the syntax for using putchar{)? What are the possible arguments that are used in putchar()? : 46. What is the syntax for scanf() function? 47, What is a conversion specifier? 48. What Is a conversion. character? 49. What is a header file. Name any 5 header files? What is the purpose of math.h file? What is the propose of main() function? How many times the function main(} can be used in a program? 53. What is the suppression character what is its effect? Whenever the character * appears between the percent sign (%) and the conversion character of,a,conyersion specification then itis Known as.suppression character. Ex: scanf("%d %*d8d*,&a;&b) ; How would the number 9875 appear if printed with the following conversion Specifications 1) %0d 2) %3d 3) %4d 4) %10d. . What are the control structures available in c : 37. 38. 39. 40. 41. 42. 43. a4, 45. 50. 51. 52. 54. 55. 56. 57. Name the selective. constructs inc What is looping? Distinguish between a pre test looping and post test looping Name the loop constructs in c Name the unconditional contro! statements inc Name the conditional control structures in C Explain in detail the different forms of if constructs inc What is conditional expression Illustrate the use of ternary operations c «othe wi i i Explain the do- while structure with examples Can the action of a do- while structure is simulated by If or if-else structures? Explain with an example. 58. 59. 60. 61. 62. Notes Prepared by T. Ratna Reddy Mobile: 99856 66778 _ meee 67. 66. Fi 72. 73. 74, 75. 76. 77. 78. 79. 39. 82. 83. 84, 35. 86. 87. 88, Compare the while structure with co~ witrite structure . Write the advantages of white ious over tie do- while loop How is a for loop equivaiently written using a while loop. Under what circumstances will the do-while be more appropriate than the for loop. Differentiate between break and continue statements. What is meant by nested loop? Explain switch-case structure with examplz. Compare the switch-case with if else structure. Why goto statements are discouraged? Rewrite the following without using compound relations 1F(EM>908&&EG >95||Total>190) printfSUCCESS”); else printf(*Failure*); what is the output of the following prograin mainQ) t int i; for(zi;) mj printh("%d",i); - } Distinguish between source code, object code and executable code. Draw flow chart for various contro! constructs. Define the following Function prototype, Function cali, Function definition, Actual parameters, Formal parameters, call by value, call by reference, function header, recursive function calling function, called function. Explain the following Automatic variables, Extemal variables, Static variables, Register variables. Explain different pre-processor commands Explain switch statement with suitable example. Explain recursion with example Define scope, lifetime & visibility of variables, How many values can a function return What is the default data type a functien returns What is meant by scope of the variable and life time of a variable? Page :40 | 1D arrays > Features of arrays Features ofarrays | i wrAvray is a Collection of similar data types under one Soynameés owAn ‘arfay is aderived data type Wit holds one or more:eteménts of the same data type > ooh thand henee itis useful'ta store more data | teAn array. ‘hatne followed bythe subscript, enclosed within the square brackets, tefeérs to the individual float, bi20].: char str{50]; initialization of. en fen array: int a[S} = { 3,6,2;8,7}; panensiene PROGRAM [evnenensesnneny PTO INITIALIZE AN’ARAY AND PRINT THE ELEMENTS */ #include main : { int al20]=(3,5,8,10,13,16,19}; int i; printi(‘the elements of the array are\n"); forti=0;1<7;i++) ) printf("%4d" af); } . f 5 pacneninsisapROGRIAM geoesmenteetnts] TO PRINT THE ELEMENTS OF AN ARRAY IN THE ;- REVERSE ORDER */ » finclude © main { int af20]={3,5,8,10,13,16,19}; inti; printf(‘the elements of the array in reverse order are\n’); T. Ratna Reddy . Associate Professor, CBIT. fay became? , PROGRAMMING IN Mobile : 9985 666 778 " printf’%4d" afi); penentees ROGRAM 3*eteeenentny /* TO FIND THE MAXIMUM OF GIVEN NUMBERS */ #include void main) { 10 int af20],J,max,n; print{CHow many elements\n"); scant(%d",&n); /* loop to read values into array */ printf(Enter the elements\n"}; for(=O;igpii++) inf", Bali); /° loop to find maximum of n numbers */ max=a[0], for(i nitty if(alij>max) max=ali]; } printf(MAXIMUM = %d\n", max); } fittenennenentt DROGRANL steteetnenanunes) /¢* LINEAR SEARCH */ Hinclude maing { int a[10]i,n,key,flag=0; printf(‘enter how many numbers\n"); scanf("%d",&n); i /* loop te read valtes into array *! printf(Enter the numbers\n"); forGi=0;i maind c : int low, ;high flag=0, mid,a[10},i,n,key; printfCenter how many numbers\n"), scanf("%d",&n); /* Joop to read values into array */ printfCEnter the numbers\n"); for(=0;ia{mid)) jow = mid+1; else if(key==a[mid]) printf(’search Is: printf(‘tocation Bir Program breserereesy /*BUBBLE SORT*/ #include mainQ int 9[20),, j, temp,pass, n; printfC'How many numbers to sort ? "); scanf("%d", &1); T. Ratna Reddy . Associate Professor, CBIT. /* loop to read values into array */ printf(“\nEnter %d nurabers betow:\n", n); for (i= 0; i alj+1)) { temp = aj]; ali] = afj+4 aj+1] y wy preeseesProgram 6rNteaenensy A SCTION SORT*/ #include void mainQ, 1 int a[20],i,n,j,temp; printf(Enter how many\n"); scanf("%d",&n); printf(‘enter elements\n"); for(=0;iali)) ‘ temp=ali}; ali afi]; afijstemp; nit for(i ) printf’ %d_ "afi; Mobile : 9985 666 778 Page 2 2D arrays . A Two Dimensional array can be define as an array of one dimensional array De int a[10]{10}; float b[20}[20], char str{50][50]; array initialization of an erray: This can be done in two ways 1. Int af2]2]= {13,6} , {2.9} } 2. int af2i2}={ 3.6.2.9}. #include maind { int a0, {1 O}{10],c[10](10} ij,m,n; ci Center ‘the number of rows and columns: for A and Bin"); scanf(%d%d" &m,&n); {* loop to read values of matrix A*/ printf(’Enter the elements for matrix A\n"); r¢ itt) soantced alii; /* loop to read values matrix B*/ print(("Enter the elements for matrix Bin"), for(=0: main). Int a{10][10},b{10]{10}.c{10}(191.ij.m,n,p,4,k; T. Ratna Reddy . Associate Professor, CBIT. PROGRAMMING INC (Part - Ii) Mobile : 9985 666 778 clrscr); printf("Enter the number of rows and columns for A \n"); scanf("%d%d",&m,&n); printf("Enter the number of rows and columns for Bn"); scanf("%d%d",&p,&q); ? loop to read values of matrix A*/ printf("Enter the elements for matrix ay for(i=0:icm;i++) forg=Oj main) { int a[5]{5),b(5)(5}.i,,r.0; printf("Enter the size of matrx\n’); scanf("%d%d", 8,80); / loop to read values of matrix A*/ printf(’Enter the matrix valuesin"); for(i=0;icri¢+) ford Cit) scant("%d" 8a); loop to find transpose of matrix A*/ Page 3 forgo i main) { void tsearch(int { ].iat, int); int a[10],n,,key; printf(’enter how many elem seanf("%d",&n); printf("Enter the values\n? for(=0;i { void input(int [ }.int); void bsearch(int [],int,int); int a[25],n,key; printf(How many numb scant("%d",&n); } } “Mobile: 9985 666 778 if(found== ‘* binary search br tion *, maing. inction input */ int n) for ( yi a[mid]) fow = mid+1; alse if(key == a[mid]) printf("search is.successfulln"); printfClocation = %din",mid+1); flag=1; break; } ) if(flag==0) printf('search is unsuccessfulln’), - /* end of function bubbiesort Page 4 /*bubble sort by functions */ #include main? ‘ void input(int [1.int); void output(nt flint); void bubblesort(int int); int a[25],n; printi(How many numbers to sort ?"); scanf(‘%d",&n); printf(’\Enter %d numbers below:\n", n); input(a,n), bubblesort(a,n); printf(\nThe sorted Array is: \n"); output(a,n); } 7 end of main “7 /*Function input */ void — input( int ap.int n) intk; for (i= 0:i alj+1)) { temp = afi]; ali = a+ 1}, alj+4] = temp. } 3 printf("%5d\n". afi); } 7 end of function output */ T. Ratna Reddy . Associate Professor, CBIT. PRUGRANINIING 1. We can pass entire two dimensional array to function like one dimensional array. . 2, When we pass two dimensional array to a function, in the function definition formal argument, the size of the coluggg is must and size of the rowis optional. /*Program to add two mati functions*/ #include }O}.int,int); [10],m,n; matrix A and B: *); loctt elements of matrix A \n"); (A, m,n); tf(\nEnter elements of matrix B \n’); : admat (B,m,n), matadd(A, B, C,m,n); printf("Matrix A is :\n"); display(A, m,n); printf("Matrix B is :\n"); display(B, m,n); printi(’MMATRIX GC (= A + B)is:\n"); disptay(C, m,n); 3} /* end of main */ /* Function to read the elements of a matrix cow-wise */ void readmat(nt X[10}[10],int_ rows,int cols) 0; j Het) scant(%ch, &XtIGD; } /" end of function read_matrix */ Mobile : 9985 666 778 Page S PROGRAMMING IN C (Part - II) /*Function to add two mon matrices */ ‘void matadd (int A[10}{10], int B[10]{10}, int C[40]{10), int, int ny { inti, j; for(i = 0; i mainQ i void readmattint [10] int,i printfC\iEhter elements of matrix B \n"); readmat (B,p,q); matmul(A, B, C,m,q.n); printt(’Matrix A is :\n"); display(A, m,n); T. Ratna Reddy . Associate Professor, CBIT. } } fend of main */ /* Function to read the elements o| void readmat(int X[10][10},int rows, { . { } Mobi ce ID print Matrix B is :\n’): display®, p,q); Print((\AMATRIX C (= A X B) is:\n"); display(C, m,q); w-wise */ px q matrices */ ‘B[10][10}, int C[10](10), inim, intq, intn) Cia =0; for(k=0; k maing, { int a= 10; int *pa; /! declaration of pointer variable pa = &a; 1/ initializing the pointer variable printf(‘value of a =%d\n",a); printf(value of a 3%d) printf(value of a = printt(: “Address of € a edn", fh 4040 4040 Initialization of A pointer is Same ‘to any other variable except that it” only memory address, and therefore, it needs to be ized with a valid address before it can be used. * Pointers should be initialized either when they are declared or in an assignment statement... i initialized to 0, NULL or an address.A value NULL points to nothing. NULL isa constant defined in he: If pointer to 0 is equivalent to initiali The value 0 is the only integey directly to a pointer variabig Since a pointer is allowed on it. Tt possible with p a Eto another pointer. Tis be incremented or decremented. Tie :to cause the pointer to point to the subsequent or previous element. int a=10,*pa; . pa = &a; patt; An integer can be added or subtracted from a. pointer. One pointer can be subtracted from another pointer (out can never be added) provided that they are pointing to the same s /. The expression retums the number o| tween them. Two pointer variables: can NEVER be multiplies or divided, but muttiplication of a pointer variable with a number is possible. Jprses808** PROGRAM 2 *eeereteennenn/) LTo find the sum of two vaiues using pointers Hinclude main() - { int a,b,sum; inc *pa,po;7/ deciaration of pointer voriabies pa-&a; —// assigning address of a to pa; pb=&b; — // assigning address of b to pb; printf("Enter two numbers\n"); scanf("%d%d", 8a, &b); sum = *pa + *pb; // addition by pointers print{("sum = %d\n",sum); } T. Ratna Reddy . Associate Professor, CBIT. Mobile : 9985 666 778 Page 7 PROGRAMMING IN C (Part - II) 30). [paeseneassnanest PROGRAM grettenanenenecensy output 1 To find biggest of two numbers using pointers Elemno Elem Address Hinclude x0) 2 4086 pn x42] 9 4060 ‘int xy, *big,*xptr, *yptr; x13} 3 4062 ai eal » /* To display contents of array by different Ways*/ sant 66% We include yor cB void main() . ( if(*xptr >*yptr} ir = . wn int a[5} = { 20,30,10,50,25}; ' big = xptr; inti; és orb = votes printf(“Elements of the a a’ bigee big): for (i=0;ic5;i+-4) ; printf(“biggest number is %d\n”, *big); printf("96340%309 Relation between arrays and pointers In C, when an array is declared, the array name denotes the address of the 0 element In that array. The address of the 0" element Is also talled base address or starting address. Therefore, if we refer the name of the array we get the starting address of the array. So array name itself is an address or pointer. The elements of the array together with their address can be displayed by using array name itself since array elements are stored in contiguous memory locations. For example, an array Is initialized as below: int a4) =(3,7,9,4; Wow, we can access the value in the second loc: ways. By array notation; a1] By pointer notation; *(a+1) Similarly, we can get address of ways. By erray notation: &a{1 By pointer notation : (a: FOCESS by which the required memory address is ithout an explicit declaration. The required ined by using the memory ion functions like malloc() and clloc(). Memory allocation functions retum a pointer value to a block of memory of required size. This retumed pointer value is assigned to a pointer variable. Thus, the required memory space is dynamically created and assigned This method of allocation is known as dynamic memory allocation. The function malloc obtains the number of bytes mentioned as its arguments and returns a generic pointer (pointer to void ie void *) to the memory obtained. This generic pointer is typecast in to the data EXAMPLE type we want. /* To display e {that location and Ex: address of that va int tip; sinc ii Pe {int *}mattoc(sizeof(int)); [pt+esestnesene PROGRAM ditttteattaneeneey) /* bubble sort by dynamic memory allocation*/ forli=0;i<4; #include { Hinclude printt(x[%d] %d %d”,i, *(ati), (a+i)}; void maing } { , . int *a,n,i,temp,pass,j; } printf(‘How many elements\n’); . errr ner 2 ree ene nen T. Ratna Reddy . Associate Professor, CBIT. Mobile: 9985 666 778 Page 8 PINVUORSLINEINETIN ENG (halt VL scant((%d",&n); /* dynamically allocating the memory for n elements */ a = (int*}malioc(n* sizeof(int)); 7 loop to acceptin values */ printf(“Enter the numbers\n’); for(i=0;i"(ati*1)) temp= “(ati); *(ati) Aatirt); *atitt) = temp, } } } 7" loop to display the sorted elements printf(‘The sorted elements are\n’); for(i=O;i void main(} { void makezero(intint*}; /*function prot int x=50,y=100; makezero(x,8y); /* function call y printi(“x=%d y=", xy); } /* function makezero void makezerofint Al2I81 = (1.23.4,5,6,7.8,9); 1 A 13] = { 1,2,3,4,5,6,7,8,9}; #1 column size is must 90 201 Faz Bo Ti Az Bq Aa, a2 2D array can be accessed in different ways. Address | &ajO][0] or In general of a[O}{0] | a[0) or Address of aft) iz “aor Salil or afil+ a or value of | *&a[0}[0] or *asi) 4] afO}[0] *al0] or < “a or afoy{o) Address | &al7][1] or Value of afiliil is of af2][1] | af2}+1 or *&afili) or *(afi}+i) *(a +2) +1 or value of | “&al2][t} or *(*at) +) af2iit} *(@l2]+t) or *((a +2) +1) Mobile : 9985 666 778 © Page 9 . PROGRAMMING IN C (Part - 1) QO\VD ARRAY OF POINTERS Whenever addresses are stored as array elements, such an array is called an array of pointers. The format for ‘the declaration of array of pointers is For example a 2D.array. a[5][10] can be represented by array of pointers as, *a[10} Storage representation of a 2D array using array of pointers. int a[10}[16] CAN BE REPRESENTED BY int *ptr[10] HL AlN [ptaneennensenen PROGRAM Bttenenntensennnn// Example for arr ointers - Uito print a matrix by array of pointers — include include ‘void maing) int fa[Spm.nij; print? Enter the size of the m: soanf("%eu%d", m,n); ‘y. Ratna Reddy . Associate Professor, CBIT. Mobile : 9985 666 778 POINTER TO AN ARRAY Array elements are stored in consecutive memory allocations. 2D array elements are stored row by row. in C it is possible to define a 2D array as a pointer to a group of consecutive one-dimensional array. The format for declaration of pointer to ang é ae. xample for pointer to array "pepe ‘ffiatrix by pointer to array jude | #inélude * void maing Bas int Ca)[S].m,n,i4; printf("Enter the size of the matrixin’); scanf(%d%d",&m,&n); a=(int (*)[ Pmalloc(m*n*2); printf(” "Enter the elements of A \n"), “scant("%d",("(ati)4)); printf("Matrix A is. :\n"); ror(i=O;i(int()[]}malloctmn'n* ali}={int *}malloc{n*sizeck{int); ‘sizeof{in()); The tows of the 2D amay are of same lengths The rows of the 2D array may be of different lengths Total memory can be |- ‘Memory should be allocated allocated at a time. to all rows individually rerseeeseesseers PROGRAM Srttoersssssstson]) ifTo add two matrices by array of pointers #include #include void main() int *a[10),*b[10],*c[10].i,j,.m,o; printf('Enter the size of matrix\n"); scanf((%d%d",&m,&n); 7* Woop to allocate memory*/ for(i=O;i #include void maing na bizecK(ind)); (m*n* sizeof(int)); Lingttix A*/ (“Enter the elements for matrix A\n"); jiemii++) O;j void main() : 9985 666 778 Page 11 Difference between array of pointers and pointer to an array Array of pointers declaration *aj 10} Pointer to an array declaration (aid) Ih array of pointers the row size is mentioned in the In pointer to an array. the column size is mentioned in declaration the declaration ex ex fox(e0;iemies) a=(nt¢)—)malloct'n* ali}=Gnt *)malloc{n*sizeof{it)), ‘sizeof(int)); The rows of the 20 array may be of different lengths The rows of the 20 amay are of same lengths "Memory shouid be allocated be |- to ali rows individually Total memory allocated at a time can freenennasesesPROGRAM Brtttsetaaeen tes) Iffo add two matrices by array of pointers #include #include void main() int *a[10],*b[10},*c{10),i,j,m,n; printfEnter the size of matrix\n"); scanf((%d%d",&m, &i1); 7* loop to allocate memory*/ for(i=O;i #include void maing int Canto} ey ii 3 sant ‘%eod".*(ati+)), /* loop to read matrix B*/ printf("Enter the elements for matrix Bin’); . for(i=0;i printiCResultant Matrix cis -\n"); void main() Seer, T. Ratna Reddy . Associate Professor, CBIT. Mobile : 9985 666 778 Page 11 PROGRAMMING IN C (Part - 11) 2012: int a,b; void swap(int *,int *); printf("Enter two numbersin"); scanf((%d%d",&a,&b); printf(’Before function call a=%d_b=%d\n"); swap(&a,&b); printf(’After function call a=%d_ b=%d\n"); } . J function swap void swap(int *x,int *y) STRINGS Jarati itialization of string variables A String is an array of characters. A string may include letters, digits and various special characters. It can be read as a single entity. The genera! form of deciaration of a string variable is char string-name [size] When a string is initialized it automatically supplies a NULL (‘\0’) character at the end of a string. Therefore, the size should be equal to the. and press the enter key. It is to be noted that C language provides a NULL character ‘\0’ to the end of any character string. The given string is stored in the memory as shown in the figure. c{elr {tho [ | puts()_ Function Example: char str[20) = “SMILE reas puts(str); When this functi t display the strifg’on thé:monitor #include- void main() { ‘duarstr[20} prinff Ente your name\n"); gets(str) printf(’Very glad to meet you“); puts(str); } Various library functions in string.h maximum number of characters in the string plus function | purpose 1 one. 2 strupr() | Tocomet al steupr“ebi’) | CBIT Strings can be initialized when theyiSre declared. Alebabets in aog This can be done in the follogingaeey _— tee ase char str[5] = “city”; : striwrt Tocomertal | siriwncBiT) | cit char str[] = “city” ; F | Sptatessinsting | > jebit char str[5] = {'c',i'A to lower case i When we initialize ated élements, we letters - _—- must supply NULL characté EL ly. strien() Fak engi olhe char sf; [4 | . F intn; PUT /OUTPUT FUNCTIONS excudng the | ent { NULL character i 2 strre.{} | Toreverse a strrov("city); . SeAito read a string of ‘ string v ytic | white spaces. Note that a strepy() Copies string st2_| char s2{]="city”; | s2 Nhite spaces cannot be read to sting st char s1 [20]; contains | ’ format specifier. as strey yf, 52) city 4 strom compare | nestremp(“cbit” | n= § form ; pO ine 1 scp pe” n=O gets(str); identical character string variable. strnemp() | Compares the first [ n-stracmpe n=0 “| n characters of “ram” 2); ! char str[13]; st and str2 . i gets(str); streat() To join st2 tostt | strepy(“stu", student | when this function is executed, the computer waits “dent") j for the string value. Enter the strings(e.g. “CBIT”) T. Ratna Reddy . Associate Professor, CBIT. Mobile : 9985 666 778 Page 12 PROGRAMMING IN C {Part - II) 20) 2 & Program to check whether the given string is Copy a string to another string by using user palindrome or not by using library functions*/ defined function #include #include maind #include { main void scopy(char [},char [] » { static char sir1[30}) char str1[30},str2[30), printfCEnter a string\n”), printf("Enter a string\n’); gets(sir1); gets(str1); scopy(sir1 str2); stropy(str2,strt); puts(str2); if(stremp(str1 strrev(str2))==0) } printf(‘yes ,Palindrome’); else Pfanction scopy 7 , printf('Not patindrome"); void scopy(char st[, ir } se Program _to swap iwo strings _by using library functions Hinclude #include main() { char str1(30]="hyderabad” str2[30]= “city” temp[30}, strepy(temp,str1); stropy(strt ,str2); stropy(str2,temp); puts(str1); % chat str1[30],str2[30]; puts(str2); : printiEnter a string\n"); gets(strt); printfEnter other string\n"}; gets(str2); , scat(strt,str2); } #include cee /* function scat *7 int sien(char [D; void scat(char s1[ }, char s2[ }) char s1[30]; { a int len; ros Amero; tfCEnter Wn"); or=0:s1 ff] = NO'++ oa setrngin for(ilj=0:s2f] = NOsie+ j+#) len = sien(st for(i=0;s1[!="0'i++) printi(%c",st[i)); printi(\n’); ; To reverse a string by using user ed function. return(length); #include main() f . ° een T. Ratna Reddy . Associate Professor, CBIT. Mobil : 9985 666778 Page 13 void srev(char] |): char $1(30}: printf("Enter your name\n"); gets(sl); srev(s1); } /* function srev */ void srev(char s}| |) t int Lig; char s2[30}; for(I=0;s1[I]!=\0' 1+), Soe jin) S2Ui=sllik: s2hi]=\0'; © printf("%s",s2); STRUCTURES: Definition of struc A structure is a “collection of different datas types under one name. So it is a derived date. type. A structure is defined in the following way. struct tag name data_type member 1; data_type member 2; data_type "Ue n; at Dot( . ) operator a Dot {.) or perig 0) rator is ‘eed to access a ructi data member of a§ ia ariable-si It is be noted ‘thgt the dot operator separates the: trycture vai de and the data te member. ig and accessing members ne b, by.Hbt operator */ void main) { /* declaring a structure */ struct book char title[40]; 'T. Ratna Reddy . Associate Professor, CBIT. int pages; float price; /*declaring and initializing a structure variable */ ‘struct book b1={"c&c++",300,150:0}; /* display value of data members */ print{(os\n",b1.name); printi(‘sedun",b1 pages); printf(“%fin", 1. price); } /* assigning neg Ng aa] ieee PROGRAM 3 /* assigning the values by key board */ #include #include void maind) { struct account { char name[30}; int number; float balance; ya printf("Enter the account holders name\n‘); gets(a.name); printf("Enter the account numberin"); scanf("%d",&a.number): printf("Enter the balance\n"); scan{("%f",&a.balance); printf(’ the details are\n"); printf(‘%s%d%fin",a.name,a.number,a.balance); } Mobile: 9985 666 778 Page 14 ARRAY OF STRUCTURES It is possible to declare array of structures. The following example illustrates this. struct employee_info char name[30}; int ape; char designation[20]; float gross_pay }staff{200}; This declares staff to be an array with 200 elements. The process of declaring a structure array is similar to declaring any other kind of array. PROGRAM 4 Declaring array of structure student and displaying the marks of students who got imore than 75 marks #include typedef struct student { int mo; char sname[40]; int marks; student; pr Fie yi. an), Co a printf('Roll numbenn*); scant('%d", &5fifH0}2 printi(’ Name tw"); See "): %- Sd\n",s[i].mo,s[i].sname, s[il.marks); PROGRAM 5 /*TO DISPLAY THE SORTED LIST OF STUDENTS: AGCORDING TO MARKS */ #include * T.Ratma Reddy. Associate Professor, CBIT. PROGRAMMING IN C (Part - II) void main() struct student int marks; intm; char name(10]; }s{20],temp; intinj: printf("How many students\n" scanf("%d",&n); for(t=O;i #include maind { struct student { int marks; int m; char name[10}; }s[20],temp; Mobile: 9985 666 778 Page 15, int ings printf("How many students\n"); scanf("%d",8n); forti=O;i0) ‘ temp=sfj}; sles 1h; s{j+1}=temp; } } printf("The sorted order is\n"); tor(=0;i void maing) struct book e oes stiuct Ugh, B1-{ Lacrr,900, 150.0}; ptr= oft printf(%s\i"%1->name); printf(“%ed\n",b1->pages); printi(“36fin",bt->price), } T. Ratna Reddy . Associate Professor, CBIT. PROGRAMMING UN C (Part FUNCTIONS AND STRUCTURES There are three ways to pass a structure to a function 1. Passing individual members of a structure variable to the function 2. Passing the entire structure to 3. Passing pointer of the str function. function. i display2(struct student) . void display3(struct student *); 2 ‘struct student s1={*Akhil”, 20.,85.5}, struct student “ptr; pir= &st; display1(s1,name,st.cno,s1.marks); display2(s1); Gisplay3(ptr); } fend of main */ /*function display1*/ void display1(char a[40j,int x,float z) printf("%s } . %d %s\n", a,x,x); /*tunction display2*/ void display(struct student s) { printf("%s\n”,s.name); printf(*%f\n",s.marks); + /*function display3*/ printf(“%d\n",s.mo); Mobile : 9985 666 778 Page 16 oe PROGRAMMING IN C (Part - 11) void display(struct student *s) printf(“%s\n",s->name); printf(“%d\n",s->mo); printf(*%f\n”,s->marks); + , UNION A.union is a derived data type, like structure, but only one data member is active at a time. Declaration of a union is similar to a structure. Example: union student £ int rno; char sname[30]; } union student x,y,std{50]; DIFEI BETWI TI STRUCTURE UNION 4.The key word struct | 1.The key word union is used to declare a is used to declare an ructure union Ail data members | 2.Only one date in @ structure are member is active St active at time equal to the sum of the size of all individual data float price; ds; for s total memory required if 404244 required is 40 bytes bytes only. T. Ratna Reddy . Associate Professor, CBIT. " Mobile : 9985 666 778 2012. def The typedef statement defines synonyms for an existing data type. It does not introduce a new data type and does not reserve storage also, The general format is typedef existing_data_type new_data_type Exampie 1: typedef float REAL; REAL area,volume; Example 2: typedef struct account F oat referential structures Fe, if oné or more members are } tO the same structure, then self-referential structure ucture refers to itself is #incllide main() typedef struct list { int data; struct list *next; Hist; list *p,*q,*r 5 p=(list *) malloc(sizeof(list}); q=(list *) matloc(sizeof(list)): r=(list *) malloc(sizeof(list)); p->data: Qe >next=NULL; ->data=3; r->next=NULL; p->next: q->next=r; while(p != NULL) « : printf("%d\n",p->data); p=p->next; e} EP OINUUINEAIEEEINAT AN NM UE GAEL 2h the FILES A file contains data/information which is stored permanently in a storage device. Generally used storage devices are CDs, DVDs & hard disks. When large quantity of data is required to be stored and processed, the concept of fife is used. A file stored in a storage device is always identified ‘using a file name (e.g. STUDENT.DAT, INFO.TXT). Normally a filename has a primary name and a secondary name, which are separated by a dot(.). STUDENT . DAT Primary name separator secondary name The primary and secondary names are assigned by the programmer. Normaniy secondary name is used to identify the nature of the file. Secondary names are optional. TYPES OF FILES BASED ON THE TYPE OF DATA 1. Data file 2. Text file BASED ON THE ACCESSING THE DATA 1. Sequential access files 2. Random access files Data file: A data file contains data stored in the form of records. A record is a collection of data rela t0 a person or item. For example, a student reco contain data like roll number, student né marks obtained by him. A file contains mai records, Imagine the records are arta one as shown in the figure. A data file with records 2249: shekar_ 90 | [2250° swamy 99 oe jntains information stored in the form narecsels. Tie characters enterea keyboard are stored continuously as ihostrated Betove Sequential access file: In sequential file data/information is stored sequentially one by another. The data is read in the same order in which they are stored. T. Rama Reddy . Associate Professor, CBIT. Mobile : 9985 666 778 Random access file: In random access file the data/information can be read randomly. Normally a key is used to identify the required record in random file accessing. FILE DECLARATION A file is declared and the data is a file pointer. It has the following gener FILE *fp; he curent position inthe file ni gets the position to the beginning of the file. tion ‘ fopen() function is used to open a file and “set the file pointer to the beginning/end of a file. It has the following form. fp=fopen(“filename”,”mode”); Where fp refers to file pointer Filename refers to the name of the file to be opened Mode refers to the operation mode to access data The following “mode” are used in data processing. fo) ww to open a file to write data/information “ to open file to read data/information -from the beginning of the file. “a” | to open a file to add data/information at the _ end of an existing file “w+” | to open a file for writing. Data can be read _l after writing, using the same m "r+" | to open a file for reading and w data “a+” | to open a file to write information at the end of a file. Data can be read after writing using the same mode. Example: FILE *fptr,*tfile; fptr=fopen(“STUDENT.DAT”,"w"); tfile=fopen(“info.txt”,"r“); Page 18 PROGRAMMIN oe NOTE: 1. If a file opend in “w” or “w+” mode, the contents will be erased automatically. When a file is opened in “r” or “r+” mode, the file pointer “is always set at the beginning of the file. . Wheit we try ‘to open a file that does not ‘exit, the fopen() function will return a NULL. 2. felose() Function All files that are opened should be closed after all input and output operations with the file. This is to prevent data from getting: corrupted. fclose() function is used to close an active file. It has the following form. fdlose(fp); where fp refers to file pointer. xxceEEEE PROGRAM 1 **8#e RX Program to read data from the keyboard, write it to a file catled INPUT: , again read the same data from the INPUT file, and displaying it on the screen *! #include main { PLE char ¢; “to 1" loop to store data in a file */ printf’ Einter the datatn"); {1 = fopanINPUT’, “w’); white((c =getcharg) t= pute(c, fi); folose(fp); #* PROGRAM 2 **####4x } lower case text from afile and display its ‘upper case equivalent on the screen“! #include main() t ‘T. Ratna Reddy . Associate Professor, CBIT. “Mobile : 9985 666 778 GIN C (Part-I) FILE *fp; char c; fp = fopen(“sample”,"w"); while((c=getc(fp)) != EOF) putchar(toupper(c )); fclose(fp); £24402" — PROGRAMS, +48 EEHE f* Program to count chars, spaces, tabs, afic-riewilines in afile * #include ° main() FILE *fp; Char ch; i int nol=0,;not=0,noc=0,nob=0; fo=fopen(*sturec”,"r"); ile(ty * “if(ch: nol++; if(ch=="‘\v’) not++; + felose(fp); printf("Number of characters = %d\n",noc); printf("Number of blanks = %d\n”,nob); printf(“Number of tabs = %d\n",not); printf("Number of lines = %d\n”,nol); SEO Pa file copy program *! #include main PROGRAM 4 *2268Kx { FILE “fs,“ft; char ch; fs = fopen(‘rect.c°,"r); if(fs=NULL) puts("Cannot open source file’); exit; } fi = fopen(‘rec2.c*,"w’); if((s=NULL) { puts(Cannot open target file”); Page 19 } while(1) { ch = gete(ts); if(ch==EOF) break; else pute(ch,ft); } felose(tt); fclose(fs); *keEKEKK «PROGRAMS *##94# 0% # concatenate two files */ #include void maing, { char ch; FILE “fp1,"fp2: {p1=fopen(“inputt. bt’, "r'); {p2=fopen(‘outputt.txt”,"a"); while ((ch=igetc(fp1)) != EOF) fputc(ch.fp2); fclose(fpt); fclose(fp2); fp1=fopen(“outputt txt","7); while((ch=fgetc(fp1))'= EOF) putchar(ch); {close(fp1); } fscanf() Function fscanf() function is used ; Ms is similar to the scanfQ4 ¥cept thal is used to read data from:disk. It ‘has the following form. iscanf({p,"format string” &v1,&v2,- fprint f() Function . {printf function“is, used to: write data to a file. It is similar ‘to’ printf( fiinction except that fprintf) is used to write data to, the disk. It has the following ee ee SL L52,. LVN), I /* program to create a file “STUDENT.DAT”, contains information such as student roll number, name, total marks. */ #include ) mainQ { PROGRAM 6 *###%eke int i,n,mo,tot; T. Ratna Reddy . Associate Professor, CBIT. Mobile : 9985 666 778 {Fan — ip char sname [20]; FILE “fp; fp =fopen(‘STUDENT.DAT*,"w); printfCHow many students\n"); * scant("%d",&n); /* loop to read n students detalls for(=0;i alj+t}) { temp = afjj; a] = alj+1), alj+1} = temp; } } . } ° for(=O;i void maing { Int af3)(3}, DI3I3}.o13]13]4,9=3,; FILE “fp1;"fp2; fp1=fopenCinput2d.tt",""); fp2=fopen(‘output2d.ba","w"); for(i=0;i +or- long integer number that represent the number of bytes to be skipped. Position > position from which n bytes tobe skipped 0-- beginning ae 1+ current 2- end. Example: long int n=9} fseek(ptr,n,1); fate en(“data’, ” ene : © white#EOF) © ‘putchar(n); by, Dgetethy fcosetty 2 PROGRAM LQ FEHR 1 * copy form one file to other in reverse order */ #include #include void maing) { char file[30]; char ch; FILE *fp;long count,last printf(’‘Enter the name of the file\n"); gets(fite); fo=fopen(file,"r+"); : fseek(fp,OL,2): last = ftell(fp); for(count=1L;count<=tast;count++) { fseek(fp,-count,2); ch=fgetc(fp); HMif(ch!=EOF && ch!= ‘r) putchar(ch); 3 felose(ip); ) : 9985 666 778 Page 21 COMMAND LINE ARGUMENTS C programming language allows passing of parameters to a program during execution. Such parameters are called command line arguments. If ac program has to access and use the command line arguments, it has to be prepared for it. As the main function is executed first on start of execution, the parameters (commiad line arguments), if any, are passed to the function. This is achieved by two parameters argc and argv. argc: an argument argc is a counter, counts the total number of arguments passed from command prompt to the main() argv: An argument argv is an array of pointers to string, that points to each command line arguments, The definition of a program to handle command line arguments is as follows. main ( int argc, char *argv[ J) xxkkEK =~ PROGRAM 1 *# eet /* to display the strings */ #include main(int argo, char *argvi}) { Int 1; printf(“total number of arguments are %ed\n",arg: for(isO:i /a.out hello CBIT Output: - The number of arguments are 3 Ja.out hello CBIT anges 3 Explanation: ay [ o | Glawt { \\o : 2 > _CBIT PROGRAMMING IN C (Part — Ib T. Ratna Reddy . Associate Professor, CBIT. .Mobile : 9985 666.778 Number of arguments are 3,.and the argument aj are -/a.out, hello, CBIT. The pictorial representation is shown’ in fig. *eeee0% | PROGRAM 2 seenened / program to find sum of two numbers */ Hinclude : include main(int argc, char *argv{]) { int sum,a.b; a = atoilargv{t); = atoi(argvi2); sum = atb; ers. Since all arguments are taken as strings, the integers are also taken as strings. Therefore they have to, be converted into integers again, This can be done by using the library functions in siclib,h> The function atoi() converts string to an integer. After converting strings to an integer, acidilion is rnate. xeekEKEX PROGRAM 3 **4ER KE / copying files by using command line arguments */ #include main( int arge, char “argv ])) { FILE “fs, “ft; char ch; fs = fopen(file1,"r); ft = fopen({ile2,"w); while((ch=fgetc(fs) )I=EOF) puic(cn, fy fclose(f); felose(fs); } Page 22

You might also like