Staff Handled By



PROGRAMMING IN C SYLLABUS Unit-I Structure of a C program – C character set – Delimiters – Keywords – identifiers – Constants – variables – rules for defining Variables – data types – Declaring and initializing variables – type Conversion. Operators and expressions Unit-II Formatted and Unformatted Input and output functions – Decision Statements – loop Control Statements. Unit-III Arrays : Array initialization – definition – characteristics- one – dimensional array, predefined streams- Two- dimensional array – Three or multi dimensional arrays. Strings and Standard functions:Declaration and initialization of string- Display of string with different formats – String standard functions – Application of strings. Pointers: Features, Pointer declaration, Arithmetic Operations with pointersPointers and Array – Pointers and Two-dimensional array – Array of pointers – Pointers to pointers – Pointer and Strings –Void pointers. Functions: Definition, Declaration, The return statement, Types of functions, Call by value and Call by reference, Functions returning more values, Functions as an argument. Functions with Arrays and pointers – Recursion – Preprocessor Directives. Unit-IV Structure and Union: Features of structure, Declaration and initialization of structure, Structure within structure, Array of structure, Pointer to structure, Bit fields, Union. Unit-V Files: Streams and file types, Steps for file operation, File I/O, Structures read and write, other file functions, Command line arguments, I/O redirection


Unit-I Introduction to C programming - Structure of a C program – C character set – Delimiters – Keywords – identifiers – Constants – variables – rules for defining Variables – data types – Declaring and initializing variables – type Conversion. Operators and expressions Introduction to C programming C was an offspring of ‘Basic Combined Programming Language’(bcpl) called B, developed in the 1960’s at Cambridge university. B language was modified by Dennis Ritchie and was implemented at Bell Laboratories in 1972.The new language was named as C. since it was developed along with UNIX operating system, it is strongly associated with UNIX. It can run under various operating systems including MSDOS. Importance of C: 1. It is robust language. 2. Rich set of built-in functions and operators are available. 3. Easy to create complex programs. 4. Suitable to write both application software as well as system software. 5. It is highly portable. Because C programs written for one computer can be run on another with little or no modification. 6. It is well suited for structured programming. So that it is easy to debug, test and maintain a module. 7. It can extend itself. Basic structure of C programming: Documentation section link section

Definition section Global declaration section Main( ) function section { declaration part executable part } Subprogram section function 1 function 2 function 3 . e) Executable Part: This part contains the statement following the declarations of the variables. This section must be declared outside of all the functions. The function main ( ) is a starting point of every C program. f) User-defined function: The functions defined by the user are called user-defined functions. These functions are generally defined after the main ( ) function. These variables are known as global variables. #include <stdio. This portion is not compulsory. function n a) Include header file section: A C program depends upon some header files for function definition that are used in the program. Empty parenthesis after main is necessary.h> b) Global declaration: This section declares some variables that are used in more than one function. Initializations of variables are also done in this section.h extension. Initialization means providing initial value to the variables. . This part contains a set of statements or a single statement. d) Declaration Part: It declares the entire variables that are used in the executable part. They can be also be defined before main ( ) function. Eg. These statements are enclosed between braces. g) Comments: . Each header file has . The execution of the program always begins with the function main ( ). c) Function main ( ): Every program in C must contain main ( ) function.

The characters in C are classified into the following characteristics. Character Set 1) Letters 2) Digits 3) White Spaces Blank Space Horizontal Tab Vertical Tab New Line Form Feed Capital A to All decimal digits 0 to 9 Z Small a to z 4) Special Characters: . Comments can be inserted by the programmer. Semi – colon * Asterisk : Colon Minus ` Apostrophe + Plus “ Quotation < Less than mark ! Exclamation > Greater than mark Vertical bar ( Parenthesis left / ) right / Slash [ Bracket left / ] right \ Back slash { Braces left / right } ~ Tilde % Percent _ Under score # Number sign or hash $ Dollar = Equal to . Letters 2. White Spaces 4. Period or dot ^ Caret . Digits 3. The clarity of the program can be followed if it is properly documented. numbers and expressions depending upon the computer on which the program runs. the programmer can include comments in the program. Special characters. These are useful for documentation. Comma & Ampersand .It is not compulsory in a program. However to understand the flow of a program. Example / * This is a single comment * / / * This is an example of / * nested comments * / * / / * This is an example of comments with multiple lines * / / * It can be nested * / C Character Set The characters are used to form words. 1.

consisting of sequence of letters and digits. The keywords cannot be used as variable names because they have been assigned fixed jobs. The underscore ( _ ) . They are assigned a fixed meaning. Lower case letters are preferred. the upper case letters also permitted. However. which are called as delimiters. Comma Variable separator The C keywords: The C keywords are reserved words by a compiler. functions and arrays. However. with the letter as the first character. They are user-defined names.? Question @ At the rate mark Delimiters: Language pattern of C uses special kinds of symbols. Semi Colon Terminates statement ( ) Used in expression and Parenthesis function [ ] Square Used for array bracket declaration { } Curly Scope of statement brace # Hash Preprocessor directive . few compilers allow to construct a variable name. The description of the keywords is given below. Delimiters Use : Colon Useful for label . For utilizing the keywords in a program no header file is to be included. They are given as under. auto doub int struct le break else long switch case enu regist typede m er f char exter retur union n n const float short unsign ed contin for signe void ue d defaul goto sizeof volatil t e do if static while Additional keywords for Borland C asm if static while Identifiers: Identifiers are names of variables. which exactly coincides with the keywords.

Examples: 1) ‘a’ 2) ’#’ 3) ’2’ . #define N 10 2. Many parameters or quantities are defined not only in integers but also in real numbers. They are classified as follows. There are several types of constants in C. Example: 1) 54.98 2) 25. They are also represented with a single digit or a single special symbol or white space enclosed within a pair of single quote marks. Character constants: 1. A.75 B. 20. The number without a sign is assumed as positive. #define a 15 Here “N” and “a” are user-defined identifiers. Example: 1. Integer constants can either be positive. Constants: The constants in C are applicable to the values that do not change during the execution of a program. +30. It requires minimum two bytes and maximum 4 bytes. Numerical constants: 1) Integer constants: It refers to a sequence of digits from 0 to 9 without decimal points or fractional part or other symbols. negative or maybe zero. Example: 10. -15 2) Real constants: The numbers with fractional part is called real or floating-point constants. Single character constants: A character constant is a single character.symbol can be used as an identifier.

a.. “C” Data Types: Data is a collection of characters. Rules for forming a variable: 1. Basic data type b. C data types are classified into the following categories. “India”. 6. “444”. 2. Upper and lower case are significant. The maximum number of characters in a variable may be 8 characters. digits. The number of characters differs from compiler to compiler. The string may be a combination of all kinds of symbols. symbols etc. User-defined data type d. 5. The first character may be followed by a sequence of letters or digits. the data are used to represent information. The starting character should be a letter.4) ’ ’ 2. Special characters except _(underscore) symbol are not allowed. White space is not allowed. String Constants: They are a sequence of characters enclosed within a double quote marks. Example: “ Hello”. 4. Example: TOTAL is not same as total or Total. Derived data type c. A variable may take different values at different times during the program execution. Variables: A variable is a data name that may be used to hold a data value. Void data type . “a”. 3. The variable should not be a keyword. The data are classified in various types.

32768 to 32767 0 to 65535 .7E + 308 3.1E +4932 .7E – 308 to 1.32768 to 32767 0 to 65535 .4E.4E+38 1.32768 to 32767 .32768 to 32767 .Basic Data types: The basic data types supported by C are described with their size in bytes and ranges.4E – 4932 to 1. Data Type char unsigned char signed char Int unsigned int signed int short int unsigned short int signed short int long int signed long int unsigned long int float double long double enum Derived Data type: Size Bytes 1 1 1 2 2 2 2 2 2 4 4 4 4 8 10 2 in Range -128 to 127 0 to 255 -128 to 127 .38 to 3.32768 to 32767 2147483648 2147483647 2147483648 2147483647 0 to 4294967295 to to 3.

Pointers can have any name that is legal for other variables and it is declared in the same fashion like other variables but it is always denoted by ‘*’ operator. After execution of funA( ) and funB( ) the program control returns back to the calling function main( ). Variables: A variable is a data name that may be used to hold a data value. Rules for forming a variable: 1. These are invoked from the body of main. Arrays 1. Functions: A function is a self-contained block or a sub-program of one or more statements that perform a special task when called. Pointers 2. In the same way ‘f’ is a float pointer that stores the address of any float variable and ‘y’ is a character pointer that stores the address of any character variable. A variable may take different values at different times during the program execution. char *y. Functions 3. float *f.The derived data types are of the following types: 1. 3. int b[4]. . 2. Eg. Arrays An array is a collection of elements of similar data types in which each element is located in separate memory location. In the first statement ‘x’ is an integer pointer that tells to the compiler that it holds the address of any integer variable. In fig funA( ) and funB( ) are two user-defined functions. Pointers: A pointer is a memory variable that stores a memory address.The starting character should be a letter. int *x.

1868 2. Integral type: a.long signed int iv. (area) allowed 3.unsigned int v. 4. Floating-point type i. User. Integer i.The maximum number of characters may be 8 characters. Character i. Primary data types. double Reason 1) The first letter should be a letter 2) Special characters not 3) Number should not be a 4) Special characters not allowed size 16 8 bits 32 bits 16 8 32 bits bits bits bits 8 bits 8 bits 32 bits 64 bits . 5.Upper and lower case are significant.White space is not allowed. Derived data type 4.unsigned long int b. signed char ii. john 2.short signed int iii.unsigned short int vi. it differs 3.2. a1 Invalid examples: 1. empty data set Primary data types: 1. value 3.defined data type 3. % Data types: 1. 6.Special characters except _(underscore) symbol is not allowed. signed int ii. Example: TOTAL is not same as total or Total.The variable should not be a keyword. 2. float ii. tot_amt 4. unsigned char 2. Valid examples: 1. 27th first character 4.

type definition 2. 4. It specifies what type of data the variable will hold.v2. double a1. float area.volume. The user-defined type is later used to declare variables. 2. 5. long double 80 bits Declaration of variables: Purpose: 1. enumerated data type Type definition: Purpose: This allows the user to define the identifier that would represent an existing data type. General form: keyword equivalent char unsigned char signed char signed int to int signed short int signed ling int unsigned int or unsigned int unsigned short int unsigned long int float double long double .iii. char array. int a. Syntax: v1.variables Example: 1.b. 3.v3…. data type character unsigned character signed character signed integer signed short integer signed long integer unsigned integer unsigned short integer unsigned long integer floating point double precision extended double precision User defined declaration: Types: 1. int count. It tells the compiler what the variable name is.

…value n. Enumerated data type: It is defined as follows It is used to declare the variables that can have one of the values enclosed within braces(known as enumerated constants). week_end=saturday.value2 as 1 and so on.sunday}. we can assign values like 2. In the above Wednesday will take the value of 6. We can compare the values like 3.batch2.…sunday}.if (week_beg == friday) week_end=thursday. The compiler automatically assigns integer digits beginning with 0 to all the enumeration constants.tuesday=5. Examples: 1.…vn can have one of the values value1.value2.week_end.keyword Type . However the automatic assignments can be overridden by assigning values explicitly to the enumeration constants.name1[20].v2. enum day week_beg.Typedef . . Units name[10].tuesday.exiting data type Identifier –new name given to the data type Typedef cannot create a new type. Thus the enumeration constants assign value1 as 0. Using identifier the variables can be declared using the following syntax: Examples: Typedef int units. enum day {monday.Thursday will take 7 and so on. week_beg=sunday. Example: enum day {monday=1. Units batch1.….we can declare variables to be of this ‘new’ type as below: The enumerated variables v1.

enum month(Jan. No need to declare the global variables in all functions. printf(“\nDec=%d”. main( ) { int I.Mar.Nov.Dec). printf(“\nFeb=%d”.Feb.Jul.Jun. feb to 1 and so on.Oct.Sep. clrscr(). .Jun. It is also known external variable.May. } OUTPUT: Jan=0 Feb=1 June=5 Dec=11 Explanation: In the above program enumerated data type month is declared with 12-month names within two curly braces.Nov.Dec). Example: /*example of storage classes*/ int m.Apr.Sep. The enumerators are the identifiers Jan. By default the compiler assign value from 0 onwards.Feb. Global and local variables: Global variable is visible to all functions in the file.Apr. Using printf() statement the constants are displayed for different identifier.May.h> Void main() { enum month(Jan.Oct.Dec) this statement creates user defined data type.Mar. Their values are constant unsigned integers and start from 0.Mar.Apr.Aug. The compiler assign 0 value to first identifier and 11 to last identifier. printf(“\nJune=%d”.Jul.Feb. Instead of 0 the programmer can initialize his/her own constant to each identifier.Feb). printf(“\nJan=%d”.Dec. #include <stdio. the identifier jan refers to 0. The identifiers are not to be enclosed with in quotation marks.Sep.Jun. Write a program to create enumerated data type for 12 months. Display their values in integer constants.Jul.June).Aug.h> #include <conio.Oct. the keyword enum is followed by the tag name month.Jan). Local variable is visible and meaningful only inside the function in which they are declared.May.Aug. It is necessary to declare the variable before the main function.Nov.

.static value even after 3. extern long total.register Example: auto int count.float balance.. function1( ). local variable which exists and retains it ‘s control is transferred to the calling function.extern 4. auto where it is declared 2. Examples: . Types 1. …… …… } Storage classes: Purpose: It provides the information about location and visibility of variables. Assignment statement: Purpose : values can be assigned to variables using the assignment operator = as follows meaning local variable known only to the function default is auto. register char ch. } function1( ) { int i. ……. float sum. static int x. ……. global variable known to all function sin the file local variable which is stored in the register.

It is possible to assign the values during declaration time as follows: Example: Declaring a variable as Constant : Purpose : To maintain the value of variable throughout the program execution we are declaring the variable as constant. The ampersand symbol & before the variable name is an operator that specifies the variable name’s address Example : %d. Syntax: The control string contains the format of data being received. Example: Reading the data from the keyboard: Another way of giving values to variables is to input data through keyboard using the scanf function.represents integer value %f“ float number %c“ character %lf .“ double %u “ unsigned int Output using printf: Purpose : It is used to display the output as well as to create an interactive program . Syntax: .

Operator Meaning < is less than > is greater than > is greater than or equal to <= is lesser than or equal to == is equal to != is not equal to Logical operators: Purpose : To combine two or more expressions. Special operators Arithmetic operators: Arithmetic operators are used to perform arithmetic operations like addition . Types: 1. Operator meaning && logical and || logical or ! logical not Assignment operators: = is used to assign value to a variable.*. Relational operators 3. subtraction. Increment and decrement operators 6. Assignment operators 5. Logical operators 4. Bitwise operators 8. The corresponding symbols are +(addition or unary plus).C does not have an operator exponentiation.(subtraction or unary minus)./.. Conditional operators 7. Relational operators: Purpose: To relate any two or more quantities. Arithmetic operators 2.% (modulo division). multiplication and division and to find the remaindering division.Operators : Purpose : It is used to tell the computer to manipulate data and variables. In addition .

y=m++. a=a+1 a=a-1 a=a*1 a=a/1 a=a%b Advantages: Statement Hand a+=1 a-=1 a*=1 a/=1 a%=b this c has shorthand operators.subtracts 1 unary operators Example: ++m. It is easy to read. In the above case m and y would be 6. The statement is more concise and clear. 2. Similarly for the --operator. The statement is more efficient. Syntax: Statement with simple with short Assignment operator. Increment and Decrement operators: Purpose: To decrement the value of the variable by one or to increment the value of the variable by one. In the above case m would be 6 and y would be 5.adds 1 to the operand -. Operators: ++ . 4. (++ as postfix operator) If they are used independently then meaning is same. operator. Consider the following m=5. Conditional operator: Purpose: A ternary operator pair “?:” is used to construct . y=++m. No need to repeat the operator again in the right hand side.. m=5. 3. (++ used as prefix operator) m++.

and -> . The above syntax is equivalent to if …else statement. Logical Arithmetic expression: Operand combined with arithmetic operators called as arithmetic expressions Examples: a+b c-d Types: 1. In the above the condition is evaluated first . Operator & | ^ << >> ~ Meaning bitwise AND bitwise OR bitwise EXCLUSIVE OR shift left shift right one’s complement Special operators: sizeof .conditional expressions Syntax: Example : x=(a>b)?a:b.pointer operator Expressions: Combination of both operand and operator.member selection operator & and * . Arithmetic 2. Types: 1.if true then a will be assigned to x or else b will be assigned to x. Bitwise operators: Purpose: Manipulating the data at bit level. Integer arithmetic 2. Real arithmetic .y=17.(comma) .to determine the size of the variable .x+y) . Relational link the related expressions together example : value=(x=10.

5. 4. 1. If one is unsigned long int and other one is long int then a. Logical AND 3. Real arithmetic: Arithmetic operator combined with real operands. Unsigned long int will be converted into long int or . 3. High priority * / % left to right Low priority + Logical expression: Whenever the logical operators combine any two relational expressions then it is called logical expression. Else if one is unsigned long int then other will be unsigned long int. Example: ((a<b )&& (c>d)) Operator precedence: 1. where a and b are of type integer. Example: a + b where a and b are of type real. Else if one is float then other will be float. Logical NOT 2. Evaluation of expression: Expression evaluation based on the priority of operators. Mixed mode arithmetic: Expression consists of both integer and real operands. 2. All short and char to int. Logical OR Type conversions in expressions: If operands are of different types then the lower type is automatically converted into higher type before the operation proceeds. If one of the operand is long double then other will be converted into long double. 6. The result is of higher type. Example: a-b where a is of type integer and b is of type real.3. Else if one is double then other will be converted into double. Mixed arithmetic Integer arithmetic: Arithmetic operator combined with integer operands. Example: a + b.

Explain about mixed mode arithmetic operations 8. Long int will be converted into unsigned long int.Explain Structure of C Program with suitable examples. 17. 15. 9.b. 16. General form of Casting: Suggested Questions 3. ratio is of type float. . List out the rules to declare a variables.What is type casting.Explain data types supported by C 11.Write a program Which combine all the operators. Casting a value: If we need to force the type conversion explicitly then it is called as coercion. Explain about operators supported by C 10.What is Identifiers. What is the name for data type conversion? 7. Where number 1 and number2 are of type integer type.Explain arithmetic & relational operators? 13. 5. What are unary operators? 4. Example: ratio=(float) number1/number2. Where was C orginally developed and by whom? 6. 14. Write short notes on logical operators.What is variables.Give the hierarchy of operator precendences covering all of the operators in C 12. Give an example for short hand assignment operator.

Control/Decision making statements: 1.Switch statement 3. B.Conditional operator statement 4.Goto statement If statement: Purpose: It is a powerful decision making statement to control the flow of execution.If statement 2.STUDY MATERIAL COURSE SEMESTER UNIT SUBJECT NAME LECTURER NAME NUMBER OF PAGES DATE OF ISSUE Unit-II Decision Statements – loop Control Statements.MYTHILI 7 true Different forms of IF statement: 1.Sc ECS : III II PROGRAMMING IN C : D. Syntax: It allows the system to evaluate the expression first and then. entry false : : : : : II YEAR A. depending on whether the value is true or false it transfers the Control to the particular statement. It is basically two-way decision statement and is used in conjunction with and expression. Simple if statement .

otherwise the false block statement are executed. immediately following by the If statement are executed. If …else statement: Syntax: Above statement if the test expression is true then true block statement. Else if ladder Simple if statement: Syntax: In the above statement if test expression is true then statement block will be executed else statement block will be skipped. Nested if … else statement 4.2. If …else statement 3. In either case either true block will be executed or false block will be executed but not both. Nesting of if … else statement: Syntax: .

The switch tests the value of given variable (or) expression against a list of case values and when a match is found. a block of statements associated with that case is executed. if the second condition is false then the statement 2 will be executed. Syntax: . Else … if ladder: Syntax: The condition are evaluated from the top to bottom as soon as a true condition is found. the statement associated with it is executed and the control is transferred to the statement x.In the above statement if the condition 1 is true then the second if condition 2 will be tested and if it is also true then the statement 1 will be executed. When all the ‘n’ conditions become false then the final else containing the default-statement will be executed. The Switch statement: Purpose: Using the value of any variable or expression uses it to select one branch among several alternatives. If the first condition is false then the statement 3 will be executed.

When a switch is executed. default: c=a/b.…. --------------------------------Loop constructs: Purpose: It is used to repeat the block of statements for n number of times. Incrementing the counter. break. There is no need to put braces around these blocks. Test for a specified condition for execution of the loop. Process involved in looping statement is as follows:1. The break statement is used to exit from the switch statement. case 2: c=a-b.. break.c). break. Each of these values should be unique within a switch statement.…. } printf(“%d”. 3.In the above syntax the expression is an integer expression or characters the value-1. The case labels must end with a colon. 4. Setting and initialization of counter. then the block of statements that follows the case are executed. if matches. Example: ------------------switch(n) { case 1: c=a+b. block-2. . the value of expression is compared with case values.value-2. are statements contain zero or more statements. are constants or constant expressions and are known as case labels. 2. block-1. Execution of the statements of the statements in the loop.

b. If at the entry condition itself the test-condition is false then body of loop will be skipped. b. Syntax: Example: #include < stdio. then the body of loop is executed. While statement 2.controlled loop statement. while (i<1) { printf(“this is number %d\n”). The body of loop will be executed once and the condition is tested if the condition is true then body will be repeated or else exit from the loop. i++. The do is an exit. For statement 1) While statement: a. The test -condition is evaluated first and if the condition is true. The while is an entry.h> void main() { int i=1. Again the test-condition is tested and body of the loop will be repeated until the condition becomes false c. Do statement 3.Types: 1. } } 2) The do statement: a. Syntax: Example: .controlled loop statement.

i++. In that case the initial value should be greater than the final value.j--) 7. 5.---------------------------------do { printf(“well done!”). In normal situation initial value is lesser than the final value. then the control is transferred back to the For loop.) loop within a loop. 8. i--) (negative increment) for (i=0. The control variable will be incremented by using the increment and again tested using the test condition. When the body of the loop is executed. It allows negative increments. 6. then for statement can be used. Initialization of the control variable is done first.). it is entry controlled control loop. i++) (positive increment) for (i=10. 2. If the test condition is true then the block is executed otherwise the loop is terminated and the execution continues with the statement immediately follows. i<=j. (ie. ----------------------------3) For statement : If we know the exact number of times for repetition of block of statements. 3. } while(number<=10). For statement is not followed by semicolon(. Syntax: Execution of ‘for’ statement as follows: 1. It allows more than one variable initialization as well as more than one variable incrementation. Examples: for (i=1. 4. i>0. i<=10. Example : ------------------------------- . Nested loop is also possible. This will be repeated until the test condition becomes false.. The value of the control variable is tested using the test condition.j=8.

It can be used a part of If statement.I++) { if (a<b) break..Name any two ascii types of constants. Avoid using goto statements in for statements.What is meant by linking 22. Example: for(i=1. Break statement is used to exit from the loop.I<=10.What symbol terminates each C statement/ .What is the size of long int? 19.Must all the variables appearing within a C program be declared ? 21. To skip a portion of statements in the for loop continue statement can be used in conjunction with if statement and will goto the for statement. Suggested Questions Objective answers: 18.j++) { ----------------------------------} } ------------------9.When is the logical expression evaluated in a do.i++) { for(j=1.for (i=1.i++) { if (a<b) continue.i<=10. Example: ----------for(I=1. 20.j<=m.while statement? 23.i<=n. --------------------------} ------------11. --------------------------} ------------10.

city.what is initialization? Why it is important? 36. give reason.which of the following are invalid variable names and why? Maximum Last.b=25and c=-7 a>b&&a<c a<b &&a>c b>12&&c<0 ||c<0.which of the following arithmetic expressions are valid? If invalid. lowercase letters are significant. 33.Area= IIr2+22/7rh 43. 30.what is variable. in the following input statements scanf(“%c %f %d”. c language .m1+m2 45.a line in c program may have more than oneline of output.a printf() statement can generate only one line of output.Torque=2m1m2 44.2 41.5 99999 “12.342” 39.what are enumeration variables? How are they declared? 37.say true or false 28. 38.24.quan). 35.rollno Mn+me Row total 40. 31. 42.say true or false 27.if any.&price).0 46.every line in c programming should end with a semi colon.0001 5x1.every c program end with and END word.describe the purpose of the qualifiers const and volatile.What sre symbols used for logical operators AND & OR? 25.what are trigraph characters? How are they useful? 34.which of the following are invalid constant and why? 0.main() is where the program begins its execution. 47.write the c assignment statements to evaluate the following equations.syntax error will be detected by the compiler.determine the valueof each of the following logical expressions if a=10.state errors .what is the use of conditional operator? . scanf (“%s %d”. 32.4%2 21 %(int)3. 25/3%2 12.Give the conversion specifications used for printing octal & hexa decimal values.

Explain about looping statements with suitable examples 62. B.write a program to find largest among three given – dimensional array.. write the difference between while statement and do…while statement Suggested Questions: 49. 57.write a program to generate prime numbers. 54.Write a program in c to solve a quadratic equation to check all possibilities of their coefficients STUDY MATERIAL COURSE SEMESTER UNIT SUBJECT NAME LECTURER NAME NUMBER OF PAGES DATE OF ISSUE : : : : : II YEAR A.Differentiate while & do.Sc ECS : III III PROGRAMMING IN C : D.Display of string with different formats – String standard functions – Application of strings.write important features of for statement.write a program to check whether the given year is a leap year or not 53. predefined streams.write a program to generate fibanocci numbers 59. statement .. 56.while statement 51.write a program to find reverse of the given digit 55. 60.write a program to convert the given farenheit temperature to Celsius temperature.? 52. Pointers: Features.MYTHILI 56 Unit-III Arrays : Array initialization – definition – characteristics.write the syntax of if.dimensional array – Three or multi dimensional arrays.Two.write a program to calculate simple and compound interest Essay Answers 61. Strings and Standard functions:Declaration and initialization of string.write a program to do arithmetic operations for any two given numbers using switch case statement.Write a program to print the prime numbers between 1 to 100 64.Write a program to print the fibonacci series 63.48. Pointer declaration. Arithmetic Operations with pointers- .. 58.Explain if statement with an example 50.

valid c programming variable size . 3. 2. longint. Example: int a[10].no. Example: An array name salary can be used to represent a set of salaries of a group of employees. Types of functions. float height[20]. Functions returning more values. Functions as an argument. DECLARATION OF ARRAYS: Syntax: where type . 3. 2. TYPES : 1. Explanation: In the first declaration we can store atmost 10 elements . ARRAYS Definition : An array is a group of related data items that share a common name. char name[10].subscripted array. of elements 1. A particular value in an array is called an element and can be written as follows salary [10] represents the salary of the 10th person. One dimensional arrays / Single subscripted array Two dimensional array Multi dimensional array ONE DIMENSIONAL ARRAY: Definition : A list of related data items with one variable and only one subscript is called single. float .char variable_name . Call by value and Call by 1.double. Functions: Definition.Pointers and Array – Pointers and Two-dimensional array – Array of pointers – Pointers to pointers – Pointer and Strings –Void pointers. Declaration. The return statement. Functions with Arrays and pointers – Recursion – Preprocessor Directives.

-20 and the remaining elements are set to zero.63. In third we can store atmost 9 characters. 2. There is no convenient way to initialize only selected elements. TWO DIMENSIONAL ARRAYS: Definition : A list of related data items withone variable and subscripts representing the row value and column value is called two dimensional array.-20}. DRAW BACKS IN INITIALIZATION OF ARRAYS: 1. In the above the size is omitted. While declaring character array the last character must be a null character(‘\0’). While mentioning about the size we must include one extra space with maximum number of characters. Example: a.1. static int count[]= {1. In the above list of values are separated by comma. The compiler itself allocates enough space for all initialized elements.1}. static float total[5] = {0. In the above the first three elements are set to 0. The second declaration can hold 20 elements of real numbers. There is no shortcut method for initializing a large number of array elements like the one available in FORTRAN. This character is automatically included while assigning values to these variables. DECLARATION OF ARRAYS: Syntax: . 15. 2. b.of type integers. Suppose the value is not given then automatically it will be assigned as zero. INITIALIZATION OF ARRAYS: Syntax: We can initialize the array variable like ordinary variables when they are declared.5.

float .5.-20}.where type . In the first declaration we can store atmost 100 elements of integers. The second declaration can hold 40 elements of real and the remaining elements are set to zero. of elements Example: int a[10][10]. float height[20][2].63. This character is automatically included while assigning values to these variables.valid c programming variable size 1. -20 and in the second row the first element is 10.double. In the above list of values are separated by comma.{10.char variable_name . While mentioning about the size we must include on extra space with maximum number of characters. char name[10][10]. 15. While declaring character array the last character must be a null character(‘\0’).2}}. . MULTI DIMENSIONAL ARRAYS: Definition : A list of related data items with one variable and more than 2 two subscripts is called multi-dimensional array. 3. 3. DECLARATION OF ARRAYS: Syntax: . Explanation: 1. . Suppose the value is not given then automatically it will be assigned as zero. longint. 2. INITIALIZATION OF ARRAYS: Syntax: We can initialize the array variable like ordinary variables when they are declared. In third we can store almost 10 names of 9 characters. Example: a.5 . static float mat[2][3] = {{0. In the above the first row elements are set to 0.15.

} STRINGS AND CHARACTER ARRAYS: .i<=n-1. double . for(i=1.h> main() { int i. a[j]=t.i++) printf(“%d”.j++) { if (a[i]>a[j]) { t=a[i].3…n SAMPLE PROGRAM USING ARRAY:(ascending order) #include <stdio. /*INPUT THE NUMBER OF ELEMENTS*/ printf(“Enter the total no of elements \n”). a[10]. return(0).int .size of ith dimension where i = 1. /*ENTER THE VALUES TO BE SORTED*/ printf(“Enter elements \n”).i<=n. t. for(i=1.h> #include <string.i++) { for(j=i.valid c programming variable si -. n.2. /*BUBBLE SORT*/ for(i=1.j<=n. a[i]=a[j]. } } } /*PRINT THE RESULT*/ printf(“ sorted elements \n”).a[i]).&a[i]). float . char array_name -.&n). getch(). scanf(“%d”. longint .where type -.i<=n.i++) scanf(“%d”.

’.name). Reading a line of text: We can read the entire line of text using the function getchar().’y’. char name[30]. In the above example & is not required before the variable name.’.’\o’}. By using the above function it terminates the input process whenever . 5. Reading and writing strings. Drawback: 1.’e’. Comparing strings for equality. static char city[9]= “new york”. In character array the compiler automatically includes the null character at the end of the string. In the above 3 and 4 initializations are same. 2. 3. 4. Example: “Where there is will there is way” Operations performed on strings: 1. static char city[9]={‘n’.’k’.’o’.’r’. 4. char city[10]. Copying one string to another. Extracting a portion of string. Example: char name[15]. If the size is not mentioned then the compiler itself defines the size of the array variable depending upon number of elements in the initialization statement. Any group of characters enclosed between double quotes is a string constant. 2. 3. Combining strings together. READING STRINGS FROM THE TERMINAL: The scanf function can be used with the control string %s to read in a string of characters. DECLARATION AND INITIALIZATION OF STRING VARIABLES: Syntax: Example: 1.’w’.Definition: String is an array of characters. scanf(“% s”. We cannot read a line of text from the terminal.

Example: /**************************************/ /* program to read a line of text from terminal*/ /**************************************/ #include <stdio. the entire string is receives the newline character. When the number of characters to be printed is specified as zero. c++. The minus sign in the specification causes the string to be printed left. c=c-1. printf(“enter text . 4. EFFECT OF VARIOUS %S SPECIFICATION : 1. } WRITING STRINGS TO THE SCREEN: Printf statement with control string %s is used to display the string value. ARITHMETIC OPERATIONS ON CHARACTERS: C allows us to manipulate the characters in the same way as numbers. printf(“\n%s\n”. do { character=getchar(). 2. The integer value on the right side of the decimal point specifies the number of number of characters to be <enter> at end\n”). 3. Whenever a character constant or character variable is used it is automatically converted into integer value by the system.Total characters s”. When the field width is less than the length of the string .character. line[c]=’\0’.line). c=0. } while (character!=’\n’). nothing is printed.h> main() { char line[81]. Example: Printf(“%s”.name). (or) printf(“%Total columns. The integer . line[c] int c.justified.

printf(“%s”.i++) t_str[i]=f_str[i].t_Str).value depends on the local character set of the system.atoi(string).subtraction . Example: X=’a’.s_str[j]!=’/0’.x). PUTTING STRINGS TOGETHER: Just as we cannot assign one string another directly. k. The size of the array str3 should be large enough to hold the total characters. t_str=’ ‘. multiplication . Example: PROGRAM FOR CONCATENATION OF TWO STRINGS: #include <stdio. static char f_str[10]={“hello”}.h> #include <conio. j . char t_str[20]. we cannot join two strings together by the simple arithmetic addition like as follows: Str3=str1+str2. static char s_str[10]={“world”}. for(j=0. for(i=0. To convert integer to ascii as well as ASCII to integer is done by using library functions like itoa(integer). The output of the above statement will be 97. Printf(“%d\n”.f_str[i]!=’/0’. invalid The characters from str1 and str2 should be copied into the str3 one after another. . } Output: hello world STRING HANDLING FUNCTIONS: C library supports a large number of string-handling functions that can be used to carry out many of string manipulations like concatenation .h> #include <string. division etc. Similarly it is also possible to perform all the arithmetic operations like addition . Str2=str1+”good”.h> main( ) { int i .j++) t_str[i+j+1]=s_str[j]. t_str[i+j+1]=’ ‘.

comparison . copy . strncat( Appends source string to destination string upto specified ) length. Compares characters of two strings Compares two strings Compares characters of two strings upto specified length Compares characters of two strings upto specified length. Determines first occurrence of a given character in a string Determines last occurrence of a given character in a string Determines first occurrence of a given string in another string strcat( ) Appends source string to destination string. strspn( ) Finds upto what length two strings are identical. Functio ns srlen ( ) srcpy ( ) srncpy( ) srcmp () sricmp( ) srncmp( ) srnicmp () srlwr( ) srupr( ) srdup( ) strchr( ) strrchr( ) strstr ( ) Description Determines length of a string Copies a string from source to destination Copies character of a string to another string upto the specified length. Ignores case. . strrev( ) Reverses all characters of a string. strnset ( Sets specified numbers of characters of string with a given ) argument or symbol. strpbrk( Searches the first occurrence of the character in a given ) string and then it displays the string starting from that character. Converts uppercase characters of a string to lowercase Converts lower characters of a string to upper` Duplicates a string. STRCAT( ) FUNCTION: Syntax: Example: Part1=”computer ”. finding length of the given string etc. strset Sets all characters of string with a given argument or () symbol.

N = Strlen(part1). thus in the given example the output should be “computer science”.if not it will return the numerical difference between the mismatching characters in the strings. The above function compares the two given strings string1 and string2 and return value 0 if both are equal .string2 are character arrays.”science”).string2 are character arrays. Strcmp(part1. Thus the resultant value is stored in part1.”computer ”). Thus in the given example the output should be “science”.”science”). The counting ends at the first null character. In the given syntax string1. In the above example it return o as a value. In the given syntax string1 is character array. Thus the resultant value is stored in . STRLEN( ) FUNCTION: Syntax: Example: Part1=”computer”. When the function is executed string2 is copied to string1.Strcat(part1. In the given syntax string1. When the function is executed string2 is appended to string1 by removing null characters at the end of string1. STRCPY( ) FUNCTION: Syntax: Example: Strcpy(part1. When the function is executed it counts and returns number of characters in a string. STRCMP( ) FUNCTION: Syntax: Example: Part1=”computer ”. Thus in the given example the output should be 8. Thus the resultant value is stored in part1.

Main() { printline(). once a function is designed and blocked it is called as ‘black-box’ that takes some data from the main program and returns value.To reduce the complexity of program.To call the function wherever it is needed. The function is used in main as follows. 66.a<40. 67.To reduce the length of the program. Example: Printline() { int a. printf(“\n”).a++) printf(“=”).Easy to debug. } Need for functions: 65. test and maintain. printline(). printf(“Use of C functions”).N. 68. } This example defines a function called printline that prints a line of 40 characters. Syntax: Working of functions main() { . for(a=1. USER-DEFINED FUNCTIONS: DEFINITION: A function is a self-contained block of code that performs a particular task.

‘abc’ is a function name. Function name Here. ‘y’ and ‘z’ are actual arguments. } Suppose if the return type is integer then there is no need to mention about the return type in the function definition as well as in the proto type. Formal arguments The arguments of called function are formal arguments. ‘k’ and ‘j’ are formal arguments.i<=n1. } Actual argument The arguments of calling function are actual arguments In the above example.y.k. If the function returns non integer value then there is need for explicit specification about the return type. It takes the following form . return(f1). for(i =1. Function call Actual argument _______ _______ } abc(l. Argument list Variable names enclosed within parenthesis are called argument list. Function call A function can be called by its name. In the above example. ‘l’ . Example function fact (int n1) { int f1.z). The return statement is used to return a value to the calling function. terminated by a semicolon. ‘x’ .j) { Function definition Formal argument ________ ________ return()._______ _______ abc(x.i++) f1=f1*i.

Can be accessed by all the functions in the program. } function1( ) { int i. main( ) { int i. Global variables Global variables are defined outside the main( ) function.Local and Global variables There are 2 kinds of variables. Needs to be declared inside the function where it is to be used. Example: int m. Stored in separate locations . used. local variables: Global variables: Can be accessed only in the function where it has been declared. Variables are secure. ……. so Stored in one location. The variable defined is local to that function only. float sum. variable m is a global variable and can be accessed anywhere in the program where as variable i is a . …… …… } In the above example. so any accessing will change the value function accessing can change only in the function where it’s its value.. ……. Needs to be declared in the global declaration section outside all programs. function1( ). Can be used by many functions and so are not secure. Other functions can not access these variables. Multiple functions can use them. float balance.. Local variables The local variables are defined within the body of the function.

clrscr( ). } Output: Enter the value of x: 5 The cube of 5 is: 125 Types Of Functions: Depending on whether the argument is present or not and . default: printf(“The cube of %d is : %d”.7 The Return Statement The user defined functions uses a return statement to return the value to the calling function. printf(“ enter the value of x:”).&x).local variable and should be accessed only in the function in which it is declared. scanf(“%d”.h> main( ) { int pass(int). x. break. switch(y) { case 1: printf(“ The value returned is %d”. Eg. Exit from the called function to the calling function is done by the use of a return statement.y).y.h> #include<conio. y=pass(x). Write a program to use a return statement in different ways. else return(a*a*a). #include<stdio.y). if(x= =1|| x<0) return 0. } return NULL. } pass(a) { if(a = = 0) return. When the return statement is executed it always returns 1. int x. The variables balance and sum are local variables and can be accessed in the functions main and function1 respectively.

So this approach is not better. 2. So there is only a transfer of control between the calling and the called function. 4. Example: /* addition of two numbers*/ #include<stdio. Functions with no arguments and no return values. it does not receive any data from the calling function. the calling function does not receive any data from the called function. 1.a). The nature of data communication between the calling function and the called function is with arguments but no return values. but not a data transfer.b. No Arguments and no return values: When a function has no arguments. . may belong to one of the following categories. Functions with arguments and no return values. To make it efficiently we could make the calling function to read data from the terminal and pass it on to the called function. } With Arguments but no return values: In the previous category there is no data communication between the functions. 3. Functions with no arguments and return values. a=a+b. } /* function definition*/ add() { int a. Functions with arguments and return values. Similarly.whether a value is returned or not. return(0). when it does not return a value. printf(“%d”.h> main( ) { add ( ).

h> main( ) . Example: /* addition of two numbers*/ #include<stdio.a1). When a function call is made.Example: /* addition of two numbers*/ #include<stdio. To make it more effective. So it is like one-way communication.b=3. With Arguments and return values: In the previous category the calling function sends some data to the called function. } The arguments that we are using in the main function are called actual arguments. printf(“%d”.b). but the called function does not return anything to the calling function.h> main( ) { int a=2. both send and receive data in this category. } /* function definition*/ add(int a1. it has to be shown in the main function b1) { a1=a1+b1. If there is any change of values in called function. Changes inside the function will have no effect on variables used in the actual argument list. The arguments that we are using in the called function instead of the actual arguments are called as formal arguments. add (a. only a copy of the values of actual arguments is passed into the called function. return.

} With no arguments and return values: Eg.s. Program without passing any value through main( ) #include<stdio.h> main( ) { int sum( ).b. clrscr( ). } /* function definition*/ add(int a1. return 0. printf(“ Enter the values”). s=sum( ). } Output: Enter three values: 3 5 4 Sum = 13 Call by value and Reference There are 2 ways in which we can pass arguments to the function. Call by value 69. printf(“%d”. printf(“Sum =%d”.y. return(x+y+z).Values of actual arguments are passed to the formal . c=add (a. scanf(%d%d%d” b1) { a1=a1+b1.c).{ int a.&. return(a1). a. s).&x.c.&z).b). } sum( ) { int x. getch().

b=4. swap(a.Any change made in the formal argument will affect the actual arguments. b=3 In main a=3. printf(“a=%d. printf(“In main”).arguments and the operation is done on the formal arguments. getch(). b). printf(“In function swap”). b=%d”.h> main( ) { int a=3. 73. b=%d”. t=a. &b). 70. b=4 Call by Reference 72.Function operates on addresses rather than values. 74. a=b. b=t. a.h> main( ) { int a=3. int b) { int t. Example /* swapping of two numbers*/ #include<stdio. b=%d”. a. b). b).Any change made in the formal argument does not affect the actual arguments.Example /* swapping of two numbers*/ #include<stdio. printf(“a=%d. swap(&a. } /* function definition*/ . addresses are passed. printf(“In main”).Instead of passing value. getch().b=4. } /* function definition*/ swap(int a. 71. b) } OUTPUT In function swap a=4. a. printf(“a=%d.

*b=t.swap(int *a.y. t=*a. b) } OUTPUT In function swap a=4.h> main( ) { int x. *a=*b. printf(“a=%d. b=3 Function Returning More values: Eg:Write a program to return more than onevalue from a user-defined function. change(int *.h> #include<conio. &sub). . add). sub). &add. &x. clrscr( ). int * b. a.&y. change(&x. } change(int * a. printf(“ Enter values of X and Y:)”). b=%d”. b=3 In main a=4. add. &y). int *. int *c. sub. *d= *a-*b. printf(“Subtraction: %d”. return 0. scanf(“%d%d”. x. int *). int *d) { *c=*a+*b. int *b) { int t. #include<stdio. int *. printf(“Addition:%d”. printf(“In function swap”). } Output: Enter values of X and Y: 5 4 Addition:9 Subtraction: 1 Function as an argument: Eg: Write a program to pass a user-defined function as an argument to another function: main ( ) { int y=2.

int). small=a[0]. it is enough to list the name of the array. static float a[5]={1. 4.34 . } . printf(“%f”. } Output: x=8 Functions with Array and pointers a) Initialization of an array using a function:: Like the values of simple variables.n).5)). } double(m) { return(m*2). without any subscripts and the size of the array as arguments. } square(k) { return(k*k).0 . 1. Example: Lar(a.i<m. for(i=1. Array size of the array Name /* program to find smallest element among given set of elements*/ #include<stdio.0}. x).i++) if (a[i]<small) small=a[i]. float small.x= double(square(y)). 50. } /* function definition*/ float smallest (float a[]. int m) { int i. it is also possible to pass the values of an array to a function. To pass an array to a called function. return(small).h> main() { float smallest(float. printf(“x=%d”.3 .smallest(a.0 . 60.

} Output: num[1] = 12 num[2] = 13 num[3] = 14 num[4] = 15 num[5] = 16 num[6] = 17 num[7] = 18 c) Passing reverse array to a function: Eg: Void main( ) { int show(int *).14. num[]).u). m+1. } OutpUt: num[6] = 18 num[5] = 17 num[4] = 16 num[3] = 15 .k<7.17. for (k=0. m.15. m.17.k++) show(k. int). show(int. int num[ ] ={ 12. int num[ ] ={ 12.16. show(& num[6]).13. } show(int m.14. } show(int *n) { int m=6. clrscr( ). u .15. } return (NULL).-. int u) { printf(“num[%d] = %d”.18}.-.18}.b) Passing array elements to a function: Eg: Void main( ) { int k.16.13. clrscr( ).*u). while(m!= -1) { printf(“num[%d] = %d”.

} cpy( int * p.h<5.h++) printf(“%d %d”. int *m) { int j=0.5}.num[2] = 14 num[1] = 13 num[0] = 12 d) Copying an array: Void main( ) { int cpy(int *. p++. for (k=0. h. clrscr( ). } return (NULL). cpy(&a1[0]. &a2[0]). in tarry( ). int a1[ ] ={ 1. for (h=0. clrscr( ). } } arry( ) { . } Output: Source Target 1 1 2 2 3 3 4 4 5 5 e) Reading a private array: eg: void main( ) { int k. int *).a2[h]).3.k<5. arr( ). printf(:Source Target”). m++ j++.2.4.k++) { printf(“%d”. while(j!=5) { *m =*p. a1[h].

When n=2.h> main() { int n.2. int b[5]={1.static int k.The recursion can be used directly or indirectly. } Output: 12345 Output: 12345 Recursion: 75.4.3.Recursion is the process where a function is called repetitively by itself.When n=3. 1 is returned & control goes to step 1 where fact = 2*1=2 & control is returned to step 1 where fact = 3*2=6 & value is given to the calling function Indirect Recursion A function calls another function then the called function calls the calling function. } factorial(int n) { int fact. 76. return(fact).When n=1. Direct recursion A function calls itself till the condition is true.&n). Example 1: //program to find the factorial of a number #include<stdio.5}. scanf(“%d”. printf(“%d”. . fact=2*factorial(1) 3. fact=3*factorial(2) 2. } Steps: 1. Example. if(n==1) return 1. else fact=n*factorial(n-1). return(b[k++].factorial(n)).

main(). Syntax: Int variable name. } } STORAGE CLASSES: Purpose: Storage classes tell the compiler the information about location and visibility of variables. so the same name can be used in different functions. Longevity: Longevity refers to the period during which a variable retains its value. • A variable declared inside a function without any storage class specification is treated as auto by default. } add() { static int i=0. C has four storage classes • Automatic variables • External variables • Static variables • Register variables. Scope: Scope of a variable determines over what parts of the program a variable is active or actually available for use. • They are local to the function where they are declared and so are called local or internal variables.Void main() { add(). while (i<5) { i++. Automatic variables: • They are declared inside the function where they are used. . • They are created when a function is called and destroyed when the function is exited. Or Auto int variable name. • The value of an auto variable cannot be changed accidentally.

a). } This will cause the compiler to generate an error message since y has not been defined in the function main. printf(“%d\n”. • A global variable is visible only from the point where it is declared. . …… } int y. main() { y=5. function2(). Therefore these are generally used when values are to be shared between functions. • They are declared outside a function.Example: main() { int a=1000. f1() { y=y+1.a). } function1() { int a=100.a). printf(“%d\n”. } function2() { int a=10. • Once a variable is declared as global any function can change its value. To avoid this we use the storage class extern. • They can be accessed by any function within the program. } Output: 100 10 1000 EXTERNAL VARIABLES: • Variables that are both alive and active throughout the program are external or global variables. printf(“%d\n”. function1().

Example: int a. . The extern declaration does not allocate storage space for the variables. function2(). } Output: 1000 1000 1000 STATIC VARIABLES: • The value of static variables persist until the end of the program.main() { extern int y. } function1() { a=a*10. function1(). printf(“%d\n”.a).e) it is declared as a global variable in one file and specified as an extern in the other. printf(“%d\n”. } function2() { a=a*10.a). • Multiple files can share a variable provided it is declared as en external variable (i.a). main() { a=10. …… …… } • The keyword extern informs the compiler that thevariable y has been declared somewhere and asks to perform a lookup for the variable. printf(“%d\n”. …… …… } f1() { extern int y.

• Register access is much faster than memory access. • Frequently used variables can be placed in the register.They are similar to auto variables but are alive throughout the entire program. printf(“%d\n”. } } stat() { static int x=0.x). • Leads to faster execution of programs. • C automatically converts register variables into non register variables once the limit is reached. } Output: x=1 x=2 x=3 REGISTER VARIABLES: • Register variables tells the compiler to store the value of a variable in a register instead of the memory. i<=3. Syntax: . • A static external variable is available only within the file where it is declared. for( i = 0.• Can be of internal or external type depending on the place of declaration. • Internal static variables are those that are declared inside a function. They are used to retain values between function calls. i++) { stat(). • Most compilers allow only int and char datatype to be placed in the register. Example: /*Static variable example*/ main() { int i. x=x+1. • A static variable is initialized only once. • External static variables are those that are declared outside functions.

3. Pointers reduce the length and complexity of a program. REPRESENTATION OF A VARIABLE: . 2.VISIBILITY AND LIFETIME OF VARIABLES: Storage class None Place of Declaration Visibility Lifetime Entire Program(Glob al) Global. A pointer enables us to access a variable that is defined outside the function. Pointers are more efficient in handling the data tables. 5. 4. Before all functions Entire file + other files in a file where variable is declared as extern. The use of a pointer array to character strings results in saving of data storage space in memory. Extern Before all functions Entire file + other files in a file where variable is declared as extern and the file where it is originally declared as global. Advantages of using pointers: 1. They increase the execution speed. Static(exter Before all functions Only in that file nal) in a file None or Inside a function Only in that function auto Register Inside a function Only in that function Static(intern Inside a function al) Only in that function Global Until end of function Until end of function Global POINTERS: A pointer is a variable that contains an address which is a location of another variable in memory.

pt_name points to a variable of type data type. 1. pt_name needs a memory location. Thus it may have some address the above ‘quantity’ is a variable name with the content 100 stored in the location 5000. every variable must be declared for its type. 3. Example: int *p. Example: p = &quantity. In our scanf function we use this operator to indicate the address of a variable. Whenever a variable is declared the value will be stored in a memory location in the given name. The asterisk (*) tells that the variable pt_name is a pointer variable. Each byte has a unique address associated with it. they must be declared before we use them. Since pointer variables contain the address of a variable . Thus in the above example p is a pointer variable which holds the address of the variable quantity. Thus pointer variable is a variable which contains the address of another variable.The computer’s memory is a sequential collection of ‘storage cells’ called as a byte. The declaration of pointer variable takes the following form Syntax: The above tells the compiler three things about the variable pt_name. . DECLARING AND INITIALIZING POINTERS: In C . Thus to assign the address of a variable to the pointer variable we can use this operator. Using pointer variable p the memory representation will be as like as follows Accessing a variable using pointers: The address of a variable can be accessed by using the symbol ‘&’ which is called as ‘address of ‘ the variable. 2. If we use a pointer variable for indicating this content then the pointer variable itself contains the address 5000 as its value.

sum =sum+ *p.which points to integer data type. POINTER EXPRESSIONS: Like other variables. For example . This as called pointer initialization. p = &quantity. *p. pointer variables can be used in expressions. Thus in the above example the first statement declares the pointer variable p . n = *p. n. . quantity = 100. In the third statement the address is assigned to the pointer variable p. Statements Quantity p n 5000 5010 5020 int quantity. The type int refers to the data type of the variable being pointed to by p and not the type of the value of the pointer. Example: int quantity. *p. declares x as a pointer to a floating point variable. ACCESSING VALUE OF A VARIABLE THROUGH POINTERS: Once a pointer has been assigned the address of a variable . then the following statements are true. n. Similarly the statement float * x. In the second statement 100 is assigned to quantity.declares the variable p as a pointer variable that points to an integer data type. if p1 and p2 are properly declared and initialized pointers. it can be made to point to a variable using an assignment statement such as p = &quantity. we can access the content using the ‘indirection operator’ (*). y = *p1 * *p2. p = &quantity. p1++. In the fourth statement the content is assigned to the variable n. n = *p. Thus p now contains the address of the variable quantity. Once a pointer has been declared . quantity = 100.

3. provided p1 has been declared and initialized properly.2}. POINTERS AND ARRAYS: When an array is declared . In the third statement the address p1 is incremented by one. Suppose we declare the array x as follows: Static int x[5]= {1.represents Initial value and -represents value After increment Thus when a pointer is incremented its value is increased by the length of the datatype that it points to> This length is called the scale factor. POINTER INCREMENTS AND SCALE FACTOR: Pointers can be incremented using any of the two ways mentioned below.6. The base address is the location of the first element (index 0) of the array.4.then the above expression causes the pointer to move to 2002 location.the compiler allocates a base address and sufficient amount of storage to contain all the elements of the array in contiguous memory locations. In the second statement the content of p is added with sum.y = *p1/ *p2. The fourth statement divides the p1 by p2. There should be a blank space between / and the indirection operator * otherwise it is treated as a comment. In the above the first one is to perform multiplication of the content of p1 and p2 and assign it to y. Suppose the base address of x is 1000 and assuming each integer . If p1 is a integer pointer in the location 2000. p1 = p1+1. p1++. Datatype Memory locations 2000 2001 2002 2003 2004 2005 Int Char Float Where .

i<10. for(i=0.the location where x[0]is stored. *p. for(i=0. . Suppose if we want to access the next element then we can increment the address by p++ to move from one element to another. p++. sum=0. i.i++) scanf(“%d”. then we can make the pointer p to the array x by the following assignment: p=x.&x[i]).h> Main() { int x[10].i++) { sum = sum + *p. elements value address x[0] 1000 x[1] 1002 x[2] 1004 x[3] 1006 x[4] 1008 base address The name x is defined as a constant pointer pointing to the first element . the first element will be stored as follows. p=x.x[0] and therefore the value of x is 1000. printf(“Enter the elements\n”). The relationship between p and x is shown below: P= &x[0] (=1000) P+1=&x[1] (=1002) P+2=&x[2] (=1004) P+3=&x[3] (=1006) P+4=&x[4] (=1008) The formula for calculating the effective address of ith element if Example: /*Program to calculate the sum of numbers in an array using pointers*/ #include<stdio.i<10.requires two bytes. That is x = &x[0] = 1000 If we declare p as a pointer . That is equivalent to p=&x[0].

for(i=0.sum).i<5.} printf(“Sum = %d”.1 ) (2.h> main() { int a[5][3].0 ) (3.j. } Pointers to two dimensional array: 0 1 (1.2 ) pointer to the first row pointer to the ith row pointer to first element in the ith 2 . printf(“Enter the values of the 5*3 matrix\n”).j++) { pointer to jth element in the ith (3.i.j) Example: /*Program to find the transpose of a matrix*/ #include<stdio.i++) { for(j=0.0 ) p p+i *(p+i) row *(p+i)+j row *(*(p+i)+j) value stored in the cell(i.j<3.

} } printf(“Original Matrix\n”). } printf(“\n”). } printf(“Transpose of the original matrix\n”).j<3.i++) { for(j=0.i++) { printf(“%d\t”.j++) { printf(“%d\t”.i<5.scanf(“%d”. . for(j=0.i<5.j<3.&a[i][j]).j++) { for(i=0.a[i][j]). for(i=0. } printf(“\n”).*(*(a+i)+j)).

POINTERS AND FUNCTIONS: The address of a variable can be passed on to a function. (*p)[3] – denotes p as a pointer to an array of three elements. name=”delhi”.cptr).h> Main( ) { char*name. char *cptr =name. we can use a pointer to access the individual characters in a string. } POINTERS AND CHARACTER STRINGS: A string is an array of characters .*cptr. Thus *p[3] – denotes p as an array of three pointers. Example: #include<stdio. Like in one dimensional arrays. Pointers can also be used to handle tables of strings.”Bombay”.length). } Thus the above program finds the length of the given string. int length.} getch(). cptr++. terminated with null character. When we the address to a function the parameters should be declared as . } length=cptr-name. while (*cptr!=’\0’) { printf(“%c is stored at address %u”. printf(“length %d”. Example: Static char *name[3]={“Delhi”.”Chennai”} Declares name to be an array of three pointers to characters as shown below Name[0]-delhi Name[1]-Bombay Name[2]-Chennai *(name[I]+j) is used to access the jth character in the ith row .

So it is possible to declare a pointer to a function. the addresses are passed as actual parameters. • When a function is called.y=200. *b = t. *a = *b.h> Main() { int x=100. Pointers to functions: A function also has an address in the memory. printf(“After exchange : x = %d y = %d\n”.&y). call by reference provides a mechanism by which the function can change the stored values in the calling function. The function that can be called by reference van change the value of the variable used in the call. *b) { int t. Example: #include<stdio. } Output: Before exchange : x=100 y=200 After exchange : x=200 y=100 Thus. Syntax: .x.y). } exchange(int *a. printf(“Before exchange : x = %d y = %d\n”.x.The process of calling a function using pointers to pass the address of a variable is known as call by reference. exchange(&x.pointers of the appropriate datatype.y). t=*a. Note: • The function parameters are declared as pointers and are used in the function body.

} } int val(f.I).I) int (*f)().Example: /*Program to calculate 2*x*x*/ #include<stdio. for(I=1.I.v).I<=5.val(). printf(“%d”.I++) { v=val(exp. { return (2 * (*f)(I)).v.h> void Main() { int exp().I. } int exp(int I) .

an array of pointers contains a collection of addresses.i=10. Since a pointer variable contains the address of an another variable.h> main() { int *arr[3]. . arr[1]=&j.j=20. Example: /*Array of pointers to isolated variable*/ #include<stdio.k=30. arr[0]=&I.{ return(I*I).m. The addresses of array elements can be the addresses of isolated variables or the addresses of other array elements. we can have an array of pointers. } ARRAY OF POINTERS: Similar to an array of integers or an array of characters.

m++) printf(“%d\n”.*(arr[m])).m<3. I j k 4008 5000 5100 arr[0] arr[1] arr[2] . } Output: 10 20 30 The contents and arrangement of the variables and pointers in memory is as follows.arr[2]=&k. for(m=0.

p[0]=a.5.3}. .h> void main() { int *p[3].c[]={7. In general a n-dimensional array can be declared as follows Syntax: Example: /*Array of pointers to one dimensional arrays*/ #include<stdio. Datatype *array[expression1]. Thus a two dimensional array can be declared as a series of one dimensional arrays as follows. p[2]=c.I.b[]={4.7000 7002 7004 A multidimensional array can be expressed in terms of array of pointers.j. p[1]=b.9}.6}.2.8. int a[]={1.

for(I=0.I<3. The expression (p[I]+j) denotes the jth value at the ith row.I++) { for(j=0.j<3. . Thus p[0] has the address of the first array a.*(p[I]+j) represents the value at the jth column in the ith row.j++) { printf(“%d”.*(p[I]+j)). } } } In the example p is a pointer to 3 arrays. Thus (p[2]+1)represents the first element in the third array ‘c’.printf(“the values are…\n”). p[1] has the base address of the second array b and so on.

Program: #include<stdio. The macro definition can be terminated with semi-colon and it is optional. Ø In between these stages there also involves one stage i. The preprocessor then passes the source code to the compiler.It operates under the preprocessor directives or preprocessor command lines.Compilation 79.14 . Preprocessor directives are placed before the main() function.h> #define M 5 .Linking 80.C program is written in the editor. The #define Directive The syntax of #define directive is as follows: #define identifier <substitute text> OR #define identifier (argument 1…. Ø The preprocessor is a program that processes the source code before it passes through the compiler.14 This statement defines macro templates. One of the most important features of C language is to offer preprocessor directives.. • They are placed before the main() function. argument N) substitute text Example: # define PI 3. 78.14 is its macro expansion.Preprocessor Directives : Introduction of Preprocessor Directives: The steps for execution of any program: 77. Rules: • Preprocessor directives begin with #. The macro templates are generally declared in capital letters. Here PI is the Macro template and 3. Ø The preprocessor is a program that processes the source program before it is passed on to the compiler. • They do not require a semicolon at the end.e Preprocessor. 81. Ø The program typed in the editor is the source code to the preprocessor. The words followed by # are not keywords and the programmer can use these words for variable names.The executable code is generated. During preprocessing the preprocessor replaces every occurrence of PI with 3.

scanf(“%d”.&a).res. scanf(“%d %d %d “.c). } Output: Value = 25 Program: #include<stdio.h> #define CUBE(x) x*x*x void main() { int a. printf(”Result = %d\n”. #include<stdio.M*5).#define AND && #define EQUALS == void main() { int a=5. else if(b larger a and b larger c) printf(“%d is the larger number”. else if(a equals b and b equal c) printf(“\n Numbers are same).h> #include<conio.b). else if(c larger a and c larger b) printf(“%d is the larger number”.res). } Output: Enter three numbers: 5 4 8 . printf(“Enter three Numbers:”).c. clrscr().b.&b. res=CUBE(a).h> # define equal = = # define larger > void main () { int a. printf(“Enter value”).&a.a).&c). if (a larger b and a larger c) printf(“%d is the larger number “. } Example: Write a program to define macros for logical operators. printf(“Value = %d”.

for(k=1. It is placed before the argument.k<=5.” Token pasting and Stringizing operators Stringizing Operation: In this operation macro argument is converted to string. } Output: HELLO Explanation: In the above program after conversion the statement say(HELLO) is treated as printf(“HELLO”) . wait. In the above program #undef directive undefines the same macro. #include<stdio. The sign # carries the operation.h> #include<conio. # undef wait getche().k).h> #define say(m) printf(#m) void main() { clrscr(). say(“HELLO”). It is not essential to enclose the text in quotation marks in the stringizing operator. Example: Write a program to carry out stringizing operation. #include<stdio. using the statement #undef identifer Example: Write a program to undefined a macro. Example: .k++) printf(“%d \t “.h> #define wait getche() void main() { int k.8 is the larger number Undefining a macro: A defined macro can be undefined. clrscr(). } Explanation: In the above program wait is defined in place of getche() . Hence the compiler flags an error message as “undefined symbol ‘wait’ in function main.h> #include<conio.

} Output: Function called Contents of udf.h> # define MAX(x. The macros and functions of loaded file can be called in the current program.c). . 1) The filename is included in the double quotation marks which indicates that the search for the file is made in the current directory and in the standard directories .Write a program to find the larger of the two numbers using macro with arguments. MAX(x. clrscr().c file int display(). #include<stdio.c.h> # include “udf.y).h> #include<conio. printf(“\n Larger of two numbers = %d”. Example: Write a program to call the function defined in “udf.h> #include<conio.c” void main() { clrscr(). The # include Directive The # include directive loads specified file in the current program. else c=y. The included file is also compiled with current program. The syntax is # include “file name”or #include <filename> where # is a symbol used with directives. display(). When a macro is called.The expression contains if statement that determines the largest number and assigns it to variable c.y) if (x>y) c=x.y=8. } Output: Larger of two numbers = 8 Explanation: In the above program macro MAX() is defined with two arguments x and y. void main() { int x=5. its corresponding expression is executed and result is displayed .c” file #include<stdio.

} #else { statement3.b.It is a userdefined function file .c” is included . Example: Write a program with conditional compilation as to whether the identifier is defined or not. If the identifier is defined then #if block is compiled and executed. statement2.#else 84. } Explanation: In the first program the “udf. return0. statement4. Conditional Compilation The most frequently used conditional directives are: 82. } #endif The #ifdef preprocessor tests whether the identifier has defined substitute text or not. The complete programs along with the included one are executed. Error messages will not be displayed .It is compiled before the main program is compiled. Syntax of #ifdef #ifdef<identifier> { statement1. if identifier is not defined then #else block is compiled and executed. . The compiler compiles selected portion of the source codes based on the conditions. The output of the program “Function called” is displayed.#endif etc.c.h> #include<conio. The compiler ignores #else block even if errors are intentionally made.h> #define E = void main() { int a.#if 83.display() { printf(“\n Function called”). #include<stdio.d. These directives allow programmer to include the portions of the codes based on the conditions.

Example: Write a program to check conditional compilation directives using #ifndef . b E 3. The #ifndef preprocessor tests whether the identifier has defined substitute text or not.b). } #else { c=2. } #endif The #ifndef works exactly opposite to that of #ifdef. #ifdef E { a E2.clrscr(). } Output: A=2 &B=3 Explanation: The compiler search for the identifier E . statement 4. If it is found then execution of #if block takes place otherwise #else block. Error messages will not be displayed. The #ifndef Directive The syntax of #ifndef directive is given below #ifndef <identifier> { statement 1. statement 2. } #endif getche(). The #endif statement indicates the end of #if-#endif block. The compiler searches for the identifier E. printf(“C=%d & D=%d”.c. If identifier is not defined then #if block is compiled and executed. d=3.d). printf(“A=%d &B=%d”.a. . If the identifier is defined then #else block is compiled and executed and the compiler ignores #If block even if errors are intentionally made. } #else { statement 3.

#else printf(“\n Macro is defined”). If it is defined the #else block is executed.h> #define B 1 void main() { clrscr().h> #include<conio. #ifndef T printf(“\n Macro is defined . In the absence of identifier an error is generated and the #error directive displays the error message. The syntax is # if !defined (identifier) # error <error message> # endif Example: Write a program to display user-defined error message using #error directive.#include<stdio. In case the identifier is undefined the #else block is executed and output is “Macro is not defined”. On execution of the block the output of the program is “Macro is defined”. #include<stdio. #endif } Output Macro is defined. Explanation: In the above program #ifndef checks for the identifier T. #endif } Explanation: In the above program identifier ‘B’ is defined.h> #include<conio.h> #define T 8 void main() { clrscr(). #if !defined(A) #error MACRO A IS NOT DEFINED #else printf(“Macro found”).”). The #error directive The # error is used to display user defined message during compilation of the program. The error message is user defined and displayed in the message box at the bottom of the .

editor. The # defined directrive will work opposite to the #!defined directive. The syntax is # if defined { } #else # error <error message> # endif The #line directive The syntax is #line <constant> [<identifier>] This causes the compiler to imagine the line number of the next source line is given by <constant> and <identifier> gives the current input file. If <identifier > is absent , then the cuurent file name remains unchanged. Example : # line 15 add.c The INLINE directive Reports the compiler that the source code has in line ‘asm’ statements. The source code will contain the assembly code. The #pragma SAVEREGS It guarantees that a huge function will not modify the value of any of the registers when it is entered. Place this directive immediately preceding the function definition. The #pragma DIRECTIVE The ANSI-C and TURBO-C provide pragma directives > these # pragma directives are defined with #(hash) and these are the preprocessor directives. It sets/resets certain warning and errors during compilation of C program. Syntax: # pragma warn +xxx # pragma warn –xxx ANSI Violations and #pragma # pragma name Hexadecimal or octal constant too large Redefinition not identical Both return and return of a value used Warning On +big +dup +ret Warning off -big -dup -ret

Not part of +str structure Undefined +stu structure Suspicious pointer +sus conversion Void functions +voi cannot return a value Zero length +zst structure Common errors and #pragma #pragma name

-str -stu -sus -voi -zst Warning On Warning off -aus -def -eff -par -pia -rch -rvl -amb Warning Off -amp -nod -pro -stu -use

Assigned a value but never +aus used Possible use before definition +def Code has no effect +eff Parameter never used +par Possibly incorrect assignment +pia Unreachable code +rch Function should return a +rvl value Ambiguous operators need +amb parenthesis Less Common Errors and #pragma #pragma name Warning On Superfluous & +amp with function or array No declaration +nod for function Call to function +pro with no prototype Structure passed +stu by value Declared but +use never used Portability Warnings #Pragma name Nonportable pointer assignment Constant is long and #pragma Warning On +apt +cln

Warning Off -apt -cln

Non-portable pointer comparison Constant out of range in comparison Non-portable pointer conversion Conversion can lose significant digits Mixing pointers to signed and unsigned char

+cpt +rng +rpt +sig +ucp

-cpt -rng -rpt -sig -ucp

Example: Write a program to set off certain errors shown by the program using #pragma directive #include<stdio.h> #include<conio.h> #pragma warn-aus #pragma warn-def #pragma warn-rvl #pragma warn-use main () { int x=2,y,z; printf (“\n y=%d”,y); } Explanation: The above program contains following warnings 85.Possible use of ‘y’ before definition in function. 86.‘Z’ is declared but never used in function main. 87.‘x’ is assigned a value which is never used in function. 88.Function should return a value in function main. The display of these errors can be made on/off by using the pragma options. Standard i/o predefined Streams in Stdio.h The predefined streams automatically opens when the program is started. Standard i/o predefined macros in stdio.h Macros Function

Definition in stdio.h

Predefined macros in ctype. for(i=0. for(i=0. printf(“text inputted”).i++) putc(ch[i].i<11. The first macro expansion &streams[0] reads string thru the keyboard and the second &streams[1] displays it.h> void main() { char ch[12]. printf(“input a text:”).i<11. } Output: Input a text: Programming Text input: Programming Explanation: In the above program instead of using macros their corresponding macro expansion is used.&_streams[1]). int i. clrscr().i++) ch[i]=getc(&-streams[0]).h Macro Returns true value if isalpha(d) isupper(d) islower(d) isdigit(d) isalnum(d) isxdigit(d) isspace(d) d d d d d d d is is is is is is is a a a a a a a letter capital letter small letter digit letter or digit hexa decimal digit space . #include<stdio.Stdin Stdout Stderr Stdaux Stdprn Standard input device #define (&streams[0]) Standard output #define device (&streams[1]) Standard error output #define device (&streams[2]) Standard auxiliary #define device (&streams[3]) Standard printer #define (&streams[4]) stdin stdout stderr stdaux stdprn Example: Write a program to enter text and display it using macro expansions.h> #include<conio.

This is called dynamic memory management. Realloc – modifies the size of the previously allocated array.ispunct(d) Isprint(d) isgraph(d) iscntrl(d) isascii(d) d d d d d is is is is is a punctuation a printable character a printable but not a space a control character an ascii code DYNAMIC MEMORY ALLOCATION: C requires the number of elements to be specified at the compile time. initializes them to zero and then returns a pointer to the memory. Free – frees previously allocated memory. Calloc – allocates space for an array.C uses four library functions to support dynamic memory allocation. They are • • • • Malloc – allocates requested size of bytes and returns a pointer to the first byte of the allocated space.e) space may be wasted or more space will be required . To avoid such problems C allows the user to specify the size of the array at run time. Thus the process of allocating memory at run time is known as dynamic memory allocation. Storage of a C program Stack Heap . Sometimes our initial judgement of the size of the arrays may be wrong (i.

This allocates a block of the specified size and returns a void pointer.Permanent storage area The global variables and the instructions are stored in the permanent storage area. In that case the memory allocation processes returns a NULL pointer to denote a failure to allocate the requested memory space. Therefore memory overflows can occur. This statement allocates a memory space equivalent to 100 times the . Malloc(): A block of mamory can be allocated using malloc() function. The free region is called the heap and is used for dynamic memory allocation. Local variables are stored in the stack. Syntax: Example: X=(int *)malloc(100 * sizeof(int)). The heap keeps changing when the program is executed when the variables are created and destroyed.

. }. Calloc(): Calloc() allocates multiple blocks of storage each of the same size and initializes them to 0.. If the function cannot allocate memory it returns a NULL pointer. Syntax: Example: ……. struct student { char name[25]. float age.. typedef struct student record.size of an int and returns the address of the first byte to the pointer x. ……. long int id. record *st_ptr.

2. Realloc(): There are 2 cases when we require to realter the memory already allocated 1.. In both the cases the memory size can be changed with the use of . …….int class=30. Free(): With dynamic allocation.sizeof(record)). st_ptr=(record*)calloc(class. When the previously allocated memory is not sufficient and the user requires additional space. Syntax: Example: Free(p). the user has to release the memory when it is not used. ……. This is important when the storage space is limited. The function Free() releases the memory. When the memory allocated is larger and the user wishes to reduce it..

cols allocates space for c . p[0]=(int*)malloc(c*sizeof(int)). p[1]=(int*)malloc(c*sizeof(int)).realloc(). printf(“Enter the no of cols\n”. Syntax: This function allocates a new memory space of size new-size to the pointer variable ptr and returns a pointer to the first byte of the new memory block if the memory allocation operation is successful.c. If the function fails in allocating the required space. The newsize may be smaller or larger than the original size.&c). Program: /*Program to access a 2 dimensional array using malloc()*/ void main() { int *p[3]. I. The realloc() function does not modify the original contents. then it returns a NULL pointer and the origunal block is lost. j.

j<c. for(I=0.I<3. } } } Suggested Questions Section A 89. } } printf(“The elements are….I++) { for(j=0.j<c.How many values a function can return? 90. .p[2]=(int*)malloc(c*sizeof(int)).j++) { printf(“%d”.j++) { scanf(“%d”.\n”).I++) { for(j=0. for(I=0.*(p[I]+j)).If white space characters are present within a control string ..I<3.(p[I]+j)).

112. • Static int number[ ]={0.if any. 101.Write the disadvantages of using goto statement.Explain and give example for predefined functions.What is a null statement? Explain its usefulness.Write the purpose of putchar function. • A switch expression can be of any type • A program stops its execution when a break statement is encountered.Write the common operations performed on character strings.13] • Char name[ROW].Declaration int a[10][10] creates how many elements. 95.Which function is used to convert the given integer value to string? 114.Write the syntax of goto statement.[COLUMN].0.’rr’. 106. in each of the following array declaration statements.How they are treated? 91.Define array. • Float values [10. 115.’r’. 99.Write the purpose of break and continue statement.Can the names of formal parameters coincide with actual parameters? 92. 109. 97.Say true or false: • when if statements are nested. 107. 110.Write any four string handling functions.} • Static char word[ ]={‘a’. 111.0.else statements. 104. 116.What is recursive function? 117.Explain the need for array variables.How the end of the string is recognized? 102.if any .Write the purpose of getchar function. 98.Can multiple return statements be included in a function? 93.. • One if can have more than one else clause.What happens when actual arguments are less than formal .in each of the following initialization statements.a switch statement differ from an if statement? 100.Describe the limitations of using getchar and scanf functions for reading strings.In what way .0. 113. 108.’y’}. the last else gets associated with the nearest if without an else. • A switch statement can always be replaced by a series of if. 96.Define string.What is the value returned by a strcmp() function? 105. 94.Write the advantages of using user defined functions.Identify errors .Write the function to convert the given string to integer . 103.Identify errors.

141. 137. 139.Write a program to search an element using linear search.Write short notes on different types of arguments 125.arguments in a function? 118.Distinguish between local and global variables 136.Write a program to find if a string is a palindrome or not.Say true or false • Function should be arranged in the order in which they are called.Differentiate local and global variables 124.Write a program to arrange the given set numbers in descending order.Write short notes on conditional operatorWrite short notes on multidimensional arrays 129.Explain string handling functions in detail with examples. • We can pass any number of arguments to a function. 145.Distinguish between formal and actual arguments.Write a program to arrange the given set of element using ascending order.Write a recursive program to generate fibonacci nubers 142. • A function in c should have atleast one argument.Write a recursive program to calculate the factorial of a given number. 133. 121. 138. 126.Write shorts notes on auto storage class 143.What happens when data type of one of the actual arguments does not match with the type of the function.Write short notes on functions 123.Explain about switch statement 135.Distinguish between automatic and static variables. 127.Write a program to add two given matrices of order m x n 134.Write a program to calculate npr using user defined function. Section –C . 119.Write a program which will read a text and count all occurrences of a particular word.Explain the usage of break & continue statement 128.Explain about register & extern variables 144.What are the different storage classes? Section –B 122.What happens when same variable is used in two different functions? 120.Is the main user defined function? If yes means how it differs from the other user defined functions? 140. 130. 132.Distinguish between global and extern variables.Write a program to sort the given set elements using selection sort 131.

6. Explain arrays with relevant examples. 150. How will you multiply 2 matrices.Write a program to sort a set of numbers and to print minimum & maximum of the set 149.Explain about user defined functions 148. Explain strings with relevant examples.Sc ECS : III IV PROGRAMMING IN C : D. Explain the various storage classes 5. 154. 157. 4. Explain functions with suitable example and write a program for NCR using Functions 2. 153. 3.Explain multidimentional arrays.MYTHILI 18 . 155.Explain recursion with an example 147. Write a program to count the number of palindromes in a given text.Write a program to multiply 2 matrices.Explain any 4 string functions with examples 152.Write a program to find the transpose of a matrix Section D 1. 156.Discuss on different storage classes 8.Write a program to sort a list of names in alphabetical order. Write a program to sort out a list of n names in bith ascending and descending order. Write notes on two dimensional arrays.Write notes on two dimensional arrays with examples.146.Write a program to find sum of positive & negative real numbers seperately from a given set of real numbers using continue and while statement 151.Write notes on one dimensional array with relevant example. STUDY MATERIAL COURSE SEMESTER UNIT SUBJECT NAME LECTURER NAME NUMBER OF PAGES DATE OF ISSUE Unit-IV : : : : : II YEAR A. Write a program to print the set of names in alphabetical order 9. B.

Structures enable the user to group together a collection of different data items of different data types using a single name. Bit fields. Advantages: 1. char stud_rollno[10].Structure and Union: Features of structure. STRUCTURES AND UNIONS: Structure is a constructed data type for packing data of different types. Structures help to organize complex data in a more meaningful way. Array of structure. Union. Structure within structure. float stud_mark2. STRUCTURE DEFINITION: A structure definition creates a format that may be used to declare structure variables. float stud_mark1. It is a convenient tool for handling a group of logically related data items. 2. rollno. }. Example: A structure can be used to represent a student’s details such as student_name. marks etc as follows Struct student { char stud_name[20]. Declaration and initialization of structure. Pointer to structure. General format for structure definition is as follows: Example: . float stud_mark3.

float price. In the structure definition you should follow the rules stated below 1. float price. 1.b3. If you give the tag-name then later in the program you can declare the variables using the given tag-name otherwise it is not possible. char author[15].Struct book_bank name of the structure or structure tag { char title[20]. int pages.b2. There are 2 ways in which we can declare a structure. While defining the structure memory is not allocated for its members. }. pages and price are members of the structure. char author[15]. Only during the declaration the memory is allocated for the members. each member is declared independently for its name and type in a separate statement inside the template. author. struct book_bank b1. The template is terminated with semicolon. structure variables In the above example book_bank is a tag-name which is optional one. . Thus the structure definition creates a template to represent a group of logically related information. 2. The title.While the entire declaration is considered as a statement. structure elements or members int pages. 3.The user can combine the template declaration and the variable declaration in a single statement as follows Struct book_bank { char title[20]. The tag name such as book_bank can be used to declare structure variables of its type later in the program.

For example the word title.tot. GIVING VALUES TO MEMBERS: We can assign values to members of a structure. which is also called as “dot operator” or “period operator”.title).h> struct student { char stud_name[25].book3. The link between a structure member and a structure variable is established using the member operator ‘. int pages. The same dot operator can be used to assign values to the structure members through the keyboard as follows Scanf(“%s”. . scanf(“%s”.price=150. void main() { printf(“Enter student details\n”). has no meaning when it appears alone. }book1.title=”c programming”. printf(“\nStudent Name : “). printf(“\nMark1 : “). 2.stud_name).The use of tag name is optional as follows Struct { char title[20]. Example: /*Program to illustrate the dot operator*/ #include<stdio.mark2.student1. float price. char stud_rollno[10].mark3.}book1. They should be linked to the structure variables in order to make them meaningful members. char author[15].book3.book2. scanf(“%s”.stud_rollno). The same structure member when it appears with the structure variable book1 as book1’s title has a meaning. printf(“\nRoll no : “).’. b2. }student1.student1.00. The structure members themselves are not variables.book1. Thus we can assign a value to the member using dot operator like as follows b1.book2. float mark1.

static struct st_record stu1={30.mark3.student1.stud_name). float weight. student1.56}.mark1). printf(“Student name : %s\n”.height. } Thus in the above the value 100 to student.\n”).73}. printf(“Marks : %f %f %f\n”. a structure variable can be initialized.tot = student1.mark3).student1.student1. …………… …………… } Another variation in initializing structure variable outside the function .tot). printf(“Roll no : %s\n”.stud_rollno).&student. printf(“The student details are as follows….&student. printf(“\nMark3 : “). Example: main( ) static struct { int weight. } STRUCTURE INITIALIZATION: Like any other type.mark3). scanf(“%f”.70.mark2 + student1. There is a one. static struct st_record stu2={45. }.mark2). …………………….student1. However.150..mark1.&student. printf(“\nMark2 : “).scanf(“%f”.weight and 150.student1. }student={100..45 to student. float height. printf(“Total : %f\n”. …………………….mark2.student1. A variation in initializing a structure is as follows: Main( ) { struct st_record { int weight.45}.mark1 + student1. a structure must be declared as static if it is to be initialized inside a function. scanf(“%f”.to-one correspondence between the members and their initializing values.65.

} COMPARISON OF STRUCTURES: Two variables of same structure type can be compared in the same way as ordinary variables.”00CS0001”. float mark1. //assigns structure s1’s contents to structure s2 if(s2 = = s1) //compares structure s2 and s1 printf(“Both the persons are the same\n”). main() { static struct stu student2 = {23. }stu1={56.s3={“bbb”.170.50}.mark1) //compares structure elements printf(“Student 1 and 2’s marks are the same\n”).30}. static struct student s2.mark2. If book1 and book2 are of same type then it is possible to compare two variables as book1== book2.”00CS002”.. ……………….tot. } void main() { static struct student s1={“aaa”. similarly we can assign book2 to book1 as book1=book2.90. if(s2 = = s3) printf(“Both the persons are the same”). .50. s2=s1.20.mark1 = = s3. float height.etc.50.5}. char stud_rollno[10].56}. Example: /*Program to illustrate comparison and copying of structure variables*/ struct student { char stud_name[25]. if( as follows: struct stu { int weight. else printf(“Both he persons are different”). ……………….150. else printf(“Marks are different\n”).mark3.

s[I].mark1). } printf(“The student details are as follows….stud_rollno).i). }. scanf(“%s”.&s[I].mark2. printf(“\nStudent Name : “).s[I].mark3).s[I].tot = s[I]. For example if we want to analyse the marks obtained by a class of students then we can use array of structures. int I.s[I].I<3. Also .mark3.mark2 + s[I].tot).I<3.mark3).\n”).stud_rollno).tot.s[I]. float mark1. printf(“\nMark3 : “).mark2.stud_name).} ARRAYS OF STRUCTURES: We use structures to describe the format of a number of related variables.I++) { printf(“Enter student %d details\n”. printf(“Marks : %f %f %f\n”.&s[I].h> struct student { char stud_name[25].mark1 + s[I]. printf(“Total : %f\n”.s[I]. s[I]. } } The above example declares a structure with 6 members. printf(“\nMark2 : “). for(I=0. Example: /*Program to illustrate arrays of structures*/ #include<stdio.mark1. printf(“Roll no : %s\n”. void main() { static struct student s[3].stud_name). for(I=0.s[I].I++) { printf(“Student name : %s\n”.&s[I].mark3. scanf(“%f”. printf(“\nMark1 : “). scanf(“%s”. char stud_rollno[10].s[I]. scanf(“%f”. scanf(“%f”.mark2). printf(“\nRoll no : “).

and an array of 3 marks. }. Thus in the above example student contains 3 elements stud_name.we have declared s to be an array consisting of 3 members of type struct student. stud_rollno.j. Thus it refers to the mark obtained in the first subject by the second student. In the previous example we have declared three variables mark1.stud_name S[1]. Thus the declaration will be as like as follows.I++) { . Example: /*Arrays within structures*/ #include<stdio. float marks[3].mark3. for(I=0. int I.h> struct student { char stud_name[25]. struct student { char stud_name[25].I<3. char stud_rollno[10].stud_rollno etc. Each individual element is accessed using the dot operator.marks[1]. void main() { static struct student s[3]. float marks[3]. ARRAYS WITHIN STRUCTURES: C permits the use of arrays as structure members.mark2.tot. }s[3]. char stud_rollno[10]. We can eliminate this by using an array to hold the 3 marks. Thus the details of the first student can be represented as follows S[1]. The marks can be accessed as stu[2].

for(I=0.tot).stud_name). rollno.tot = s[I]. scanf(“%s”. scanf(“%s”.s[I].s[I]. scanf(“%f”.printf(“Enter student %d details\n”. for(j=0.j<3. printf(“\nRoll no : “). s[I]. struct marks { .I<3. s[I]. printf(“Roll no : %s\n”.stud_rollno).stud_name). float mark1. char stud_rollno[10].j<3.tot=0.i).and the maks of the student. The above structure defines student name.j). float tot.marks[j].mark3.s[I].I++) { printf(“Student name : %s\n”. Struct student { char stud_name[25]. We can group the marks into one sub structure as follows: Struct student { char stud_name[25].\n”).&s[I]. }. Nesting of structures is permitted in c.s[I]. } } printf(“The student details are as follows….j++) { printf(“\nMark%d : “.s[I]. } printf(“Total : %f\n”.marks[j]). } } STRUCTURES WITHIN STRUCTURES: Structures within the structure means nesting of structures.mark2.j++) { printf(“Mark%d : %f \n”. for(j=0.s[I].j. char stud_rollno[10]. printf(“\nStudent Name : “).marks[j]).stud_rollno). Let us consider the following structure definition to store the information about the student.

&s[I].&s[I]. struct marks { float mark1. s[I]. float mark2.mark1. scanf(“%s”. }m. scanf(“%f”. float tot.h> Struct student { char stud_name[25]. s[I]. }m. }s[3]. printf(“\nRoll no : “).m. scanf(“%s”.m. char stud_rollno[10]. scanf(“%f”. float mark2. } printf(“The student details are as follows….m. float tot.stud_name).mark3).I<3.i). }.j.I<3.m.tot=0. void main() { static struct student s[3].mark1+s[I].I++) { .stud_rollno).mark2+s[I]. for(I=0. Example: /*Structures within structures*/ #include<stdio.mark2).tot = s[I]. float mark3.&s[I]. printf(“\nMark2 : “).m. float mark3.m. scanf(“%f”.I++) { printf(“Enter student %d details\n”.\n”).s[I]. printf(“\nStudent Name : “). printf(“\nMark3 : “).mark3.s[I].mark1). for(I=0. The individual marks of the second student are referred as s[2].float mark1. printf(“\nMark1 : “).m. int I.

Pointers are used to pass the structure as an argument to a function.s[I]. Disadvantages: 1. struct marks { float mark1.s[I]. 1. This is the most simplest method and is efficient when the size of the structure is small.m.A copy of the entire structure is passed. printf(“Mark1 : %f \n”. } } STRUCTURES AND FUNCTIONS: C supports passing structure values as arguments to a function.h> Struct student { char stud_name[25].m.mark3). There are three methods by which the values of the structure are passed to a function.m.tot).s[I].mark1).stud_rollno). float mark3.mark2).printf(“Student name : %s\n”. printf(“Mark3 : %f\n”.s[I]. printf(“Total : %f\n”. printf(“Roll no : %s\n”.stud_name). 2. 1. printf(“Mark2 : %f\n”. Example: /*passing structure members to a function*/ #include<stdio.The method becomes unmanageable when the structure size is large. float mark2.Passing each member of the structure: In this method each member of the structure is passed as actual arguments to the function. .s[I].s[I]. char stud_rollno[10].Each member of the structure is passed as an actual argument. 3. This method treats the structure members as ordinary variables.

50}} for(I=0.mark2. . So the formal arguments in the function should be declared as a structure type variable.s[I]. printf(“Mark2 : %f\n”. {“bbb”.float).mark1.s[I].I<3.m. for(I=0.}m.Passing a copy of the entire structure to the function: This method passes the entire structure as an argument to the function.10.m.tot).mark3). void main() { float total(float.I++) { s[I]. printf(“Mark1 : %f \n”.50.60}.30. static struct student s[3]={{“aaa”. } } float total(float a.20.s[I].I++) { printf(“Student name : %s\n”.tot = total(s[I].m.m.mark1).float.m.70.I<3.s[I].c) { return(a+b+c). printf(“Mark3 : %f\n”.mark2). float tot.”00CS003”.s[I].stud_name).s[I].40}.”00CS001”. printf(“Roll no : %s\n”. } printf(“The student details are as follows….b.”00CS002”. {“ccc”.m.stud_rollno). } 2.s[I]. }.s[I]. printf(“Total : %f\n”.40.\n”).mark3).

tot).”00CS003”.mark3.mark3).s1[I].30.mark2).mark2.\n”). struct marks { float mark1. void main() (struct student is the return type) { struct student total(struct student). Example: /*passing entire structure to a function*/ #include<stdio. float tot.”00CS001”.s1[I]. printf(“Mark3 : %f\n”.Disadvantage: 1. for(I=0.70. }.I++) { printf(“Student name : %s\n”. static struct student s[3]={{“aaa”. }m.I<3.m.m.mark1). for(I=0.s1[I]. {“bbb”.This method works on the copy of the structure.40.stud_name). char stud_rollno[10].10. printf(“Mark2 : %f\n”.stud_rollno).20.”00CS002”.s1[I]. Therefore it is necessary to return the structure.40}.I<3.s1[I].m. So any changes made to the original structure is not reflected.60}. printf(“Total : %f\n”.I++) { s1[I] = total(s[I]). .s1[I]. passing the structure as a parameter } printf(“The student details are as follows….50}} static struct student s1[3]. printf(“Mark1 : %f \n”. {“ccc”. printf(“Roll no : %s\n”.50.h> Struct student { char stud_name[25].

(->) • Member operator. The members of the structure can be accessed through 2 ways.m.mark2 + a.m. Advantages: 1.Using pointers to pass a structure as an argument: This method uses the concept of pointers to pass the structure as an argument to a function.} } struct student total(struct student a) { a.If is more efficient because any changes is reflected in the original structure. } 3. • Arrow operator. The function can access indirectly the entire structure and can work on it.m.(.mark1 + a. return(a).tot = a.(ie) the address location of the pointer is passes to the function.) Example: /*use of pointers to pass a structure as an argument to a function*/ .mark3.

then it must be declared as struct with an appropriate tag name. printf(“Student name : %s\n”.#include<stdio.tot).(*ptr). void main() { void total(struct student *p). printf(“Mark1 : %f \n”. float mark3. float tot. static struct student s={“aaa”. } Rules: • The called function must be declared for its type. printf(“Total : %f\n”.50. struct marks { float mark1. For example if the function is returning a copy of the entire structure. appropriate to the data type it must return.stud_rollno).h> Struct student { char stud_name[25].*ptr.ptr->m->mark1). printf(“The student details are as follows…. The structure variable used as the actual argument and the formal • . printf(“Mark3 : %f\n”.\n”). char stud_rollno[10].ptr->m->mark2). printf(“Roll no : %s\n”.”00CS001”. printf(“Mark2 : %f\n”.ptr->stud_name).(*ptr).60}. float mark2. } void total(struct student *a) { a->tot = a->m->mark1 + a->m->mark2 + a->m->mark3. }m. ptr=&s. total(ptr).ptr->m->mark3). }.40.

printf(“%d\n”. In union the memory is allocated for the longest member in the union.color=’r’. In structure the memory is allocated for all the members included within the structure and all can be accessed simultaneously. When a function returns a structure. }shirt.size=12.shirt. }p1. shirt.shirt. The called function must be declared in the calling function for its type. Thus 4 bytes will be allocated and that memory is shared by all members in the union.color). if it is placed after the calling function. float price. So the definition of union is same as structure except with the keyword union.size). The main difference between the structure and the union is in the memory allocation only. printf(“%c\n”. Example: Union product { int quantity. it must be assigned to a structure of identical type in the calling function. So that all the members in the union can share the allocated memory one at a time.• • • argument must be of the same struct type. In the above the memory is allocated based on the longest data type float. int size. shirt. The return statement is necessary only when the function is returning some data. char code. UNIONS: Unions are the concept derived from structure . } . Example: /unions example*/ void main() { union samp { char color.

Thus at a time only one member can be accessed. If we have a statement as follows shirt.size=12; printf(“%d %c\n”, shirt.size, shirt.color); Then the output will be 158.garbage character BIT FIELDS: There are occasions where data items require much less space than the allocated space. C allows the user to use small bit fields to hold data items and thereby to pack several data items in a word of memory. A bit field is a set of adjacent bits whose size can be from 1 to 16 bits in length. The name and size of bit fields are defined using a structure. 159.Bi t field provides exact amount of bits required for storage of values. If a variable value is 1 or 0 we need a single bit to store it. 160.The variable is expressed between 0 and 3, then the two bits are sufficient for storing these values. 161.Similarly if a variable assumes value between 0 and 7 then three bits will be sufficient to hold the variable and so on. 162.The number of bits required for a variable is specified by nonnegative integer followed by colon. 163.To hold the information we use the variable. The variables occupy a minimum of one byte for char and two bytes for integer. 164.The information about the vehicle, following information has to be stored in the memory. 165.Petrol vehicle 166.Diesel vehicle 167.Two wheeler vehicle 168.Four wheeler vehicle 169.Old model 170.New model In order to store the status of the above information we may need two bits for types of rules as to whether the vehicle is of petrol or diesel type. Three bits for its type as to whether the vehicle is two or four wheeler. There are restricted on bit fields when array are used. Array of bit fields are not permitted. The pointer cannot be used for addressing the bit field directly, although the use of the member access operator (à) is acceptable. The structure for the above problem would be as follows Struct vehicle { Unsigned type:3; Unsigned fuel:2;

Unsigned model:3; }; The colon (;) in the above declaration tells to the compiler that bit fields are used in the structure and the number after it indicates how many bits are required to allot to the field. Example: Write a program to store the information of vehicle. Use bit fields to store the status of information. #include <stdio.h> #include <conio.h> #define PETROL 1 #define DIESEL 2 #define TWO_WE 3 #define FOUR_WE 4 #define OLD 5 #define NEW 6 Void main() { Struct vehicle { Unsigned type:3; Unsigned fuel:2; Unsigned model:3; }; Struct vehicle v; v.type=FOUR_WE; v.fuel=DIESEL; v.model=OLD; clrscr(); printf(“\ntype of vehicle:%d”,v.type); printf(“\nfuel:%d”,v.fuel); printf(“\nmodel:%d”,v.model); } OUTPUT: Type of vehicle:4 Fuel: 2 Model:5 Explanation: In the above program using #define macros are declared. The information about the vehicle is indicated between integer 1 to 6. The structure vehicle is declared with bit field. The number of bits required for each member is initialized. As per the program for type of vehicle requires 3bit, fuel requires 2 bits and model requires 3 bits. An object v is declared. Using the object bit fields are initialized with data. Format:

Thedatetype can either be signed or unsigned int and the bit_length specifies the number of bits. Rules: • • The first field always starts with the first bit of the word. The sum of all the fields in the structure should not be more than the size of a word. • There can be unnamed fields declared with size Example: unsigned :2; Such fields provide padding within word. • • There can be unused bits in a word. We cannot take address of a bit field variable(ie)we cannot read values into bit field variables nor can we use pointers to access them. • Bit fields cannot be arrayed. • Bit fields should be assigned values within their range. Example: Main() { struct num { unsigned a:1; unsigned b:2;

unsigned d:6. Explain structure with pointers. 174.c. n.c=4.n.Explain Bit fields.d=14.n. }n.Describe structure with suitable examples. n. n.unsigned c:3.a.b.b=2.n. What is the difference between Them. n. 175.d).Explain union with suitable examples. } Output: 0 2 4 14 Suggested Questions : 171. .What is structure and Union. printf(“%d %d %d %d\n”. 172.a=0.n. 173.


MYTHILI 16 . Steps for file operation. closing a file. high level i/o use C’s standard library functions. Structures read and write. BASIC FILE OPERATIONS: 1. other file functions.STUDY MATERIAL COURSE SEMESTER UNIT SUBJECT NAME LECTURER NAME NUMBER OF PAGES DATE OF ISSUE Unit-V Files: Streams and file types. File I/O. 2. It becomes difficult and time consuming to handle large volumes of data through terminals. writing data to a file 5. opening a file 3. HIGH LEVEL I/O FUNCTIONS: : : : : : II YEAR A. Command line arguments. The entire data is lost when either the program is terminated or the computer is turned off.Sc ECS : III V PROGRAMMING IN C : D.scanf() Problems in console oriented i/o operations: 1. There are 2 ways to perform operations on a file a. Example: printf(). FILE: A file is a place on disk where a group of related data is stored. B. reading data from a file 4. low level i/o use UNIX system calls b. I/O redirection CONSOLE ORIENTED I/O: Console oriented I/o functions are the functions that use the terminal as the target place. naming a file 2.

open the file for reading only “w” . a primary name 2.creates a new file or opens an existing file for use fclose( ) closes a file which has been opened for use getc( ) reads a character from a file putc ( ) writes a character to a file fprintf( ) writes a set of data values to a file fscanf( ) reads a set of data values to a file getw( ) reads an integer from a file putw( ) writes an integer to a file fseek( ) sets the position to a desired point in the file ftell( ) gives the current position in the file rewind( ) sets the position to the beginning of the file DEFINING AND OPENING A FILE: While opening a file we should include the following : 176. Example: input. Purpose may any one of the following . So all files should be declared as type FILE (defined data type). an optional period with the extension. It has 2 parts 1.filename the file for writing only “a” .purpose The filename is a string of characters and should be a valid one. . • read ( r ) • write ( w ) • append ( a ) GENERAL FORMAT FOR DEFINING A FILE : Function name fopen( ) Operation The mode is any one of the below type “r” .open the file for appending (or adding ) data to structure Data structure is defined as FILE in the standard I/O library.

if the purpose is ‘reading’.same as a except for both reading and writing. The contents are deleted.When trying to open a file . the file is opened with the current content safe .”w”). Another instance where we have to close a file is when we want to reopen the same file in a different mode. Many recent compilers include additional modes of operation: R+ . A+ . then the file is opened with the current contents safe. c. W+ .same as w except both for reading and writing. a file with specified name is created if the file does not exist. --------------------------INPUT OUTPUT OPERATIONS ON FILES: Function name fopen( ) Operation creates a new file or opens an existing file for use . a file with the specified name is created if the file does not exist. * p2. CLOSING A FILE: A file must be closed as soon as all operations on it have been completed. SYNTAX: Example: FILE * p1. when the purpose is ‘appending’ .the existing file is opened for both reading and writing. p2=fopen(“output”. fclose(p2). It also prevents any accidental misuse of the file. p1=fopen(“input”. and if it exists.”w”). This ensures that all outstanding information associated with the file is flushed out from buffers and all links to the files are broken. otherwise an error occurs. one of the following things should be noted: a. when the mode is ‘writing ‘. --------------------------fclose(p1). if they already exist. b.

f1=fopen(“input”. FILE *f1. …….h> main ( ) { FILE *f1.b=’b’. char c. SYNTAX: getc( ): To read a character from a file.”w”).fclose( ) getc( ) putc ( ) fprintf( ) fscanf( ) getw( ) putw( ) fseek( ) ftell( ) rewind( ) closes a file which has been opened for use reads a character from a file writes a character to a file writes a set of data values to a file reads a set of data values to a file reads an integer from a file writes an integer to a file sets the position to a desired point in the file gives the current position in the file sets the position to the beginning of the file To manipulate on character data we use getc() and putc() functions. /* open the file input*/ . Example: char a. printf(“data input \n”).f2). Program : # include <stdio. …… a=getc(f1). Putc(b. *f2. putc( ): To write a character to a file.

while ((c=getchar( ))!=EOF) /*get a character from keyboard */ putc (c, f1); /*write a character to input */ fclose(f1); /*close the file input */ printf(“\n data output \n\n”); f1=fopen(“input”,”r”); /*reopen the file input */ while ((c=getc(f1))!=EOF) /*read a character from input */ printf(“%c”,c); /*display a character on screen */ fclose(f1); /*close the file input */ } To manipulate an integer value we can use getw and putw functions. SYNTAX:

getw( ): To read an integer from a file. putw( ): To write an integer to a file. Example: int a,b=10; FILE *f1, *f2; …… a=getw(f1); ……. Putw(b,f2); Program : # include <stdio.h> main ( ) { FILE *f1; Int i,c; printf(“data input \n”); F1=fopen(“input”,”w”); /* open the file input*/ For (i=1;i<=10;i++) Scanf(“%d”,&c) If (c==-1) break; putw (c, f1); /*write a number to input */ fclose(f1); /*close the file input */ printf(“\n data output \n\n”); f1=fopen(“input”,”r”); /*reopen the file input */ while ((c=getw(f1))!=EOF) /*read a number from input */ printf(“%d”,c); /*display the number on screen

*/ fclose(f1); } /*close the file input */

To handle a group of mixed data simultaneously we can use fprintf and fscanf functions. SYNTAX:

fscanf( ): To read a group of data from a file. fprintf( ): To write a group of data to a file. Example: char a,b=’b’; int c,d=10; FILE *f1, *f2; …… fscanf(f1,“%d %c”,&c,&a); ……. fprintf(f2,”%d %c”,d,b); Program: # include <stdio.h> main ( ) { FILE *f1; char name[10]; int roll; printf(“data input \n”); f1=fopen(“input”,”w”); /* open the file input*/ scanf(“%s %d”,name,&roll); /*get a group of data from keyboard */ fprintf(f1,”%s %d”,name,roll); /*write a character to input */ fclose(f1); /*close the file input */ printf(“\n data output \n\n”); f1=fopen(“input”,”r”); /*reopen the file input */ fscanf (f1,”%s %d”,name,&roll); /*read data from input */ printf(“%s %d”,name,roll); /*display data on screen */ fclose(f1); /*close the file input */ } ERROR HANDLING DURING I/O OPERATIONS:

It is possible that an error may occur during i/o operations on a file. Typical error situations include: 1. trying to read beyond the end –of-file. 2. device overflow. 3. trying to use a file that has not been opened. 4. trying to perform an operation on a file, when the file is opened for another type of operation. 5. opening the file with an invalid name. 6. attempting to write to a write-protected file. If we fail to check such read and write errors, a program may behave abnormally when an error occurs. Two different types of library functions for error handling are feof( ) and ferror( ). SYNTAX:

feof( ): It is used to test for end of file condition. It takes the file pointer as the only argument and returns a nonzero integer value if all of the data from specified file has been read, and returns zero otherwise. Example: If (feof(fp)) Printf(“end of data”); ferror( ): This function reports the status of the file indicated. It takes a file pointer as its argument and returns nonzero integer if an error has been detected or returns a zero otherwise. Example: If ( ferror(fp)!=0) Printf(“an error has occurred”); Program: #include<stdio.h> void main() { FILE *f1; Char filename[10]; Int a,b,i; F1=fopen(“TEST”,”w”); For(I=0;I<10;I++) { scanf(“%d”,&a);

If((f1=fopen(filename. } } fclose(f1). goto x. Scanf(“%s”. …… rewind(f1). } fclose(f1).filename). In that case we use the 3 functions fseek(). } RANDOM ACCESS TO FILES: Sometimes we might want to access only particular parts of a file rather than the whole file.ftell(). It takes a file pointer as an argument and returns a type long that corresponds to the current position. n=ftell(f1). SYNTAX: Example: FILE *f1. } else { while(feof(f1)==0) { b=getw(f1). .rewind() in the C I/O library.putw(a.f1).b+10). x: printf(“Enter the filename). ftell(): The function ftell() gives the current position of a file.”r”))==NULL) { printf(“Invalid file name\n”). printf(“%d\n”. SYNTAX: rewind(): The function rewind() moves the pointer to the start of the file. It takes a file pointer as an argument and moves the pointer to the start of the file.

Position – position takes one of the 3 values 179.0). file pointer – pointer to the concerned file.m. Fp=fopen(“test”.2) – go to the end of the file.1) – go forward by m bytes. fseek(fp. Example: fseek(fp.1 – current position 181. //writes characters //gives the current //moves the . Program: #include<stdio. Long n.0) – move to m+1th byte.f1).”r”).0L. 3.ftell(f1). { fseek(f1. fseek(fp. While((c=getchar())!=EOF) Putc(c. It takes 3 arguments.1) – stay in the current position. into the file. Advantages of rewind(): Helps to read a file more than once without having to open and close it.h> void main() { FILE *f1. While(feof(f1)==0) position by 5 bytes. position of the //pointer in the file Fclose(f1).”w”). fseek(fp.n. fseek(fp.0L.0L.-m. Offset – specifies the number of positions(bytes) to be moved. Printf(“No of characters %ld\n”. fseek(): This function is used to move to the desired position in the file. N=0L. 2. fseek(fp. F1=fopen(“test”.2 – end of file.0 – start of file.m.0) – go to the beginning of the file. 1. 180.1) – go backwards by m bytes.Now n will have a value of 0 ( the start of the file).

• They are placed before the main() function. Preprocessor directives are placed before the main() function.ftell(f1). • They do not require a semicolon at the end. String value may be a constant .getc(f1)). Simple macro substitution 2. Compiler control directives Macro substitution: Macro substitution is a process where an identifier in a program is replaced by a predefined string composed of one or more tokens. Macro substitution directives 2. Identifier should be in capital letters. expression or another macro call. fclose(f1). }while(!fseek(f1.printf(“Current position %ld current character %c\n”. Rules: • Preprocessor directives begin with #. Different forms of macro substitution are as follows: 1. This statement is known as a macro definition. Nested macro substitution SIMPLE MACRO SUBSTITUTION: .1). Argumented macro substitution 3. n=n+5L. File inclusion directives 3.-2L. } C PREPROCESSOR DIRECTIVES: The preprocessor is a program that processes the source code before it passes through the compiler.2) //moves to the last character do //prints the file in reverse { printf(“%c”. SYNTAX: There is no space in between the # and define. } fseek(f1. Categories: 1. It operates under the preprocessor directives or preprocessor command lines.-1L. The processor accomplishes this task by using #define statement.getc(f1)).

When a macro is called. scanf(“%d”. } /* 100 is assigned to .h> #define CUBE(x) x*x*x void main() { int a.Simple string is commonly used to define constants. printf(“Value = %d”. Subsequent occurrence of a macro with arguments is known as a macro call. Here the string behaves like a template.1 IS ASSIGNED TO AREA*/ Program: #include<stdio.&a). Program: #include<stdio. Example: #define COUNT 100 COUNT*/ #define CAPITAL “delhi” /* “delhi “ is assigned toCAPITAL*/ #define AREA 5*2. res=CUBE(a). It takes the form The basic difference between the previous and the current one is the replacement of macro with arguments. replacing the formal parameters with the actual parameters.1 /*5*2.res.M*5). the preprocessor substitutes the string. if(a EQUALS M) //the statement is translated as if(a == 5) printf(“a and M are equal”). printf(”Result = %d\n”. } Output: Value = 25 MACROS WITH ARGUMENTS: The preprocessor permits us to define more complex and more useful forms of replacements.res). printf(“Enter value”).h> #define M 5 #define AND && #define EQUALS == void main() { int a=5.

That is one macro definition can be paced inside another macro. The above checks if TEST is defined in the header file . Example: #define SQUARE(x) ((x)*(x)) #define CUBE(x) ((x)*SQUARE(x)) If we call CUBE(side) then it call SQUARE(side) and calculate side*side*side.h> /* include the predefined header file in to our program*/ #include “define.h” /* include the user defined header file to the program*/ Example: #include “test. If suppose you want to test whether the particular macro is defined in the given header file or not by using the directive #ifndef.H” #ifndef TEST #define TEST 1 #endif …….c” #define M 100 void main() { …… …… } COMPILER CONTROL DIRECTIVES: 1.NESTED MACRO SUBSTITUTIONS: The macro definition can be nested. So that we need not rewrite those functions or macro definitions. Example: #include “DEFINE.using the statement #undef identifer Example: #undef SQUARE The above will undefine the macro definition SQUARE FILE INCLUSION: An external file containing functions or macro definitions can be included as a part of a program. UNDEFINING A MACRO: A defined macro can be undefined . This is achieved by the preprocessor directive #include <stdio.

Using identifier the variables can be declared using the following syntax: Examples: Typedef int units..batch2.exiSting data type Identifier –new name given to the data type Typedef cannot create a new type. TYPE DEFINITION: This allows the user to define the identifier that representS an existing data type. Categories: • Bitwise logical operators • Bitwise shift operators • One’s complement operator. The user-defined type is later used to declare variables. . Example: …………. For that he may use the directive #ifdef. 2. General form: Typedef .keyword Type . Units batch1. BITWISE OPERATORS: Purpose: Bitwise operators are required to manipulate individual bits in memory. #endif In the above module if we want to run the program on the IBM machine we include the directive #define IBM_PC. Units name[10].name1[20].H” or not if it is included then TEST will be set to 1. If suppose the programmer has to design a large program with different requirements made by different user then depending upon the user he may activate some of the additional features. #ifdef IBM_PC code for IBM_PC #else code for other machines.“DEFINE.

One’s complement operator: This is a unary operator that causes the bits of its operand to be inverted such that 0’s become 1’s and 1’s become 0’s. Example: B = a & 0x3f. printf(“Bitwise or = %d”. //010 int c. Else 0 is returned. Else returns a 0) ^ bitwise EXCLUSIVE OR(returns 1 if one of the bits is 1 and the other is 0.e. printf(“Bitwise exclusive or = %d”.d. << >> Example: shift left shift right .a|b). //011 int b=2. A = 0110 1101 1011 0111 Mask = 0000 0000 0011 1111 -----------------------------------------b = 0000 0000 0011 0111 Bitwise shift operators: There are 2 shift operators. Example: ~011 = 100 Bitwise logical operators: There are 3 logical operators.h> void main() { int a=3.) | bitwise OR(returns a 1 if atleast one of the bits has a value of 1.The symbol used is ~.a^b). Operator Meaning & bitwise AND(returns a 1 if both bits have a value of 1.) Program: #include<stdio.a&b). printf(“Bitwise and = %d”. } Output: Bitwise and = 2 Bitwise or = 3 Bitwise exclusive or = 1 Masking: Masking is the process in which a bit pattern is transformed into another pattern by means of a logical bitwise operator.

word).I++) Fprintf(fp.I. If a = 0110 1101 1011 0111 Then a is shifted 6 positions to the left.word]). Int I.I++) { fscanf(fp.char *argv[]) { FILE *fp.argc). Printf(“No of command line arguments = %d\n”. Example: C>PROGRAM X_FILE Y_FILE Program to be invoked command line arguments So argv[0]=program Argv[1]=x_file Argv[2[=y_file Program: #include<stdio.”%s”. So b = 0110 1101 1100 0000 B = a >>6. // reads and prints the arguments printf(“Command line argument[%d] is %s\n”. For(I=1. The parameters are passed to the main function through 2 arguments argc and argv Argc – argument counter – counts the number of arguments. Char word[15].”w”). Fp=fopen(argv[1]. Argv – argument vector – has an array of character pointers to the command line arguments. . COMMAND LINE ARGUMENTS: It is a parameter supplied to the program when the program is invoked.I<argc.h> main(int argc. //writes arguments into file Fclose(fp). For(I=1. Fp=fopen(fp.”r”).argv[I]). B = 0000 0001 1011 0110 BITFIELDS: Refer IV unit.”%s”.I<argc.B = a << 6.

Write short notes on file handling commands 195.Explain about register & extern variables 193.Explain how strings may be written into file.Write the syntax of the function fprintf() 183. } Suggested Questions Objective Questions 182.Write short notes on preprocessor directives 191. 190.Which operator is used for right shift? 187.What is EOF? 185.Write short notes on bitwise operators 189. Compare fread & fwrite . fscanf & fprintf with suitable examples. .Write a program to copy the contents of one file to another using command Line arguments 4. 192.# Define is used to _____________ 186.} fclose(fp).Explain about macro preprocessor directives 196.Explain about conditional compilation Long answers 194.Explain command line arguments.Which functions are used to write the integer values into file? 184.Write the syntax of fopen() Short answers: 188.

Sign up to vote on this title
UsefulNot useful