0% found this document useful (0 votes)
65 views41 pages

C Unit 1

Uploaded by

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

C Unit 1

Uploaded by

Manish Sen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
FUNDAMENTALS OF C PROGRAMMING STRUCTURE OF AC PROG RAM, DAT, IDENTIFIERS AND KEYWORDS” Q.1. Write a Short note on “C”. Ans. C is a programming language which was developed at AJ & T's f Laboratories of USA in 1972. It was designed and written by Dennis i: This language is powerful and attracting considerable attention wor! id because the software industry is adopting the language to great advaniage The C language is a high level language. It replaced the more familiar languages, such as FORTRAN, COBOL, BASIC, PL/I, and Pascal Where it differs is that C permits very close interaction with the inner working of the computer. C is popular because it is reliable, simple, and easy to use. One main reason for this popularity is portability. It means that a program wntten in C can be transferred easily from one computer to another with minimal changes or none at all. ; 0.2. Write short note on “History of C”. (R.GP.V, Dec. 2001, June 2003) ‘Ans. There were so many languages into existence by 1960, almost each for a specific purpose. For example, COBOL was being used for commercial applications, FORTRAN for Engineering and Scientific applications and so on. So people started thinking that instead of learning and using so many languages, why not use only one language which can program all possible applications. Therefore, an international committee was sct up to develop such a language. This committee came out with a language, ALGOL 60. However. this language never became popular because it seemed too abstract, too general To reduce this abstractness and gencrality, a new language called combined Programming Language (CPL) was developed at Cambridge University. But, itwas very hard to learn and difficult to implement cc gl. 4 rite a short note on “C”. Ans, C is a programming language which was developed at AT & T’s Bell Laboratones of USA in 1972. It was designed and written by Dennis Rite ic This language is powerful and attracting considerable attention worldwide se the software industry is adopting the language to great advantage. ie. becaus The C language is a high level language. It replaced the more famuliar languages, such as FORTRAN, COBOL, BASIC, PL, and Pascal. Where it differs is that C permits very close interaction with the inner working of the computer. C is popular because it is reliable, simple, and easy to use. One main reason for this popularity is portability. It means that a program wnitten in Cc can be transferred easily from one computer to another with minimal changes or none at all. 0.2. Write short note on “History of C”. (R.GP.V., Dec. 2001, June 2003) ‘Ans. There were so many languages into existence by 1960, almost each for a specific purpose. For example, COBOL was being used for commercial applications, FORTRAN for Engineering and Scientific applications and so on. So people started thinking that instead of learning and using so many languages, why not use only one language which can program all possible applications. Therefore, an international committee was set up to develop such a language. This committee came out with a language, ALGOL 60. However, this language never became popular because it seemed t00 abstract, too general. To reduce this abstractness and generality, a new language called combined Programming Language (CPL) was developed al Cambridge University. But, it was very hard to learn and difficult to implement. ON IRGPV. MCAS, BCPL) was developed by yy, ming ru: 7 4. Program i EE This problem by bonne CPLdgnt Comb jniversitY ; out to be too less powe,.” pads Pambridge Univetpnfortunately it summed ed B was writte Petty rouse se good fF 7 e tim La Bt © turned o1 cn by k tog specific: ATONE aps, But lke (BCPL) HCPL, and some Thompson at AT heriting the features f B an > ome of jy. cific. Then. DY oan Ritchie developed c. | atures ofa C language. us distinct fe (R.GPYV, June 2006) es of aC language are as follows — istinct featur’ rit dd : us distin f built-in functions ang age whose rich set 0 any complex program. pabilities ofan assembly language fa high-level language and therefore it is well suited for software and business packages. s written in C are efficient and fast. This is due to its id powerful operators. ble. This means that C programs written for one her with little or no modification. Ans. The vyario! (i) It is a robust lang! ors can be used to wite erat : ” (ii) The C compiler combines the ca) with the features © writing both system (iii) Program: variety of data types an’ (iv) C is highly porta computer can be run on anol (v) C language is well suited for structured programming, thus requiring the user to think of a problem in terms of function modules or blocks. (vi) Another important feature of C is its ability to extend itself. Q.4. Explain the structure of a C program. ‘Ans. AC program can be viewed as a group of building blocks called functions. A function is a subroutine that may contain one or more statements designed to perform a specific task. A C program may contain one or more sections as follows — (i) Documentation secti ction consists of a set of i comment lines giving the name of the program, author and other details : (ii) Link section gives an ins ‘ ; . from the system library, instruction to compiler to link functions (iii) Defi nition section defines all symbolic constant s. (iv) Global decl arall the functions. ton section declares global variables outside of all (v) main( ) fi a e: unction and executable part. Section contains two parts — declaration pat s — declara 5 -2023) (Shivani- ) Fundamentals of C Programming § (a) Declaration part declares all variables used in the executable part. (b) Executable part has at least one statement, which is to be executed. (vi) Subprogram section contains all the user-defined functions that are called in the main function. User defined functions are generally placed immediately after main function, although they may appear in any order. Documentation Section Link Section Definition Section Global Declaration Section main() Function Section { Declaration Part Subprogram Section Function J Function 2 Function 0 Fig. 1.1 An Overview of the Structure of a C Program 0.5. Define data type. Explain the data types supported in C language. (R.GPM., Nov. 2022) Or Describe various data types available in C with examples, (R.GPK, June 2020) Ans. A data type specifies the type of data that a variable can store such as 1 in C language refer to an integer, floating, character, etc Data types used 19 declare various types of functions or variables sis of the type of variable present in a program, n storage, along with the way In extensive system that we use | in a program. Here, on the ba: we determine the space that it occupies I which the stored bit pattern will be interpreted C language is rich in its data types. Storage representation and machine instructions to handle constants differ from machine to machine. C supports four classes of data types (i) Primary data types (ii) User-defined data types (ii) Derived data types (iv) Empty data se 6 Programming ii ES e ort following primary data types, int for All C compilers supp: floating point and double for double D char for character, float for floating point. long, shor in C with Data Structure t, unsigned are extended with them, Oo” IR.GPV., Mca (Sem Mlepey TECistop PRIMARY DATA TYPES Toteger Integral Type signed type unsigned type int unsigned int short int long int types — | Type char or signed char unsigned char int or signed int unsigned int short int or signed short int unsigned short int long int or signed long int unsigned long int float double long double c enables the user to defi definition ’defines an identifier th used as ~ typedef type identifier: unsigned short int unsigned long int Table 1.1 | Size (bits) Character Signed Char Unsigned Char long double Fig. 1.2 Primary Data Types in C The following table 1.1 shows the standard sizes in bits and ranges of daty Range ~ 128 to 127 0 to 255 ~ 32768 to 32767 0 to 65535 128 to 127 0 to 255 - 2,147,483,648 to 2,147, 483,647 0 to 4,294,967,295 3.4e — 38 to 3.4e + 38 1.7 e — 308 to 1.7e + 308 3.4e — 4932 to 1. le + 4932 ne individualized type names. The we at Would represent an existing data type eee eee Fundamentals of G Programming 7 y jsnivani-2023) 8 The syntay of a typedef is identical to that of variable declaration. Some bl examples of type definition are — typedef int units; typedef float marks; Here. units and marks symbolize int and float respectiv ed to declare variables as follows ~ units batchl, batch2; marks name! [50], name2[50]; and batch? are declared as int variables and namel{50] and point array variables. The ely. They can be us batchl name2{50] are declared as 50 elements floating main advantage of typedef is that we can create meaningful data type names for increasing the readability of the program. Derived data types such as arrays, functions, structures and pointers, which may be used as a type. Indentifier — The ‘identifier’ is a user-defined enumerated data type which an contain one of the values enclosed d to declare variables that c rated constants). We can declare variables can be use within the braces (known as enumel to be this new type as follows - enum identifier V1, V2,...5V05 ed variables V1, V2, -- __,Vn can only have one of the values The enumerat yaluel, value2, ..,Waluen. The following assignments are valid — V1 = value3; V5 = valuel; Example - 1 say Sunday}; enum day {Monday. Tuesday enum day week-st, week-end: week-st = Monday; week-end = Friday: if(week-st = Tuesday) Saturday; s integer digits beginning with 0 to all the enumerated week-end The compiler assign: constants automatically. sin Care encl ed only around (single) ¢ as constants sometimes losed within double quotation ot single quotes. osed within double quotes, ni haracter constants. s referred to as Literal — Litera Single quotation marks are Us Character strings can be expressed literals, These take the form of characters encl th Data Structure IRGPV., MCA (Sem, 8 Programming in C wil a part of the literal, but merely Serve as delimitg TS, marks. The quotes are not Following are valid C literals ~ “bingo” “1234” 7 “so shaken as we are, SO wan with care... “\007" oyna” . “Evil to him who evil thinketh A double quote included in and not as a delimiter. A pair called the null string. It is stored as a nu! and has a 0 length. When a literal included in a C program, it 1s actually stored somewhere in , all that is necessary to refer to its pointer, the literal as \”is regarded as part of the litera) f double quotes with nothing between them is I character with nothing Preceding it memory. To access “literal”, For example, when a control string is passed to the printf function, as in printf(‘“a = Yod\n”, a); what actually passed as the first parameter is a pointer to the literal, “a = %d\n” In effect the type of a literal is char*. One exception to the above rule occurs when a literal is used in initializing an array. The declaration char str [] + “bingo”; actually is an abbreviation for the declaration char str [] = {*b’, ‘i’, ‘n’, ‘g’, ‘0’, ‘\0°} where str is declared as a character array and dimensioned to enough elements pieaii ephedra a including the null character. In this case, str would which must he Claes an explicit dimension can be specified, including the mul chee fer than the number of characters in the initializer, 0.6. What are identifiers ? Ans. Refer to Q.5, 2.7. Differentiate between long and unsigned. (R.GPR¥, Jan/Feb. 2008) Qualifier that i: . 7 of the associated variables is mena before the int declaration, the ran long int x; Ans. long is a led, here is a typical example — jvani-2023) ear ee Fundamentals of C Programming 9 that take positive values only. 5) ant the inf declaration with the w. can be doubled. Here is a typical example — unsigned y; Ie unsigne aoe unsigned in Thatis used for variables oa an used for counting. By prefixing , the range of the positive numbers Q.8. What are keywords in C ? Ans. Keywords are th to the C compiler. The ke: © Words whose meaning has already been expl i : -ywords cannot be used as variable n ee so we are ‘ ames beca we do so rying to assign a new meaning to the keyb es because if allowed by the computer. ‘eyboard, which is not There are only 32 keywords available in C. Table 1.2 Keywords auto do signed unsigned break double sizeof void ae else static volatile char enum struct while const extern switch continue float return typeodef default for short union 0.9. Write the differences between data and information. (R.GPM, June 2023) cen data and information are as follows — Ans, Differences betw Information S.No. Data (i) | Data are the variables thathelp | Information ts meaningful data. to develop ideas/conclusion (ii) | Data are text and numerical Information is refined form of values. actual data (ii) | Data does not rely an information While information relies on data (iv) | Data does not have any specific | Information carries a meaning that} purpose. has been assigned by interpreting data. It is the second level of know ledge. (v -level knowledge ) | Itis low-level ke e Information puts those Facts into (vi) | Data is a collection of facts, it self have no meaning context. which PEE | 10 Programming in C with Data Structure IRGPV. Moa (Se, ™.)) OPERATORS & EXPRESSIONS, PREPROCESSOR Dire, Cry INPUT OUTPUT, CASTING, PRECEDENCE Ve, 0.10. What is operator ? Describe the types of operator. Ans. An operator is a symbol that tells the computer to perform ee erat mathematical or logical manipulations. It can operate on integer, characte, ang real numbers. / C operators can be classified into various categories based on their utj and action. They include — (i) Arithmetic operators (ii) Relational operators (iii) Logical operators (iv) Assignment operators (v) Increment or decrement operators (vi) Conditional operators (vii) Bitwise operators (viii) Special operators. lity (i) Arithmetic Operators — The arithmetic operators perform arithmetic operations and can be classified into unary and binary arithmetic operators. The arithmetic operators can operate on any built-in data type. A lis: of arithmetic operators and their meanings are given below — Operator Meaning | + Addition or unary plus - Subtraction or unary minus * Multiplication | / Division | % Modulo division (remainder after division) Integer Arithmetic — When two operands such as a and b are declare’ integers, an arithmetic operation performed on these integers is called intege arithmetic. It always yields an integer value. For example, if a and b are integets then for a = 14 and b = 4, the results are — a-b=10 at+b=18 a*b=56 a/b = 3 (decimal part truncated) a“%h=7 = ¢. ri 1 oo a ———————————— ee {shivani-2023) Fundamentals of C Programming 11 During integer d reals ancated unde cen ie operands are of the same sign, the reseiafion is losplemehiitinn ebeniionk ae is negative, the direction of 6/8 = 0 and -6/-8-0 put — 6/8 may be zero or — 1, similarly, during modulo divi n sion, t f onthe frst operand. That is he sign of the result is always the sign — 14% 3=-2 -14%-3=-2 14%-3=2 Floating Point/Real Arithmetic — An arithmetic operation involving onl: real operands is called real arithmetic. A real operand may assume Ushuee either in decimal or exponential notation. The floating point results are rounded off tothe number of significant digits specified and hence the final value is only an approximation of the correct result. The operator % cannot be used with real operands. For example, if p, q and r are floats, then p = 6.0/7.0 = .857143 q = 1.0/3.0 = .333333 Z=— 2.0/3.0 = — .666667 Mixed Mode Arithmetic — When one of the operands is real and the mode arithmetic expression. other is integer, the expression 1S called a mixed- If either operand 1s real type, then only the real ope! ways a real number. Thus, 15/10.0 = 1.5 15/10 =1 ration 1s performed and the result is al whereas (ii) Relational Operators — arithmetic, logical and character expressio quantities and depending on their relation, take some decisions: These done with the help of relational operators. Each of these hand side with their right hand side. The whole operator then evaluates to an integer. It ‘alse and 1 if it is true Relational operators are used to compare sns, We often compare two similar comparisons can be operators compare their lef expression involving the relational evaluates to zero if the condition 1S f Operator Meaning = Jess than > greater than < less than or equal to > greater than oF equal to equal to not equal to Sam, re tors Dor ETO, ue, tes tO id = j-2023) (snivan’ Fundamentals of C Programming 13 s same as the statement go This i x=x+(y+1); the commonly used shorthand assignment operato rs are — Statement with shorthand operator some of Sratement with simple assignment operator qv) Increment or Decrement Operators — The increment and t operators are very useful in C language. The syntax of the operator S decremen! is given below — 4+ —~ + + —— ‘The operator + + adds I to the operand and — — subtracts | from the operand These operators come in two forms — prefix and postfix. For example. ++ operator can be used in two ways : ++ m and m ++ , wi Conditional Operators (Ternary Operator) — The conditional ator consists of two symbols ~ the question mark (?) and the colon(:). for ternary operator is exp 1 2 exp 2: exp 3; where exp], exp2, and exp3 are expressions. The operator ? : works as follows — exp] is evaluated firs zero (true), then the expression 2 is evaluated and becomes the value of the expression. If exp! is false, exp3 is evaluated and its value becomes the value of the expression. Here, only one of the expressions (either exp 2 or exp 3) is evaluated. For example, oper: The syntax If it is non- e of t a= 10; b= 15; (a>b)2a:b Here, x will be assigned the value of b. on each bit of shifting bits to ble. A list (vii) Bitwise Operators — A bitwise operator operates data, These operators are used for testing, complementing OF the right or left. Bitwise operators may not Pe applied to float or dou of bitwise operators are given below — NGPY, = in C with Data Structure U MCA (1. Sem [Meaning | ’ bitwise AND bitwise OR bitwise XOR shift left shift right bitwise complement 14 Programming ! it Bitwise AND — The statement " c=akb; f i . After this statement is execute, s use of the bitwise AND operator. A’ r nine waibe 1 only if the corresponding bits in both a and b are 1. For @ a 0000 0000 0000 1101 b 0000 0000 0000 O111 a&b 0000 00000000 0101 d, each, Xample Bitwise OR — The statement c=alb; makes use of the bitwise OR operator. After this statement is executed, a bit in c will be 1 whenever at least one of the corresponding bits in a or b is 1. For example, a 0000 0000 0000 1101 b 0000 0000 0000 O111 alb 00000000 0000 1111 Bitwise XOR - The statement c=arb; makes use of the bitwise XOR operator. After this Statement is executed, a bit in c will be 1 whenev, er the Corresponding bits in a and b differ. For example, a 0000 0000 0000 1104 b 0000 000 0000 Ol -0000 0000 1010 The val C=a<<3: ¢ value in the Integer a is shift Fr . i rhe result is assigned to inet ifted to the left by three bits positions. The my) (shivani~ (Shivani-2023) Fundamentals of C Programming 15 Lett shifi << drop off < 0000 0000 0000 1101 < insert 0's after left shift by 3 places. 0000 0000 0110 1000 ight Shift z or eel eee The right shift operator is also a binary operator. c=a>>2; The value of a is shifted to the right by 2 positions. h Right shift > > fs 0000 0000 0000 1101 — drop off after right shift by 2 places 0000 0000 0000 0011 Bitwise Complement Operator — The bitwise complement operator (~) is a unary operator. It gives the value got by complementing each bit of the operand. For example, it is required to clear the least significant (lower most) four bits of an integer i. It can be done using the ! operator as follows — i=i& ! oxf; The integer constant oxf has only its least significant four bits set. When the bitwise complement (~) operator is applied to it, an integer that has all bits set except the least four significant bits, is obtained. Applying the bitwise AND now gives the desired result. (viii) Special Operators — C supports some special operators such as comma operator, sizeof operator, pointer operators (& and*) and member selection operators (.and —). (a) Comma Operator — The comma operator can be used to link related expression together. Operator noes Operation Comma Operand type: Any (the two may be different) ; Meaning : Evaluates the left hand operand for its side effects, then evaluates the right hand operand and returns its value. This operator is used most frequently in for loops. for (a = 1, b=2;a<=20;a ++, b ++) s a compile time operator, and umber of bytes the operand qualifier. Example (b) Sizeof Opera’ When used with an operand, occupies, The operand may be a tor — The sizeof i it returns the n variable, a constant or a data type ~ Structure IRGPRV., MCA ¢) Sem » mming in C with Data Si 16 Progra e Operator ag ‘variable, value, parenthesized type Operand type Returns size (in bytes or chars) of the Operang Meaning aeoftnt) Example With these operators Following (c) Pointer Operators — operations are performed. & Operator operand neil of the return store 7 dtype : Any variable (except oni 880 clay Cee Pe | Returns address of operand Meaning : Examples &a &b(7] ane Operator * Operation Indirection id type Address Nee ia : Returns contents of location whose address ig the 1 operand, can be used on left side of assignment operator, where the value is assigned to the location pointed to by the operand, which may be any pointer expression. Examples ib) at+1)*x=4 (d) Member Selection Operators — These Operators are used in and have following meanings — Operator . Meaning : The structure member or Period operator selects a member of union or structure, Ifa isa structure whose template includes a member named b, then a.b selects member b of structure a, Operator | Meaning : The structure member or arrow Operator selects 1 member from a structure Or union pointed to by Variable. For example, if a points to a structure thé Contains a member b, thena-> ph selects membe bof the Structure pointed to by a. In other words, > bis equivalent to (*a).b. ttc operators are there in C ? Explai: Ins. Refer to Q.10 (i), (R.GPV.,, June 202! OO TESTIS LB ta Stats (Shivani-2023) Fundamentals of C Programming 17 0.12. What is the use of ternary of suitable example. operator in C ? Explain with the help Ans. Refer to Q.10 (vi). Me eeniter Q.13. What is an operator ? Explai - ? Explain the arit ic, relatit ie aiid assignment operators tC lent eae e eliata ie eas logical - GPM, Dec. Ans. Refer to Q.10. ree 14. Explain the use of the sizeof operator. (R.GP.V., June 200 3) : -GRV, June Ans. The sizeof operator is a compile time operator and when used with an operand, it returns the number of bytes the operand occupies. The operand may be a variable, a constant or a data type qualifier. Examples are — m = sizeof(sum); n= sizeof(long int); k = sizeof(235L); The sizeof operator is normally used to determine the lengths of arrays and structures when their sizes are not known. It is also used to allocate memory space dynamically to variables during execution of a program. 0.15. What is an expression ? (R.GPK, Dec. 2014) Ans, An expression consists of a combination of operators, operands, variables and function calls. An expression can be arithmetic, logical or relational. Example — a + b~ Arithmetic operation a> b—Relational operation a == b~ Logical operation Fun (a, b) — Function call 4+21 a * (b + c/dy/20 q=5*2x= +4+q%3 q>3 ination of smaller expressions, called Some expressions are combi subexpressions. For example — c/d is a subexp fC is that ev ression of given example. ery C expression has a value An important property © ee EEN ON RGPV., M ta Structure fi oe 418. Programming in € with Date - ean by 0.16. What do you me or directives ? Give preprocessor directives ? What are the digfoy, “ ys 1 example of each. (RGRV, Aprit rg Or y cessor directives. (R.GRH, June 2020, Now, 29, ) prepracess Write short note on prepro Or What do you mean by preprocessor directives ? List and explain at do ) 4 different categories. ‘Ans, The preprocessor offers several une called Preprocesse directives. Each of these preprocessor directives oe with a # symbol, The directives can be placed anywhere in a program but are most often placed a the beginning of a program, before main( ), or before the beginning of a particular function. The preprocessor directives are — (i) Macro expansion (ii) File inclusion (iii) Conditional inclusion/Conditional compilation. (i) Macro Expansion—Macro expansion is a process where an identifier ina program is replaced by a predefined string composed of one or more tokens, The preprocessor accomplishes this task under the direction of # define statement This statement is known as macro definition. The general form is — #define identifier string (R.GRM, Dec, 24 1 For example — #define PI 3.1415 main( ) cece float r = 6.25; float area; area = PI*r*r; ; printf(“\n Area of circle = %f ”, area); Here, PI in the program is calle corresponding macro expansion A #define directive is al iene So used to define operators as shown below — #define OR || main( ) { int f=1, x=4, y=99. HUESS)AND(x<=20 OR y <=45)) Printf(“\n Your PC will always work fine 'd macro template and 3.1415 is called its else ): print(\n fj r ) (\n front of the Maintenance man "ys wy on % wR oy errant shwam-2023) ( Fundamentals of C Programming 19 #define dire ve A ective could be used even to replace a condition as follows — adetine AND && #define ARANGE (a>25 AND a < 50) main( ) int a=30; if(ARANGE) printf(“within range”); else printf(“out of range”); } A #define directive could be used to replace even an entire C statement as follows ~ #define FOUND printf(“The Yankee Doodle Virus”); main( ) , char signature; if(signature = FOUND Y’) else printf(“safe.....as yet 1"); Macros with Arguments — Macros can have arguments like functions. A simple example of a macro with arguments Is define AREA (x) (3.14 *x*x) main( ) { float r1=6.25; a=AREA (11); printf(“\n Area of circle = %f”, a); a=AREA (12) printf(“\n Area of circle = %f ”, a); } phrase AREA (x) it expands it ___ Here, wherever the into the statement (3.14 *x*x) (ii) File Inclusion— Ifa file contain! that can be included as a part of a program. Preprocessor directive ‘ #include “filename preprocessor finds the ions or macro definition, ing funct e following This is done with th where the filename containing the required definition or functions. This directive can also be used as follows ~ 4include ioe Oo” ‘ Structure IRGPV. MCA (Ls, omy ith Data Programming in Cwil : ; 20. Progra hat are to be included to have ah extension, 15 It is common for files Tomes possible because it contains statem i ds for “header file’, possible DATES extension stan include go to the head of th p lal which when we if types of all mathematics related functions are storeg in For example, pre Prototypes of console input/output functions are Store the header file *ma' in the header file *conio.h’. e meaning. ae ‘his command would look for the file “filename Hinclude “filename” inthe current directory as well as the specified ji, of directories as mentioned in the include search, path that might have been set up. This command would look for the file “filename in the specified list of directories only. We can use inclusion directive in the program as follows ~ Hinclude #define M100 main( ) { ent, #include } (iii) Conditional inclusion/Conditional Compilation —C preprocessor offers a feature called conditional compilation, which can be used to “switch” on or off'a particular line or group of lines in a program C preprocessor supports more general form of test condition. #if - The general form is #if constant expression { statement-1; statement-2; MACHINE Tf the result of Pete festa ©XPression is nonzero (true), then statements © Included for Processing, otherwise skipped TE i (shivani-2023) Fundamentals of C Programming 21 Helse — Helse can be usc : ee n-be used with dif for testing an expression. Let us consider wif TEST <= 5 statement-1; statement-2; statement-3; Helse statement~ statement- statement-6; endif If the expression, TEST < = 5 evaluates to true then statements 1, 2 and 3 are compiled otherwise statements 4, 5 and 6 are compiled. F #elif — If we want to use nested conditional compilation, then #elif directive can be used there. “if | ADAPTER==MA code for monochrome adapter 4elif. ADAPTER == CGA code for colour graphics adapter #elif ADAPTER = = FGA code for enhanced graphics adapter #elif ADAPTER = = VGA code for video graphics array #else code for super video graphics array #endif #ifdef — It can be used, program. Let us consider #ifdef OKAY statement-1; statement-2; statement-3; statement-4; when we would like to compile only a part of #endif. statement-S; statement-6, statement-7; cro OKAY Here, statements 1, 2, 3 and 4 would get compiled only if macro ON has been defined. with Data structure IR.GPV., MCA(I-Sem cro TEST 1s always defined, irrespective 22 Programming in © of ma | : ihe ‘tha ‘b ens din the header file or not. This can be achieveg of whether it has bee! follows — ye #include “DEFINE.H #fndef. TEST #define EST1 #endif s the header file that is supposed to contain the definition or DEFINE.H i TEST macro. The directive #ifndef TEST , / ; he tion of TEST in the header file and if not defined, then searches for the defini all the lines between U 2 #endif directive are lef ‘active’ in the program 1.€., t #define TEST is processed. In case, the TEST has been defined in the header file, #ifndef condition becomes false, therefore the directive #define TEST is ignored We cannot write #define TEST 1, because if TEST is already defined, an he #ifndef and correspondin, he preprocessor directive error will occur. 0.17. Explain the role of C preprocessor. (R.GRM, Dec. 2014) Ans. Refer to Q.16. Q.18. Explain the following preprocessor directives — (i) undef (ii) pragma. Ans. (i) #undef — It may be desirable to cause a defined name to become undefined. This can be done by #undef directive. To undefine a macro that has been earlier #defined, the directive #undef macro template can be used. Thus the statement, #undef PENTIUM wot f would cause the definition of PENTIUM to be removed from the system. All quent #ifdef PENTIUM statements would evaluate to false. (ii) #pragma — It i . #pragma — It is a special purpose directive, that can be used turn on or off certai q in features, Pra; meer There are following pragmas, gmas vary from one compiler to another. (a) #pragm specify functions that are iin and #pragma exit — These allow us pram ‘e1 u c Program exit (just before the poeem een san up (before main( )) o inates). ) or as For example, void funt( ); void fun2( ): *pragma startup fun} #pragma exit fun2 main( ) t } t void funl() { (Shivani-2023) Fi ‘undamentals of © Programming 23 Printf(“\nInside main”), printf(“\n Inside funl”); void fun2( ) { printf(“\n Inside fun2”); Here, functions funI( ) and fun2( ) should neither receive nor return any value. (b) #pragma warn — This tells the compiler whether or not we want to suppress a specific warning. For example, #pragma warn-rv1 #pragma warn-par #pragma warn-rch int f1() { int a=5; /*return value*/ /*parameter not used*/ /*unreachable code*/ void f2(int x) printf(“\n Inside f2"): } int f3() { int x=6; return X; xt+t+; } void main( ) { fI( ); £2(7): BC); eer ith Data Structure IR.GPV., MCA (1. Sem 24 Programming in Cw roblems — There can be three P! a value, *t retu . _ 0) n ) domme x is passed to £2( ) is not being used anywhere in qi) The PO i) The control can never reach x++ In £3( ). . rit t note on formatted input and output. 0.19. Write short (R.GPV, Dec. 2001, June 2004 Or npul/output functions in i so Write about formatted in (R.GP.V, Nov. 2018) Ans. (i) Formatted Input ~ Formatted input refer to an input that has ns. particular format. The scanf( ) function allows us to enter data a the keyboard that wij] be formatted in a certain way. The general form of scanf is — scanf(“format string”, list of addresses of variables); For example — scanf(“%d%f%e”, &e, &a, &ch); Here, we are sending addresses of variables to scanf{ ) function, by using <& the ‘address of” operator. The %d, %f and Yc used in scanf( ) are format string. They tell scanf{ ) to read value for c, a and ch variables, that are of decimal integer, floating-point and character type respectively. We can use a format string %s to input string. (ii) Formatted Output printf — The printf{ ) function gives certain features that can be effectively exploited to control the alignment and spacing of print-outs on the terminals. It is highly desirable that output should be produced in such a way that are understandable and are in an easy to use form. The general form looks like this — printf(“format string”, list of variables); The format string can contain — been arranged in a (a) Characters that are simply printed as they are (b) Conversion specifications that begin with a% sign (c) Escape sequences that begin with a\sign. For example — Pant Average = % din Percentage =%f ” avg, per): ere, Average = is dumpe - id when 944 avg is picked et cape on the screen, and when %d is met the variable alue Is printed. Similarly, when \n is met is places cursor at the beginnin & of next Jin S S! Tomar eee of e. This process continues till the end of Following is the li sto nc function. f format specifi ers that can be used with the printf) s = 3 [R.GPV. MCA (I-Sem p For example, main() { char ch putch(ch putchar(ch) fputchar' ives the string fi ! function gets( ) receives 2. from re one cand) while puts( ) outputs the string to the ing Input Si ut device (Key he standard inp’ < Standard output device (screen) For example, #include yoid main() { ee ss than 80 characters) :””); printf(“\n Type a string (les gets(s)s 7 printf(“\n The string typed is: ds puts(s); } Q.21. What is the difference between character /O and string 1/0 ? (R.GP.V, Dec. 2004) efers to read a character from the standard input unit (the keyboard) and writing it to the standard output unit {the sereen), Reading a single character can be done by following functions ~ getch( ), getche( ), getchar( ). While string 1/O refers to read string containing more than one character from the keyboard and writing it to the standard output unit (the screen). 0.22. Differentiate beoween the following — a past) and putch() — (R.GP.V., Dec. 2004, Jan/Feb. 2008) i) gete : tii oa 1) and getche( ) (R.GRV, Dec. 2004 cha bia ae i J and getche( ) (R.GPM, Jan/Feb. 2008) - (i) puts() and — The puteh( ) fi containing more than one character Puts( ) function is used to print @ string ‘Ans. The character I/O operation i ii) getch() and getche| a single character the iistntit ine i i getch( ) and getche( ) functions read : ype 7 t ‘ hit, The *e” in getche( ) function rests echo Waiting for the enter key t0 Be ter that t echoes (displays) the cha 2m he i spivani-2023) Fundam Pr shiv ‘undamentals of C Programming 27 ‘ato the screen. As against this ge : typed tod is getch() ju: ‘| ‘i typed without echoing it to the screen. 1p dustctorns the charac eee (iii) getchar() and getche() ~ The *e” @ ‘e” in getche( ) fi displays) the character that is typed to dhe beret. =e | ar() works similarly and echo’s character that is typed on the screen put requires enter Key to be typed following the character that was just typed. ae Conversion? i i pe conversion ? How is automatic type conversion done Or Write short note on pe conversion. (R.GP.V,, Dec. 2004) onstants and variables of different types in an C permits mixing of ¢ erts any intermediate values to the proper jon. C automatically conv hat the expression can be evaluated without loosing any significance, implicit pype conversion. d the type of the variable An expre type sou This automat it may happen that lefi-hand side of t e expression is promoted or demoted depen ¢ conversion is known the type of the expression an on the he assignment operators may not be same. Then the ding on the type of the value of th jable on left-hand side o if the operand are of different type converted to the higher type before the o the higher type- The rules fo! (i) An arithmetic oper ves an integer result. (ii) Operation bet (ii), Operation be! vari the lower type is automatically peration proceeds. The result is of teger values in C are — 1 conversion of floating point and in} ger and integer always ation between an inte} always gives a real result tween a real and real al always gives a real result tween an integer and re For example - inti; float b; i= 3.5; b= 30; Here in first assignment statement the value of i, is float cannot be stored ini, since it is an inf. In this sense. the float is demoted to an int and then its u ed in i is 3. In next statement, its exactly b, because get stor d to 30,000000 and then stored 1n value is stored and we opposite and here 30 is promote it is defined as floating point. All short and char are automatically converted to it~ (i) Ifone of the operands is long double, the othe to long double and the result will be dong double. (ii) If one of the operands is double, the ol double and the result will be double. r will be converted her will be converted 0 a eee! A [R.GRV., MCA(1-Sop, }) jth Data Structure erands is float the o 28 Programming in C wi ne of the oP’ 1 be float. : II bef ds is unsigned long int, the other wil, d long int and the result will be unsigned long int. Jong int and the other is unsigned ; nt ther will converted to y, Poy (iii) If 07 and the result w! (iv) If one of the operan converted to unsigne' (v) If one of the operands is e converted to /ong int, the unsigned j d the result will be /ong int. int Il be converted to unsigned long jn, then — int can be (a) If unsigned i operand will be converted as such an (b) Else, both operands wi! and the result will be unsigned long int. , rands is /ong int, the other will be converteg to (vi) If one of the ope and the result will be Jong int. erands is unsigned int, the other will be converteg Il be unsigned int. long int (vii) If one of the op to unsigned int the result wi 0.24. Write short note on type casting. .s we are required to force the compiler to explicitly conver, pe, it is known as Ape casting, (R.GPV, June 2004 Ans, Sometime: the value of an expression to a particular data ty The general form of casting is — (ppe-name) expression where type-name is a standard C data type. The expression may be a constant, variable or an expression. , The following example illustrates the need for explicit conversion — inti, j; float f; i= 12; j fil: printf(“\n%f ”, fs The is ¢ output of this sequence of statements is as follows — 5 s This is inspite of th s e fact that 12/5 is 2 i both i and j are integers in the expression. “A and it can be assigned to f Since f=i/jj; integer di 1 8er division takes place, and the quotient 2 i. . nt 2 is assigned to f. Though the : variable on the left- variable, it does ae he 7 -2023) (shivant : Fundamentals of C Programming 29 0.25. Write short note on type conversion and type casting. a Refer to Q.23 and Q.24, (R.GPV., Nov. 2018) 9.26. Explain what do you mean by operation precedence. (R.GPK, June 2003) Or What do you mean by associativity of operatorys ? Give suitable example also. : (R.GPV., June 2004, 2006) ‘Ans. The precedence of an operator is used to determine how an expression involving more than one operator is evaluated. There are distinct levels of dence and an operator may belong to one of the levels. The operators at prece’ recedence are evaluated first. The operators of the same the higher level of P' precedence are evaluat the level. This is known as associativity property of an operator. Table 1.3 provides a complete list of operators, their precedence levels, rules of association. The groups are listed in the order of decreasing ce (1 indicate) the highest precedence level and 15 the lowest). ted cither left to right or from right to left, depending on and their preceden For example, if(x== 10+ 15 && y< 10) addition operator has a higher priority ational operator (== and <). Therefore, This is equivalent to The precedence rules say that the than the logical operator (&&) and the rel: dition of 10 and 15 is performed first if (x == 25 && y < 10) d whether x ts equal to ared to = the adi Now, it is to be determine: 25 and y is less than 10. Since the operator < has a higher priority comp: < 10 is tested first and then x = = 25 is tested. 1.3 Operators Precedence Precedence| Associa tin Table Category | Operator Operation Function call Highest () precedence 0) Array subseript > C indirect component 1 LOR (left-to-right) selector C scope access/ resolution C direct component selector 30 Programming in C with Data Structure “if'a then x, else y") S Unary ! Logical negation (NOT) omy 7 Bitwise (1's) component + | Unary plus | Unary minus | ++ | Preincrement or 2 R postinerement (right i ~~ | Predecrement or wel postdecrement & Address. * Indirection sizeof | (Returns size of operand, in bytes) Member ” Dereference 3 Access -> * | Dereference Lar Multiplication] * Muluply / Divide 4 L3r % | Remainder (modulus) Additive + Binary plus = | Binary minus 5 Tar Shift << | Shift left 6 >> | Shift right Tar Relational < Less than Less than or equal to > | Greater than : TOR Greater than or equal to to Equality = Equal to 8 L != | Not equal to Sie Bitwise AND Bitwise AND 9 LOR Bitwise XOR Bitwise XOR 10 LoR Bitwise OR Bitwise OR ll LOR Logical AND a Logical AND 12 LoR Logical OR -ogical OR 13 LOR Conditional xy Means 14 RoL Assignment “- = (a ee assignment Assign product Assign quotient Assign remainder ee (shivam-2023) Fi ‘undamentals of C Programming 31 (modulus) += | Assign sum = | Assign difference 7 ia & = | Assign bitwise AND = | Assign bitwise XOR |= | Assign bitwise OR <<= | Assign left shift >> = | Assign right shift oma ; Evaluate 16 L>R SS PEA ASN SCOPE OF VARIABLES, CONTROL CONSTRUCTS AND ITERATION CONSTRUCTS a Q.27. What is a constant ? Discuss types of constant. ‘Ans. A constant 1s a quantity or fixed value that does not change during nn of a program. This quantity can be stored at a location in the the executiol memory of the computer. The types of constants supported by C, are illustrated in fig. 14. CONSTANTS Numeric Constants String Real Constants Constants Integer Constants Fig. 1.4 Basic Types of C Constants eger constant consists of one or more An inte ary minus 1S considered as a negative er/orL: (i) Integer Constants — digits. An integer preceded by a un constant. A long constant 1s followed by a lett 12345678L or 12345678! Some C compilers require an unsigned constant to be followed by u or U. An integer begins with digit 0 is taken to be octal, and can contain the digits 0 throueh 7 An integer begins with Ox or OX is taken (6 be hexadecimal. an can eet through 9 and letters a through fand or A through F 7 0423 N\ [R.GPV., MCA (1-Sep, )) rructure with pata St ~pnstants — ® floating point constant , ‘ay 32 Programming inc (ii) Floating Poin two forms ~ _ This consists of a series of digi, followed by a decimal points, 5, he whole part or the fractional 7 | point cannot be omitted. Pan otation ¢ number, represenung th part. TI series of dig can be omitte Example — 3.27 (b) Scientific oF Exponential Notation — This consists of , mantissa In decimal notation, followed by the letter € OF E, followed by an exponent. The exponent consi tional plus or minus sign, followeg by a series of digits (forming a wh Example — 29.9E-45 (iii) Character Constants with in single quotation marks. T Examples of character constants are — soxe Here 'S' is not the same as number ; Itcan be represented either directly or as an escape sequence. An escape sequence isa multi-character combination, with a backslash as the first character representin; a single character. It may be one of the following special sequences — . d, but n Acharacter constant consists of a characte . i any ASCII character set, he character can be 5. The last constant is a blank space. Character Represented Escape Sequence \b " backspace 1 \n tab \f newline | ” form feed \' return \ single quote(aj postrophe | backslash eee) | (iv) String Constants — A enctose 2, — A string constant i “Hello” pace. Examples are — ® numbers, Spe “1987” “Well Done” “5 +3" ar 8 ni- 2023, isnwvani-2023) 33 Fundamentals of C Programming ote that character constant *X° is Not onstant *X° is not equivalent to the single character string constant i Escape sequences are permitted. The representation of double quotation ks within the string requires escape sequence \ whereas single quotes can be written directly. A string constant always is stored marl in a specific location in memory. meaning it has an address. It contains all character specified in the string, followed by a null character as a terminator. By this, the string should not contain a mull. The trpe of a string literal is char™. (x) Pointer Constants — These include the name of an array without d the name ofa function without parentheses. A string literal actually subscripts an js an instance of a constant pointer, since its value is a pointer to the string, Q.28. What is a variable ? (R.GPV, Dec. 2014) ‘Ans. Variable names are names given to locations in the memory of computer where different constants are stored. These locations can contain integer, real or character constants. In any language. the type of variables that it can support depend on the types of constants that it can handle. A variable can have only one value assigned to it at any given time during the execution of the program. y change during the execution of the program. Its value ma me can be chosen by the programmer in a meanir ngful way so as A variable nai to reflect its function or nature in the program. Some examples of such names are Average height Total s. digits, and the underscore (_) A variable name may consist of letters character, satisfying the following conditions (i) It must begin with a letter. However, some systems permit underscore as the first character. (ii) ANSI standard recognizes a length of 32 characters. However, the length should not be normally more than eight characters (iii) Uppercase and lowercase are That is, the variable sum is not the same as SUM. (iv) The variable name shou (v) White spaces are not allow ed significant. Id not be a keyword. Examples — Delhi xl ph_value distance N IRGPV.. MCA (.S, 1, it Structure ith Data ; “ 1s and variables. 34. Programming 7 constan 19, Explain the concept of 62” (RGR, Dec, my, 0.29. Es , 27 and Q.28. . Ans. Refer to Q27 1 the scope, visibility and lifetime rules for Vario y, explain abou! s 9.30, Explain ' tions. types of variables in func Or isibility and life ti : detail by giving example SCOPE rear and | life. time vue Explain in detail by gi" GRY, Jan/Feb, 299 for various types of Varia! or a ; d by scope, lifetime and visibility of variables ? What do you understand 0Y (R.GPK, Dec. 2915 y f the storage classes, that is — le has any one 0 ‘Ans. In C, a variab) (i) Automatic variables. (ii) Static variables. (iu) Register variables. (iv) External rs ee ee le determines s var is tle ores ie, active. The visibility refers to the accessability of a variable from the memory and lifetime refers to the period during which a variable returns a given value during the execution of a program Le., alive. The variables can be declared as local (internal) and global (external), Local is that declared with in a function, while global is declared outside the function. Table 1.4 gives the information on the visibility and the lifetime of variables in the function and files. Table 1.4 Scope and Lifetime Storage class|_ Where declared Visibility (Active) | Lifetime (Active) None Before all functions | Entire file plus Entire program ina file (may be other files where (Global) initialized). variable is declared | with extern, Extern Before all functions Entre file plus Global ina file (cannot be | other files where initialized) variable is declared extern and the file where originally declared as global. Only in that file [Global t | Static Before all functions. 19 a file. Is of C Programming 35 ishivani-2023) Fundamenta None oF auto | Inside a function (or| Only in that Until end of block) function or block. } function or block Register Inside a function Only in that Until end of or block function or block. | function or block static Inside a function Only in that Global function short notes on the local and global variables. Q.31. Write Or (R.GPV,, June 2008) pistinguish berween the global and local variables. on (RGRM, Dec. 2014, June 2020) ept of local and global (R.GPM, Dec. 2016) d local variables, such a function in which that is declared. It1s also known les are visible and meaningful only inside the y are not known to other functions. | remains with in the block function, that variable Expain with the help of an example the conc variable. ‘Ans, Variables declar fe is said to be local to the riables. Local variabl functions in which they are declared. The The life of the local variable exists till the contro! on, in which that variable is defined. Out of this ed within functions are calle variabl as internal val of functi does not exist. When variables declared before main and other functions, are called global in the program. Its need not be din all the functions 1 A global variable is also called an exte! ill the execution of a program does ons of a program. variables. These can be uses declared in other functions. nal variable. The life of the global variable e not come to the end. This variable Consider the following example int m; main() { xists t exists in all the funct inti; float balance; function I( ); function I( ) inti; float sum:

You might also like