Top Banner
Notes on ‘C’ Language By-Umesh Bhardwaj ‘C’ Language [A.] There are four type of number system as following- (1) Decimal number system (Total no. Used - 10 nos.) (0-9) (2) Octal number system (Total no. Used - 8 nos.) (0-7) (3) Hexadecimal number system (Total no. Used - 16 nos.) (0-9, A-F) (4) Binary number system (Total no. Used - 2 nos.) (0, 1) We all use Decimal Number System in general whereas Computer uses Binary Number System. [B.] There are basically three types of languages that continue language generation- (1) Machinery language (Binary language) (2) Assembly language (3) High level language [C.] Translator- Definition:- A special type of software or a program which converts any other language into the machinery language & vice-versa, is known as translator. There are basically three type of translator as following - (1) Assembler (2) Interpreter (3) Compiler Assembler:- A s/w or a program which convert the assembly language into the machinery language & vice-versa. 1
71
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 'C' Notes

Notes on ‘C’ Language By-Umesh Bhardwaj

‘C’ Language

[A.] There are four type of number system as following-

(1) Decimal number system (Total no. Used - 10 nos.) (0-9)

(2) Octal number system (Total no. Used - 8 nos.) (0-7)

(3) Hexadecimal number system (Total no. Used - 16 nos.) (0-9, A-F)

(4) Binary number system (Total no. Used - 2 nos.) (0, 1)

We all use Decimal Number System in general whereas Computer uses Binary Number System.

[B.] There are basically three types of languages that continue language generation-

(1) Machinery language (Binary language)

(2) Assembly language

(3) High level language

[C.] Translator-

Definition:- A special type of software or a program which converts any other language into the machinery language & vice-versa, is known as translator.

There are basically three type of translator as following -

(1) Assembler

(2) Interpreter

(3) Compiler

Assembler:- A s/w or a program which convert the assembly language into the machinery language & vice-versa.

Interpreter &Compiler:-

1

Both are S/W or program which convert the HLL into the machinery language & vice-versa.

Page 2: 'C' Notes

Notes on ‘C’ Language By-Umesh Bhardwaj

Difference between Interpreter & Compiler

Interpreter

It translates the source program line-by-line.(It means it would not execute the next line unless the first one has no error). So it is slower.

Compiler

It translate the source program as a whole, so it is faster in speed.

At the time of using interpreter each & every time, to obtain the output the source program is needed.

Whereas a compiler creates an unique object program, so there is no source code every timebecause out put can obtain by that object code.

Note: - For each high level language the machine require a separate Compiler or Interpreter. Example:- Interpreter based language- Cobol, Pascal, FORTRAN, HTML Compiler based language - C, C++ ,Visual Basic,Java..

(D) History of C

In 1960’s “Basic combined programming language“ (BCPL) called ‘B’ language was developed at Cambridge University. It was not fully satisfied language.

‘B’ language was modified by Denies Ritchie and was implemented at bell laboratories in 1977,was named ‘C’.

Turbo C- (Compiler made by Turbo company.)

Borland C- (Compiler name by Borland company.)

ANSI C – (Compiler made by American National Standard Institute)

(E) Features of ‘C’ language:-

(1) There are only 32 keywords.(2) Rich library of in-built function.(3) Fastest execution speed, Because of Compiler based language.(4) Open system- its ability to extend itself. We can developed our own function & add them to the

libraries.(5) It is the basis for “C++” & “Java”.(6) Structure programming approach .(7) This is highly portable language. This means that C program written for one computer can be run

on another with little or on modification.

(F) Character set:-

2

Page 3: 'C' Notes

Notes on ‘C’ Language By-Umesh Bhardwaj

The Characters in C are grouped into the following categories.:-

Letter A-Z & a-z. Digits 0-9. Special Characters-~,!,=,-,( ),*,&,^,%,$,#,@ ,--------. White Spaces.- blank space, tab, return, new line.

(G) Trigraph characters:-See in Chapter 2 of Balagurusamy page-19. (H) Tokens:-

In a ‘C’ program the smallest individual units are knows as ‘Tokens’. ‘C’ program are written using these token and the syntax of the language.

Keyword - The words which are pre defined by the ‘C’ language. Identifier - User defined variable names such as a, b, i, j, marks etc.Constant - A DataName whose value cannot be change during the execution of

the programString - Collection of CharactersOperator - A symbol which is used to perform specific operation

Note:- ‘C’ also support some special backslash charcter constant that are use in out put function. (page-25) (\a,\b,\n,\t)

3

‘C’ Tokens

Keywords

Identifiers

Constants Special Symbols

OperatorsStrings

Constants

Numeric Constant Character Constant

Integer Constant Real Constant Single Character Constant

String Constant

Page 4: 'C' Notes

Notes on ‘C’ Language By-Umesh Bhardwaj

(I) Variable & Constant

A variable & a constant is a data name that may be used to store a data value.

A value of Constant can not be changed during the executing of program.

Whereas value of Variable may take different value at different time during execution .

Variable name may consists of letter, digits, and Linder line (-) with following the below rules :-

1) They must being with a letter. 2) ANSI standard recognigs the length of 31 characters 3) Upper case & lover case are significant mean total is differ.4) Variable name should not be a key word.

(J) Data types: -

‘C’ supports four classes of data type as following-

1) Primary data type.2) User defined data type.3) Derived data type.4) Empty data type.

1) Primary data type:- int, float, char

4

Integer

Signed

Unsigned

int (2 byte) Range(-32768 to +32767)

short int (1 byte ) Range(-128 to +127)

long int (4 byte) Range(- 2,147,483,648 to +2,147,483,647 )

int (2 byte) Range(0 to +65535)

short int (1 byte ) Range(0 to 255)

long int (4 byte) Range( 2,147,483,648 to +2,147,483,647)

double (8 byte ) Range(1.7E-308 to 1.7E+308)Float

float (4 byte) Range(3.4E-38 to 3.4E+38)

long double (10 byte) Range(3.4E-4932 to 1,1E+4932 )

Page 5: 'C' Notes

Notes on ‘C’ Language By-Umesh Bhardwaj

2) User defined data type:-

a.) typedef <datatype> <identifier>;

Ex:- typedef int umesh; umesh a,b,c;

b.) enum <identifier> {value1, value2, value3, value4,………, value n};enum <identifier> v1, v2, v3, ……….., vn;

Ex:- enum days {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};enum days d1, d2, d3;

3) Derived data types:-Derived datatypes such as arrays, functions, structures & union and pointers will discuss in further topics.

4) Empty data set :-The empty data set is discussed in the chaptor on functions.

( K) Storage classes :-

5

char

signed char (1 byte) Range(-128 to +127)

unsigned char (1 byte) Range( 0 to 255 )

Page 6: 'C' Notes

Notes on ‘C’ Language By-Umesh Bhardwaj

‘C ’provides a variety of storage class specifiers that can be used to declare explicitly the scope & lifetime of variables.

There are four storage class specifies as following –

Storage class

Auto

Static

Extern

Register

Meaning

Local variable known to only to that function in which it is declared. Bydefult auto is set.

Local variable which exists and retain its value even after the control is transferred to the calling the function.

Global variable known to all function in the files .

Local variable which is stored in the register .

6

Page 7: 'C' Notes

Note:- Static & Extern variable are automatically intllized to zero. Auto variable contain garbage value unless they are initialize explicitly.

( L) Defining symbolic constant:-

[#define <symbolicname> <value of constant>]

Valid exampled of constant definition are:-

# define STRENGTH 1000

# define PASS-MARKS 50

# define MAX 200

# define PI 3.14154

(M) Operators & Expression:-

An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations.

‘C’ operator are as following categories:-

1) Arithmetic operator - +,-,*,/,% .2) Relational operator - >,>=,<,<=,= =,!=.3) Logical operator – AND(&&), OR (||), NOT(!)

4) Assignment operator - =

Short hand operator –“op=” is known as short hand assignment operator Ex - +=, -=, *=, /=, %=

Like- a =a+5 a +=5;a=a10 a =10;

5) Increment AND decrement operator-

++ (Increment) -- (Decrement)

They have two categories -a) Post increment or Decrementb) Pre increment or Decrement

Page 8: 'C' Notes

Note:- Post & Pre notations gives the same result when they form statement independently, they behave differently when they are used expression on the right hand side of an assignment statement.

Examples:-

M=1; m=1;++m; m=2;m--; m=1;

M=5; m=5;Y=++m y=6,m=6;Y=m++ y=6,m=7;

6) Conditional operators:- (Ternary operators)

(Condition Exp1 ? Exp2 : Exp3 );

Following statement can be written with the help of conditional operator as following:-

if(a>b)x=a; x= (a > b) ? a : b ;

elsex=b;

7) Bitwise Operators:- See at page no.55 in E. Balagurusamy.

8) Special Operators:-

Comma - ,Sizeof operator.Pointer operator- & - ‘address of ’ Operator

* - ‘ value at ‘ Operator

Member selection operator – (.) and (->)

Preprocessor operator –

String izing - #Token Pasting - ##

Note:- Type conversion in Expression –

(a) Auto type conversion

(b) Forcly type conversion (Type casting)

(typename) Expression;

Page 9: 'C' Notes

(N) Operator Precedence and Associativity :-

Each operator in C has a precedence associated with it. This precedence is used to determine how an expression involving more than one operator is evaluated.

There are distinct levels of precedence and an operators may belong to one of the levels.

The operator at the higher level of precedence is evaluated first.

The operator of same precedence is evaluated either from L-R or R-L, depending on the level, this is known as associativity of an operator.

See the table at page no. 66 in Balagurusamy.

Basic Structure of ‘C’ Programs

Documentation Section (Comment Staement) (//) (/*…*/)

Linking Secton (#Include Section)

Definition Section (Constant Declaration Section)

Global Declaration Section

Main( ) function Section{

}

Local Declaration Part

Executable Statement Part

Sub Program SectionFunction1( )

Function2( )

Function3( )

.

.

.FunctionN( )

User Defined Functions

Page 10: 'C' Notes

Important points about ‘C’ program1. Each ‘C’ program is written in lower case only.2. Each ‘C’ program must have at least 1 main function.3. All executable statement in ‘C’ must end written a semi colon (;).4. Anything given within “ “ is printed as it is.5. All variables in ‘C’ must be declared of it’s data types before they are used.6. All ‘C’ programs must be saved with (.c) extension.7. All header files are included before the main function starts8. All opening ‘ braces ‘ “parenthesis “,” brackets “, “quotations “ must have a

closing one.9. Use fflush(stdin) to flush keyboard buffer between two scanf’s provided to

second scanf accept the character .10. All single characters in ‘C’ must be enclosed within single quotes & strings are

enclosed in double quotes. 11. #define Statement should not end with semicolon.12. goto statement cannot jump between functions.13. exit(0) forcefully terminates the program .

Page 11: 'C' Notes

Special Note:- Reading a character -> getchar( ) function

char y =getchar ( ) ;

isalpha( ), isdigit( ) function islower( ) , isuppar( ) , tolower( ) , toupper( ) <ctype.h>I isprint( ), ispunct( ), isspace( ), isalnum( ) . Writing a characther -> putchar ( ) function

printf( ) & scanf( ) function . I

% Formats - %c for %f for float

%c for characters %s for string %[ characters] %[^ characters] %e – read a floating value ( exponent form) %g – read a floating value(e-type or f-type) %I – Decimal, hexadecimal, Octal %o – Octal %u – unsigned integer %x – hexadecimal integer

Use as prefix – h for short intl for long int or doubleL for long double

“Decision Making & Branching “

(There are also known as control or decision making statements .)

1) if statement 2) switch statement 3) conditional operator statement 4) go to statement

if statement

(a) simple if statement -

SYNTAX – if(condition) {

Page 12: 'C' Notes

statement block ;

} statement – x ;

(b)The if else statement :-

SYNTAX – If ( condition )

{True –block statements ;

}else {

False- block statements ; }Statement X;

Is Condition ?

Statement BlockFalse

Statement - X

Next statement

Is Condition ?

False Block StatementFalse

Statement - X

Next statement

True Block Statement

True False

Page 13: 'C' Notes

(C ) Nested of if else statement :-

SYNTAX :-

If ( test condition ){

If ( test condition ){

Statement 1;}else {

Statement 2;}

}else{

Statement 3;}Statement X;

(d) The else if ladder :-

SYNTAX :-if ( test condition 1){

Statement 1;}else if (test condition 2){

Statement 2;}else if ( test condition 3){

Statement 3;}

.

.

.

.else if ( test condition n){

Flow Chart for If..Else Statement

Page 14: 'C' Notes

Statement n;}else{

default Statement;}

Statement X;

Note :- Finding a leap Year

A leap Year is one that is evenly divisible by 4, other than century year(such as 1900) ; or a century year(such as 2000) .main( ){

int year;printf(“Please enter a year:-“);scanf(“%d”,&year);

/* If year is divisible by 4 and not divisible by 100, or is divisible by 400, it is leap year */

if (year%4==0 && year % 100 != 0 || year % 400 == 0){

printf(“%d is a leap year \n”,year);}else{

printf(“%d is not a leap year\n”,year);}

}

Not leap year – 1986, 1900 Leap Year - 1948, 2000

The Switch StatementThe general form of the switch statement is as shown below –

switch(expression){

case value 1:block statement 1;break;

case value 2:block statement 2;break;

.

.

.

.case value n:

block statement n;break;

default :Default block statement ;

Page 15: 'C' Notes

}statement x;

Here the “Expression” is an integer expression or characters. value-1, value-2, are constants orconstant expressions and are known as case labels.

First the integer expression following the keyword switch is evaluated. The value if gives is then matched, one by one, against the constant values, that follow the case statement when a match is found, the program executes the statement following that case, and all subsequent case and default statement as well. If no match is found with any of the case statement, only the statement following the default are executed

If he wants to execute only to that case which is matched than we can do this by using a “break” statement there is no need for a break statement after the default, since the control comes to the end anyway.

Note: -

(i) even if they are multiple statement to be execute in each can there is no need to enclose there within a pair of braces. (Unlike if, and else.)

(ii) Is switch a replacement of y? (Yes or no) Yes, because it offers a better way of writing programs as compared to it, and no because in certain situation we are left with no choice but to use if.

(iii) The disadvantage of switch is that one cannot have a case in a switch, which looks like

case K <=20 ;

(iv) All that we can have after the case is an integer constant or a character constant. Even a float is not allowed.

(v) The advantage of switch statement over if, is that it leads to a more structured program and the level of indentation is manageable, more so if there are multiple statement within each case of a switch.

(vi)The “break” statement when used in a switch takes the control outside the switch. However, use of continue will not take there control to the beginning of switch as one is likely to belive.

(vii) Switch statement may be part of any one label so such statements would be called nested switch statements.

The goto statement‘C’ supports the goto statement to branch unconditionally from one point to another in the program.

The goto requires a label in order to identify the place where the branch is to be made. A label is any valid variable name, and must be followed by a colon.

goto label;…………………..…………………..…………………..…………………..…………………..label:statement;

label:statement;…………………..…………………..…………………..…………………..…………………..goto label;

Forward Jump BackWard Jump

Page 16: 'C' Notes

Note:- Avoid goto statement ! By using goto statement programs become unreliable, unreadable, and hard to debug.

The big problem with goto statement is that when we use them we can never be sure how we got to a certainPoint in our code. They obscure the flow of control. So as far as possible skip them.

The only programming situation in favor of using goto is when we want to take the control out of the loop, which is contained in several other loops.

main( ){

int I,,j,k;for(i=1; i<=3;i++){

for(j=1; j<=3;j++){

for(k=1; k<=3;k++){

if(I==3 && j==3 && k= =3)goto out;

elseprintf(“%d%d%d\n”,I,j,k);

}}

}out:printf(“Out of the loop at last”);

}

Dicision Making and loopingLooping : - In looping, a sequence of statements are executed until some conditions for termination of the loop are satisfied.

A program loop therefore consists of two segments, one known as the body of the loop are and the other known as the control statement.

The control statements test the certain conditions and then direct the repeated execution of the statements contained in the body of loop

Depending on the position of the control statement in the loop, a control structured may be classified either as the entry controlled loop or as the exit controlled loop.

In the entry continued loop, the control conditions are tested before the start of, the loop execution. Where as in an exit controlled loop the test is performed at the end of the body of the loop and therefore the body is executed unconditionally for the first time.

A looping process, in, general, would include the following four steps:-

(1) Setting & initializing of a counter.(2) Execution of the Statement’s in the loop.(3) Test for a specified condition for exaction of the loop.(4) Increment the counter.

‘C’ language provides three loop constructs for performing loop operation.

Page 17: 'C' Notes

They are :-

(1) The while loop statement.(2) The do…while loop statement.(3) The for loop statement.

The while Loop:-

Basic format of while statement-

While (Test condition) {

body of loop;}

The while is entry controlled loop structure.The test condition is evaluated and if the condition is true, then the body of the loop is executed.

For example:-a = 1 ;while (a<=10){

printf(“%d”,a);a++;

}

The do …..while Loop : -

The while loop construct that we have discussed in the previous section make a test condition before the loop is executed. Therefore the body of the loop may not be executed at all if condition is not satisfied at the very first attempt.

On some occasions it might be necessary to execute the body of the loop before the test is performed. Such situations can be handled with the help of the do…while statement. This takes the form:-

do{

body of loop;

} while(test condition); The do….while is exit controlled loop, and therefore the body of the loop is always executed at least once.

Example:-…………….…………….do{

printf(“Input a number\n”);number=getnum( );

Page 18: 'C' Notes

} while (number>0);…………….…………….…………….

This segment of a program reads a number from the keyboard until a zero or negative number is keyed in.

The test conditions may have compound relations as well.For example-

While(num>0 && num<100);

The For Loop Statement :-

Simple For loops-

The for loop is another entry controlled loop that provides a more concise loop structure. The general form of for loop is-

for( initilization ; test-condition ; increment){

body of the loop

}

The execution of the for statement is as follows:

1. Initialization of the control variables is done first, using assignment statements.2. Then the value of the control variable is tested using the test condition. if the condition is true, then the body of

loop is executed; otherwise the loop is terminated and the execution continues with the statement that immediately follows the loop.

3. When the body of the loop is executed, the control is transferred back to the for statement after evaluating the last statement in the loop. Now the control variable is incremented using an assignment statement such as i=i+1; and the new value of the control variable is again tested to see whether it satisfies the loop condition. If the condition is satisfied, the body of the loop is again executed. This process continues till the value of the control variable fails to satisfy the test condition.

For example: - for(x=0 ; x<=9 ; x++){

printf (“&d”,x);

}printf(“\n”);

One of the important points about the for loop is that all three actions, namely in initialization, testing, and incrementing, are placed in the for statement in one place.

Additional feature of the for loop:-

The for loop in C has several capabilities that are not found in other loop constructs.

Page 19: 'C' Notes

1. More than one variable can be initialize at a time in the for statement.

For example: - for (p=1,n=0; n<17; ++n)

Notice that the initialization section has two parts separated by comma.

2. Like the initialization section, the increment section may also have more than one part.

For example: - for (n=1,m=5-; n<=m; n++, m--)

4. The third feature is that the test-condition may have any compound relation and the testing need not be limited only to the loop control variable. Consider the example below:

sum=0;for(i=1; i<20 && sum<100; ++i){

sum=sum+i;printf(“%d%d\n”,sum);

}

It is also possible to use expression in the assignment statements of initilization and increment sections. For example, a statement of the type- For(x=(m+n/2; x>0; x=x/2) is perfectly valid.

Another unique aspect of the for loop is that one or more sections can be omitted, if necessary.Consider the following statements-

……………..……………..……………..m=5;for( ; m ! = 100 ; ){

printf(“%d\n”, m);m=m+5;

}………………………………………………

Both the initialization and increment sections are omitted in the for statement.

Nesting of for loops:-

Nesting of loops, that is, one for statement within another for statement, is allowed in C.

For example:-…………..…………..for( I=1 ; I<10 ; ++I){

Inner Loop

Outer loop

Page 20: 'C' Notes

--------------------------for(j=1; j ! = 5; ++j){

` --------------------------

}----------------------------

}------------------------------

Nesting can be performed on any one of the loops.

Jumps in Loops:- (Break & goto statements)While(……….){

----------------------------if(condition){

break;}----------------------

}next statement;

do{

----------------------------if(condition){

break;}----------------------

} While(……….);next statement;

for(…;……;…...){

----------------------------if(error){

break;}----------------------

}next statement

for(…;……;…...){

--------------for(…;……;…...){

--------------if(error){

break;}-----------

}next statement

}next statement

(a) (b)

(c) (d) Exiting a loop with break statement

Page 21: 'C' Notes

Skipping a part of loop :- (Continue Statement)

While(……….){

if(error)goto stop;--------------

if(condition){

goto abc;}abc:-----------

}stop:next statement

for(…;……;…...){

--------------for(…;……;…...){

--------------if(error){goto error;}-----------

}next statement

}error:……….

Jump within loop Exit from two loop

Jumping within and exiting from two loops with goto statement

While(test condition){

--------------if(condition){continue;}-----------

}next statement

for(…;……;…...){

--------------if(……){

continue;}next statement

}……….

( a) (b)

-:Bypassing and continuing in loops:-

do{

----------------------------if(condition){continue;}----------------------

} While(……….);next statement

(c )

Page 22: 'C' Notes

ArraysDefinition: - An array is a group of same data items that share a common name .

A particular value is indicated by writing a number called index number or subscript in bracket after the array name. The individual values are called elements. Array can be of any data type. The elements of the array are stored in consecutive memory locations.

There are three types of array as following ( 1 ) One dimensional array ( 2 ) Two dimensional array ( 3 ) Multi dimensional array .

If the single subscript or index is required to reference an element of an array . the array is known as single dimension array or linear array.

If two subscripts or indexes are required to reference an element , the array is known as two dimensional array.

Analogously , the array whole elements are referenced by two or more subscripts , are called multidimensional arrays .

“Declaration of Array “

Declaration of single dimension array: -

data_type array_name [size ] ;

For example: - int. number [5];Char name [10];Float height [50];

Page 23: 'C' Notes

Declaration of two-dimensional array: -

data_type array_name [row_size] [col_size] ;

int q [2] [3] ;float p[5] [5];

Declaration of multidimensional array :-

data_type array_name [s1] [s2] [s3] ---[sn]; int survey [3] [5] [12]; float table [5] [4] [5] [3];

“ Initilization of Arrays “-

We can initialize the elements of arrays in the same way as the ordinary variables when they are declared . For example int. a [3] ={ 0,0,0 } ;

float b[5] ={0.0,15.75,-10.3};int countes [ ]= {1,1,1,1};char name [ ] = {‘j’,’o’,’h’,’n’};

int a [3] [3] = { 0,0,0,1,1,1,2,2,2}; Or int a[3] [3]={ {0,0,0},{1,1,1},{2,2,2}};

Scaning values in array and printing values of array:-main( ){

int a[10],p,i,count=0;clrscr( );printf("\nEnter any five values:-");for(p=0;p<10;p++){

scanf("%d",&a[p]);}

printf("\n\nYour entered values are:-\n\n");

for(p=0;p<10;p++){

printf("%d ",a[p]);}

}Note :-In ‘c’ language the index or subscript number is start from 0 and end at (n-1) for an array of an size. For example suppose we declare an array a[5] the five element of array a are a[0],a[1],a[2],a[3],a[4] ; only. Here is not any element a[5];

int a[10] ;

29 34 43 12 11 59 72 85 63 90 0 1 2 3 4 5 6 7 8 9

Here a[0]=29, a[1]=34, a[2]=43, a[3]=12, a[4]=11, a[5]=59, a[6]=72, a[7]=85,a[8]=63, a[9]=90

Page 24: 'C' Notes

int b[5][5]; 0 1 2 3 4

0 1 2 3 4

Here b[0][0]=22, b[0][1]=21………………..,b[4][3]=8, b[4][4]=15;

Note :- (1) So by above example it is clear that we can access every element of one dimensional array by using a single loop and element of two dimensional array by using nested loops .

(2) C performs no bounds checking and therefore ,case should be exercised to ensure that the array indices are within the declared limits.

Strings or Array of charactersDefinition :- Collection or combination of more than one charactes is known as a string .

For example :- “India“ is a string whereas ‘i’ . ‘n’. ‘d’, ‘i’,’a’ are characters.

In ‘c’ language it is an array of characters or character data type.

The common operations performed on character string are :-

Reading and writing strings. Combining strings together. Copying con strings for equality. Extracting a portion of a string.

Declaration and initialization of strings

The strings is also declared as an array

Char string name [ size ];

Special note :-

When the compiler assigns a character string to a character array, it automatically supplies a null character (‘\0’) at the end of the string. Therefore, the size should be equal to the maximum number of characters in the string plus one.

22 21 34 10 1121 15 13 22 1245 3 5 31 3556 19 91 1 1889 36 2 8 6

Page 25: 'C' Notes

Characters arrays may be initialized when they declared. ‘C’ permits a character array to be initialized in either of the following three forms .

Static char city [9] = “ new york “;

Static char city [9] ={‘n’,’e’,’w’,’ ‘, ‘y’,’o’,’r’,’k’,’\0’};

Static char string[ ] ={“Good”};

Reading string from terminal:-

The familiar function scanf can be used with %s format specifications to read in a string of characters.

For example:- char str[15];Scanf(%s”,str);

The problem with the scanf function is that it terminates it’s input on the first white space it finds. There fore if we type the string “Umesh bhardwaj” then only the string “Umesh” will be read into the array string, since the blank space after the word “Umesh” will terminate the string.

Note that unlike previous scanf calls, in the case of character arrays, the ampersand (&) is not required before the variable name, because of the name of array is like a pointer type variable, that holds the base address of that array.

For accepting strings with space we must use function “ gets” or “scanf(“%[^characters]”) “format.

For example:-

char name[80];printf(“Enter any string:-“);gets(name); orscanf(“%[^\n]”,name);

Writing string to screen:-

For writing string to screen we can use the very popular function printf( ) with %s format or puts( ) function.

For example, the statement –

Print f (“%s”,name )

can be used to display the entire contents of the array “name”.

Note: we can also specify the precision we to which the array is displayed. For instance, the specification %10.4s indicates that the first four characters are to be printed in a field width of 10 columns. If we include the minus sign in the specifiation ( e.g. % -10.4s ), the string will be printed left justified.

Special note: - Arithmetic operation on characters:-

‘ C ‘ allow us to manipulate characters the same way we do within numbers. Whenever a character constant or character variable is used in an expression, it is automatically converted into an integer value by the system. The integer value depends on the local character set of the system.

Page 26: 'C' Notes

char x =’a’;printf (“%d \n”, x) is a valid statement.

x=’z’-1 is also valid statements.

We may also use character constants in relational expression. ch > =’A’ && ch <=’z’

Or Ch > = 65 && ch<=90

Note: We can use the 2-D character array to store the list of strings.

String Handling Library function

Sr.No. Function Meaning

1. strlen( ) To find the length of a string.Example:- (i) j=strlen(“Umesh”); The value of j is 5.

(ii) j=strlen(str); Find the number of character in str

2. strcpy( ) To copy the contents of string 2 into the string1.string 2 can be either an array, pinter or a constant string.Example:- (i) char str1[20]; strcpy(str1,”Umesh”); (ii) char str1[20], str2[20]; printf(“Enter any string:”); gets(str2); strcpy(str1,str2);

3. strcat( ) This function use to add the content of one string into another. (Joining of two strings.)

Page 27: 'C' Notes

4. strcmp( ) This function compares the string1 and string2 and return values as following. A negetive value if string1 is less then string2. It returns 0 if string1 is equal to string2. A positive value if string1 is greter than string2.

5. strrev( ) This function reverses the given string.6. strlwr( ) This function convert into lower case to the given string.7. struppr( ) Conversion into upper case.8. strncat( ) Concatenate first n characters of a string.9. strncpy( ) Copies first n characters of one string to another.10. strncmp( ) Compares first n characters of two strings.11. strchr( ) Finds first occurence of a given character in a string.12. strrchr( ) Finds last occurence of a given character in a string.13. strcmpi( ) Compares two strings without regard to case. 14. strnicmp( ) Compares first n characters of two strings without regard to case.15. strset( ) Set all characters of a string to a given character.16. strnset( ) Set n character of a string to a given character.

Functions Introduction

The function is a modular programming concept, which consisting of instructions to carryout the specific particular task in general. The called function, after executing, returns a single value to calling function of program.

Classification of function:

Functions are Categorize as following :-

1.Built-in or library or Standard function :- These are not required to be written by user. These are already define by C language. For example : sqrt( ),abs( ), pow ( ),log ( ),clrscr( ),printf( ),scanf( ) etc.

2.User Defined Function (UDFs) : - A user-defined function has to be developed by the user at the time of writing a program.

Note:- main( ) is the user defined function.

Need for UDFs -

It is possible to write any program uing only main function, it leads to a number of problems. The program may become too large and complex and as a result the taskmof debugging, testing, and maintaining becomes difficult. If a program is divided into functional parts, then each part may be independently coded and later combined into a single unit. These subprograms called ‘functions’ and these are much easier to understand, debug, and test.

Page 28: 'C' Notes

Another approach is to design a function that can be called and used whenever required. This saves both time and space.

Arguments and parameters -

Arguments : The variable used in the function reference called ‘arguments’. These are written within the parenthesis followed by the function name. These are also called actual parameters, which they are accepted, in the main program.

Parameters: The variables used in the function definition are called ‘parameters’. They are also referred as functional parameters or formal arguments, because they are not accepted values. They received value from the calling function. Parameters must be written within the parenthesis followed by the name of the function in the function definition.

Points to remember while using Arguments and parameters :

1. The number of arguments should be equal to the number of parameters used . 2. They must be one to one mapping between arguments and parameters and they should be in the

same order and should have the same data type. 3. The same variable can be used as arguments and parameters.

Category of Function:

A function, depending wheather arguments are present or not and wheather a value is returened or not, may categorized as following-

1. No arguments & No return value. (Procedure concept) 2. Arguments but no return value. 3. Arguments & return value.

1. Function with no argument & return value :

In this method called function does not receive any value of data from the calling function and it does not return any data back to the calling function . Hence there is no data transfer between the calling function and called function.for example:-clrscr( );

2. Function with arguments but no return value :

In this method that called function receives the data from the calling function. The arguments and parameters should match in numbers, data type and order. But the called function does not return any value back to the calling function instead it prints or use the data in its scope.

3. Function with arguments & return value :

In this method the called function receives a value from the calling function. It uses the data & performs the specified task within its scope, however after performing the specified task the called function return the computed value to the calling function. For example :- sqrt( );

Scope of variable in function:

In both calling and called function variables are used in its scope. The existence of the variable is restricted to the calling or called function. This is known as scope of variable on this base variables are classified in two types.

Page 29: 'C' Notes

1. Local variable (Internal Variables)

2. Global variable (External variables)

1.Local variable: The variables, which are, declared whithin a particular function and can be access by only to that particaular function.

2.Global variable: These variables are declared outside of any function and can be access by any other function.

Function prototypes:

All variables used in a program are declared in the declaration section of the program. This helps in providing proper memory representation for the variable and in identifying the operations that can be performed on them. Similarly it may be necessary to identify the existence of a function with the help of a declaration.

Note : The declaration of a function before it is used is called as ‘Function prototype’.

A prototype is used to identify the type of value that will be returned to the calling subprogram and this helps the compiler to generate the correct code for the return data and a prototype can also identify the sequence and number of arguments used by function. A function prototype may have the following syntax: <return_type_specifier> <Function _name ( ) >;

or<return_type_specifier> <Function_name( type 1,type2………..)>;When we define function prototype, information about the function is stored within the stack during compilation. During subsequent calls the compiler compares the functions and the name in the stack, if there is a proper match no error message is generated otherwise an error message is generated. However ‘C’ compiler indicates that there is no need to have a function prototype for the following reasons-

1. If the function body appears before the sub program, which calls it

2.If the function returns value of the type integer as all function by default are assumed to return an integer value.

For all other reasons a function prototype is compulsory.

Parameter passing Technique

In general we know that arguments are send to the function parameters and transfer their values respectively in function. This process is known as ‘Parameter Passing’. These are the technique or a method through which arguments are passed to the called function for the specified required processing. Mainly there are two methods or techniques of parameter passing, that are:

1.Call by Value2.Call by Reference

1. Call by value method :

In this method when value of arguments are passed from the calling function to a called function. The values of arguments are copied into the called function parameters. If any changes are made to the value in the called function, there are no any changes in the original value with in the calling function.

Page 30: 'C' Notes

Example: Illustrate a called by value method by an example of accept any two number and find the sum. main ( ){

int a,b,sum;int sumof(a,b);printf(“Enter any two number”);scanf (“%d %d “, &a,&b);sum =sumof(a,b);printf(“Sum of a and b number is %d”, sum);

}

/*Call by value function */int sumof(int x, int y);{

return (x+y);}

2. Call by reference method:

In this method the actual values are not passes instead their addresses are passed to the parameter. If any modification is made on data values in the called function, the value gets changed within the calling function.

Example: Function using call by reference mechanism. main ( ){ int a,b; void function(int *,int *);

a=30;b=50;printf ( “a=%d b=%d before function call \n”,a,b);function ( &a,&b);printf( “a=%d b= %d after function call \n”,a,b)

}

/*Call by reference function */

void function ( int *x, int *y)

{

*x =*x+*x;*y =*y+*y

}

Recursion

The term recursion is the modular programming technique where execution occurred repeatedly for the same set of instructions. In other words function called by itself as known as recursion.

In recursive function technique, when function call by itself there must be a terminating statement by constructing terminate on condition as per the logic of the problem (Recursive function should be terminate on condition based), otherwise function will not be terminated it may executes infinite times.

Page 31: 'C' Notes

Structure of recursive function or format :

< type of return-value > <Recursive function name >( parameters list ){

<Declaration>; ------------------ ------------------ ------------------ <Terminating condition>

------------------------------------<Value/variable> =Recursive function name ( expression);return (<value/variable>);

}

Example: Calculate factorial value of n number using recursive function. main ( ){

/* calculate the value of non negative integer using recursive function */

int num, f;int fact(int);printf (“Enter a number for calculating factorial value \n”);scanf (“%d”,&sum); if (num < 0){ printf (“kindly enter any +ve number \n”);}else { f =fact(num); printf (“The factorial of a no is %d”, f );}

}

/* recursive function */

int fact(int n){

int p;

if (n==1) /* terminating condition */ return ( 1);

else p =n*fact(n-1);/ *recursive function structure */

return (p);}

Storage classes

Page 32: 'C' Notes

In C, variable differ in behavior from those in most of the other languages. A variable in C can have anyone of the four storage classes:

1. Automatic storage class 2. External storage class 3. Static storage class 4. Register storage class

Automatic storage class

A variable is said to belong to the automatic class if validity or scope of the variable is limited to only the function in which it has been defined. Automatic variables are declared inside the function in which they are to be utilized. They are created when the function is called and destroyed automatically when the function is exited, hence the name automatic. Automatic variables are therefore local to the function in which they are declared. Because of this property, automatic variables are also referred to as local or internal variables. A variable declared inside a function without storage class specification is, by default, an automatic variable. One can use the keyboard auto to make the storage class explicit but no one does. main () {

auto int a,b,c; or int a,b,c; …………….. ……………..}

Example 1: A program to illustrate how automatic used in program. # include < stdio.h>main ( ){ auto int num =200; functionx( );

printf ( “%d\n ,num);}functionx( ){

auto int num = 20;functiony( )printf (“%d\n”,num);

}functiony( ){

auto int num = 10; print(“%d/n”,num);

}

Example 2: A program to convert a decimal number to its binary equivalent. # include <stdio.h>main ( ) {

auto int dec, bin ;int dec_ to_bin (int);printf ( “ Enter a decimal number \n”); scanf(“%d’&dec);

Page 33: 'C' Notes

bin =dec_to_bin ( dec );printf (“ The decimal number is = %d\n”,dec); printf (“The binary number is = %d\n”,bin );

}/* Function to find the binary equivalent */int dec _to _bin ( int d ) {

auto int b,r,y;b=0;y=1;

while (d>0){

r=d % 2;d=d/2;b=b+r * y;y=y * 10;

}return ( b );

}

External Storage Class

A variable is said to belong to the external storage class if the validity or scope of the variable is from the point of definition to the rest of the program. External variable are declared outside the function from which they can be utilized. They are created when the program is run and destroyed when the program is exited. External variables are therefore global to the program in which they are declared. Because of this property, external variables are also referred to as global or external variables. A variable declared outside to a function without storage class specification is by default, an external variable. one can use the keyword “extern” to make the storage class explicit but no one does.

extern int a;extern float p;

Example 1. A program to illustrate the properties of external variables.main ( ){

extern int num =500;output ( );

}output ( ){printf (“%d”,num ); /* num declared as external in the main program * 1}

Example 2: A program to transpose a matrix with the help of external variables

# include < stdio.h>

Page 34: 'C' Notes

extern int a [10] [10], b [10] [10];extern int i.j.n;main (){

printf (“Enter order of the matrix \n”);scanf(“%d”,&n);printf(“\n Enter matrix elements \n”);for(i=0;i<n;i++){

for(i=0;i<n;i++) { scanf(“%d”,&a[i][j]);

}printf(“ The original matrix is \n”);matprint (a);transpose( ); printf (“The transposed matrix is \n”); matprint (b);

}

/* Function to transpose a matrix */ transpose( ){

for(i=0;i<n;i++){

for(i=0;i<n;i++) b[i][j]=a[i][j];

}}

/* Function to print a matrix */ matprint(int x[][] ){

for(i=0;i<n;i++){

for(i=0;i<n;i++) b[i][j]=a[i][j];

}}

Static Storage Class

Static storage class concerns itself with the permanence of variables. Static variables are declared within a function hence the scope of such variables is the same as that of automatic variables. However as the name suggests. The value of static variables persists unit the end of the program. As a result if a function is exited and is re-entered again at a later stage. The static variables defined within will retain their last values. This feature allows functions to retain their values permanently throughout the execution of the program. A variable can be declared within the function as static using the keyboard static, for example

static int m;

static float n;

Page 35: 'C' Notes

A static variable is initialized only once when the program is complied. It is never initialized again and again. In the case of usage of automatic, external and static variables with the same name, local variables are given higher precedence and their values are used instead of the other variables. Initial values can be included to static variables. The rules associated with such declarations are:1. Only constants should be used to initialize static variables and not experssions. 2. The initial values are retained only as long as the values are not changed in the body of the function. If

the values are changed then the latest value is retained . 3. All static variables are automatically initialized to zeros.

Example 1: A program to generate N fibonacci number using static vatriables.

# include < stdio.h>main {

int i,n;int fibo ( int );print f(“Enter number of elements in the series \n”); scanf (“%d”,&n);printf (“\n Fibonacci numbers \n\n”); for (i=1;i<=n;i++) printf (“%d\t”,fibo (i);

}

/* Function to find fibonacci numbers */int fibo (int k){

static int n1=1;static int n2=1; int n3; if (k= =1)

n3=0;else if ( k==2)

n3=1;else {

n3=n1+n2;n1=n2;

n2=n3;}return (n3);

}

Register Variables

In the normal process of execution the value of a veriable is got from the memory to the central processing unit and after the processing is done it is returned back to the memory. However if the value of a variable is repeatedly required like in a looping statement, a lot of computer time is wasted in the process. All this can be taken care of by telling the compiler that a vatriable should be kept in one of the central processing units registers. instead of keeping in the memory. since a register access is much faster than a memory access. keeping the frequently accessed variables in the register will lead of faster execution of programs. This is done as follows:

Page 36: 'C' Notes

register int count;

Example 1: A program to display the number and its square from 1 to 10 using register variable.

# include <stdio.h>main ( ){

register int count,sqr;for ( count =1;count <=10;count++){

sqr =count *count;printf (“\n%d”,count, sqr);

}

}

Suppose, some of the variables have been declared as register and if these variables are not the correct data type such as char or int and if there are not enough registers available, then the c compiler will automatically ignore the register data type and it keeps them in the memory. It will be treated as automatic variable.

Example 2 : To display that the register variable is created in the CPU.# include <stdio.h>main ( ){ register int y;

printf (“The address of y =%u\n”,&y);}

Note : The above example generates an error message as the variable is created in the register if the CPU and not in the memory. CPU registers do not have address.

PointersDefinition of pointer:-

“A pointer is a special variable that can hold the address of the general variables, structures and functions that are used in the program. It contains only the memory location of the variable rather than its contents”.

Pointers are used with following:-

Basic data type variable. Array subscript variable. Function names. Structure & union Names.

Page 37: 'C' Notes

Advantage of pointers:

Pointers are Pointers are used to point to different data types and structures. Manipulation of data at different memory locations is easier. To achieve a clarity and simplicity. More compact and sufficient coding. To return multiple value via functions. Dynamic memory allocations.

Declaring a pointer variable:

Pointers are declared similar to normal variables, but we must specify when we declare them and what they are going to point to. If we declare a pointer to point an integer, then it can not be used to point a floating- point value.

Pointer operators:To declare and refer to a pointer variable, C provides two special operators as folowing :-

Address Operator (ampersand) : &

In-directional operator (Value at operator) : * & - This operator gives the memory address of the variable.

* - This operator gives the value of variable at that memory address which holds the pointer.

For example:-

int a, *p;

p=&a;

*p=100;

Types of pointer variable declaration:

Example :

char *cptr; pointer to character type variablesint *iptr; *num pointer to integer type variablesfloat *fptr pointer to float type variables char *name [ 15 ] point to character array

Note : * Symbol is part of the variables type.

Example: long int *x, *y; float *avg, *ratio;

Example: Program to assign the pointer values. (using operator & and *)

1006100 1006 a p

Page 38: 'C' Notes

# include<stdio.h>#include <conio.h>main ( ){ int x,y; /* xis pointer to integer variable */ clrscr ( ); y=10; x= &y; /* y value stored in pointer x.*/ printf (“ Address of y=%d\n”,&y); printf (“value of y=%d\n”,y); printf(Address of y =%d\n”,x); printf (“value of y=%d\n”,*x);} Output :-

Address of y =65555 Value of y=10 Address of y =65555 Value of y =10

Note: (1) 65555 is a address of x & y it should be unsigned +ve. (2) Last statement value of y indirectly by using *x. *x-value at address stored by x.

Therefore * is called indirection operator when used in conjunction with pointers.

Example: Program to assign the values using operator * and &.

# include <iostream.h>#include <conio.h>main ( ){ int x,y, *ipt; */ipt is a pointer to integer variable */ clrscr ( ); x=8; ipt =& x; */Address of x is stored in ipt */

y =*ipt; /*Content of pointer goes to y */ printf ( “ The value of y is =%d\n”, y );}

Output :-

The value of y is =8

Note: Variable y is assigned to value at the address stored in ipt. since ipt contains address of x, the value at address of x is 8, so ipt is equal to 10.

Example : Program to use arithmetic operations with pointers.

#include <stdio.h>#include <conio.h>main ( ){int a,*ipt; /* ipt is a pointer to integer variable. */int m,n,k;clscr( );

Page 39: 'C' Notes

a=150;ipt=&a /* address of a is assign to pointer */m=(*ipt ) ++;n=(*ipt)--;k=(*ipt)++;printf(“value of m = %d\n”,m);printf(“value of n= %d\n”,n);printf( “value of k=%d\n”,k);}

Pointers and Arrays

There is a close association between pointers and arrays, array elements can be accessed using pointers.

Example: Program to reads 10array elements & prints the elements using pointer technique.#include < iostream.h>#include <conio.h>#include <iomanip.h>main ( )(int a[10],*arpt,i;clrscr ( );printf (“Enter array values\n”);for (i=0;i<10;i++) scanf (“%d\n”,&a[i]);/*arpt points to array */arpt =a;/*printing by technique 1 */for (i=0;i<10;i++) printf (“%d\n arpt +i);/* printing by technique 2 */for (i=0;i<10;i++)printf (“%d”, *(arpt ++);}

Note: arpt is a pointer variable, in the first technique, in the for loop *(arpt +i) it start from element i.e. *(arpt =0).

In the second technique (* arpt=0) in first cycle then increment operation j is used with the pointer instead of adding loop index to the pointer.

Example: Program to read n number of elements and find the biggest elements among them.

# include <iostream.h> #include <conio.h>main ( )

{int a [100], *arpt, i, big, n;clrscr ( ); printf (“Enter number of elements: \n”);sacnf (“%d”, &n);printf (“Enter number of elements:\n”);for (i=0;i<n;i++)scanf (“%d”,&a[i]);/*the first elements address stored in arpt */arpt =a;

Page 40: 'C' Notes

big =*arpt /* first elements value stored in big */for (i=1;i<n;i++){if big <*(arpt +i)big =*(arpt+i);}printf (The biggest among the elements =\n”,big);}

Pointer used in function

It is mechanism by which pointer can be passed as arguments to the function. Thus,the data item of the calling program can be accessed by the called program. No values is copied when pointers are passed as arguments, as in the called by value method. Another important point is that, if the value are changed in the function this will modify the original contents of the actual parameters, this is not true of case of call by value method. when the pointers are are passed as an arguments we must follow the following points .

a. In the calling program,the function is invoked with a function name and addresses of actule parameters enclosed within the parenthesis.

Example: < function Name >(&var1, &var2, &var3 .............&var n)

var –all are actual parameters.

Example: Write a program to find the sum of 5 elements static in nature using pointers with function.

main ( ){ static int array [5]={200,400,600,800,1000} ; int addnum (int * ptr ); /* function prototype */ int sum ; sum = addnum (arrays) ; printf (“Sum of all array elements= %d \n”, sum); }

int addnum (int *ptr){ int total =0,index; for (index =0;index<5;index ++) total +=(ptr +index);

return (total);}

StructuresDefinition :

Structure is a meaningful organized Collection of data items of different type under a unique name we called as structure name. In ‘C’ declaration of such related data items or fields of different types by using reserve word ‘struct’.

Declaration of structure:

Page 41: 'C' Notes

Each and every structure must be defined or declared before it appears or using in program. Syntax: struct <structure name>{

<type 1> <field /data 1> <type 2> <field /data 2><type 3 > field /data3> .................................. .................................. <type n > < field /data n >

};

Example : struct student { int rollno; char name [30];

char address [30];char city[15];flot markes;

};

Initialization of structure:

Initializing a structure description of structure member is similar to initializing static type declaration.

Example: struct student s1 = {369,”Umesh”, “Pratap Nagar.”, “Jaipur”, 560};

Embedded Structure declaration: [Nested]

It means that, Structure within the another structure is called an embedded structure.

This type of structure declared mainly in two ways that are:

a) Structure may completely defined within the another structure.b) There may be a separate structure, the embedded structure declared first and the other

structure declare declared next.

Example:

1. struct emp{

int empno;char emp_name[30];int salary;struct date_join{

int day;int month;int year;

};

};

2. struct emp{

int empno;char emp_name[30];int salary;struct date_join

};struct date_join{

int day;int month;int year;

};

Page 42: 'C' Notes

Processing of Structure;

The process of structure is mainly concerned with the accessing structure member. Each member of a structure is accessed with dot (.) operator to access a particular member of the structure; the dot operator must be placed between the name of the structure & the name of the structure & the name of the structure member.

Note:- Here e1 is known as a structure variable.

If structure variable is general variable then data member can access by (.) dot operator. If structure variable is pointer variable then data member can access by (->) dot operator.

Examples:struct emp e1;

e1.emp_name, e1.empno , e1.salary etc.

struct emp *p;p->emp_name, p->empno, p->salary

1. Write a program to accept the student details as roll_no, name, city marks using structure and print the details.

struct std { int rollno; char name [30]; char city [15]; int marks;} st; /* structure definition */ /* st -> is the structure point */

main /* main program */{ printf (“Enter the roll no \n”); scanf(“%d”,&st.rollno); printf(“enter the name \n”); scanf(“%s”,st.name); printf (“enter the city\n”) scanf(“%d”,st.city); printf(“enter the Marks\n”); scanf(“%d”,&st.marks);/* printing details */ printf (“Roll Number :%d”,st.rollno); printf(”Name : %s”,st. name); printf (“City :%s”,st.city ); printf (“Marks: %d”,st.marks)

Page 43: 'C' Notes

}

Structure used with an array:

However we know that deferent type of data sets cannot be stored an array, so, to overcome this disadvantage structure can be stored along with its members in array structure.

Example: Storing 10-student details structure in an array. std (array name)

struct student {

int rollno; char name [30];}std;

File HandlingIntroduction

In the previous chapters we have come across the function scanf ( ) and printf ( ) frequently for entering data from the keyboard and display the result on to the VDU. This works fine when the input data is very small. But, as the volume of input data increases, in most of the applications, we find it necessary to store the data permanently on the disk and read from it for the following reasons:

1. It is very difficult to input large volume of data through terminals and apart from this it is time consuming to enter such volume of data.

2. If the program is terminated for any of the reason or computer is turned off, the entire data is lost.

To overcome all these problems, the concept of storing the data in disks was introduced. Here, the data can be stored on the disks, the data can be accessed as and when required and any number of times without destroying the data. The data are stored in the form of records and as a file, which is a place on the disk where a group of related data is stored. This chapter deals with various I/O operations on disk after opening a file and before closing. All file operations are achieved using ‘C’ library functions. The functions are classified into following two categories :-

Console input/output functions Disk input/output functions

The console I/O functions use to receive input from keyboard and display the output on monitor. The Disk I/O functions are use to perform operations on secondary storage devices such as floppy disk or hard disk.

int rollno; char name [30];

int rollno; char name [30];

int rollno; char name [30];

.......................

.......................

int rollno; char name [30];

std[0]

std[1]

std[2]

std[9]

Page 44: 'C' Notes

File operations

The various file operations that are performed are:-

Open a file Read data from the file Write data to the file Closing a file

All these operations can be performed either using low-level I/O that uses UNIX system calls, or using high –level I/O library. We shall discuss some of high-level I/O functions provided by C library.

1. fopen( )

The file should be opened before reading a file or before writing into a file.

Syntax:- fp =fopen (char *filename ,char *mode )

Where fp is a file pointer of type FILE, filename holds the name of the file to be opened. The filename should be a valid identifier. Mode details are provided in following table. This informs the library function about the purpose of opening a file.

Mode Meaning Description

r Read only mode File pointer set to beginning of file (BOF)

w Write only 1. If the file already exists,the contents are lost2. If file does not exists,a file is created for writing

a Append 1. If the file already exists,file pointer is set to end of file (EOE) in write mode.

2. If the file does not exists,it is created for writing and file pointer is at the beginning.

r+ Read Write Opened for read and write,the file pointer points to beginning of file.

w+ Read Write 1. Opened for read and write,and the file contents are lost if file exists.

2. If file does not exist,the file is read write and file pointer points to beginning of file.

a+ append 1. Opened for read,write and append 2. file pointer is the end of file.

Return values

file pointer if successful

Page 45: 'C' Notes

NULL if unsucessful

The file pointer returned should be of type FILE that is defined in the header file “stdio.h”. The data structure FILE is used to store information about a file. When a file is opened, the function always returns a pointer to the structure FILE. So, before opening a file the following declaration should be used;

FILE *fp;

Where fp is pointer to the structure FILE. Each opened file will have its own FILE structure. Using this file pointer, the necessary data can be accessed from the file. If a file cannot be opened successfully for some reason, the function returns NULL. we can use this NULL character to test whether a file has been successfully opened or not using the statement:

if (fp=NULL) printf (“Error in opeing the file\n”);

If this condition is not checked, the program may terminate or we may get wrong results.

2. fclose( )

This function is used to close the opened file. A file should be closed when all file operations are over. This ensures that all buffers are flushed and all the links to the file are broken. Once the file is closed, to access the file, it has to be reopened. The syntax is shown below:Syntax:

int fclose(FILE *fp)

Where fp is a file pointer. This function returns 0 if successful and EOF on error.

Note :- If the program is terminated, all the opened files will be closed automatically. But, as a programming practice, it is better to close to close all the opened files once we know that the files once we know that the file pointers are not required.

Disk I/O functions:

The disk I/O functions are classified into following categories: -

High level unformatted character I/O High level unformatted string I/O High level unformatted string I/O High level formatted I/O

High LevelUnformatted Formatted I/O

Character I/O Numeric I/O String I/Ogetc( ) getw( ) fscanf( )putc( ) putw( ) fprintf( )

ungetc( )

High level unformatted character I/O

It may be sometimes necessary to read or write character to/from disks. The charactter I/O functions are handy at this point of time. This section deals with character I/O functions such as getc( ) and putc( ).

Disk I/O Functions

Page 46: 'C' Notes

getc( ) and putc( )

getc( ) is a macro defined in stdio.h that gets one character from the file pointer specified. The function putc( ) is also a macro that outputs a character to a file stream specified using file pointer.

Syntax

int getc(FILE *fp);

On success, the function returns the character pointed to file pointer fp. The file pointer fp will automatically point to next character in the input stream. If there is any error or end of file is encountered , the function returns EOF.

The following declaration.int putc(int ch,ch, FILE *fp);

After success, writes the character stored in ch to the stream pointed to by the file pointer fp. If there is any error or end of-file is encountered, the function returns EOF.

ungetc( ) Syntax:

int ungetc(int c,FILE *fp);

This function pushes the character read previously using getc() back into input stream pointed to by the file pointer fp. The file pointer fp points to the character pushed. After using getc( ), this function should be used only once. This can be reused again immediately after using getc( ).On success, this function returns the read character using getc( ) and on faliure, the function ungetc( ) returns EOF. The program to copy one file to other file is shown in below example using getc( ) and putc( ) macros.

Example: Program to copy one file to other file using getc( ) and putc( )

#include <stdio.h>#include<process.h>main (){

FILE *fp1; /* Point to the input files */FILE *fp2 /Points to the output file */

char file1[10]; /* Name of the input files */char file2[10] /*Name of the output files */int ch; /* used to store character read */

printf (“Enter the output file \n);scanf (“%s”,file1);

/* Open the input file only in read mode */

if ( (fp1=fopen (file1,”r”) )==NULL){

printf (“Opening input files failed \n);exit (0);

}

Printf (“Enter the Output file \n);Scanf (“%s”,file2);

Page 47: 'C' Notes

/*Open the output file only in write mode */

fp2=fopen (file_2,”w”);

if (fp2==NULL){

printf (“Opening outfile failed \n”);Exit (0);

/* read till end of file is encountered */

while (ch =getc(fp1)!=EOF){ /* write each character read into output file */ putc (ch,fp2);}

/* close both input and output file */fclose (fp1);fclose(fp2)

}

High level unformatted numeric I/O: getw ( ) and putw ( )

The functions getw( ) and putw( ) are integer oriented functions and are similar to the functions getc ( ) & putc( ). These two functions are used to read arid write integer values.

The syntax of getw ( )isnum =getw (fp);

Where fp is a pointer. An integer is read from the file using file pointer fp and copied into num. Once the integer pointed by fp is read, the file pointer fp automatically points to the next integer in the file.

The syntax of putw( ) isputw(num,fp);

Where the integer stored is num will be written into the file whose file pointer is fp the program shown in below :-

Example:- Reads the numbers from the keyboard and write odd numbers to a file called odd-file and even numbers to a file called even file.

#include<stdio.h>

void main( ){

FILE *ifp; /* To store the numbers */FILE *ofp; /* To store odd numbers in ODD file */FILE *efp; /* To store EVEN numbers in ODD file */

int n; /* Number of elements to be stored in input file */int num; /* Numbers to be stored in the input files */int i; /* Used as a counter */

printf(“Enter the value of n \n”);scanf(“%d”,&n);

Page 48: 'C' Notes

ifp=fopen(“Input”,”w”);

printf(“Enter %d positive numbers and store in the file\n”,n);for(i=0;i<n;i++){

scanf(“%d”,&num); /* Read a positive number */putw(num,ifp); /*Write number into the file */

}

fclose(ifp);

/* Open the input file for reading */

ifp=fopen(“Input”,”r”);

/*Open the odd file for writing */

ofp=fopen(“Odd”,”w”);

/* Open the Even file for writing */

efp=fopen(“Even”,”w”);

/* Read from Input file */

while((num=getw(ifp))!=EOF){

if(num%2==0) /* Check for even or odd number*/putw(num,efp); /* Write to Even file */

elseputw(num,ofp); /* Write to Odd file */

}

fclose(ifp);fclose(ofp);fclose(efp);

/* Reopen the Odd file in read mode */printf(“Contents of Odd file\n”);

ofp=fopen(“Odd”,”r”);/* Display the contents of odd file */

while((num=getw(ofp))!=EOF){

printf(“%d\n”,num);}fclose(ofp);

/* Reopen the Even file in read mode */

printf(“Contents of Even file\n”);

efp=fopen(“Even”,”r”);

Page 49: 'C' Notes

/* Display the contents of Even file */

while((num=getw(efp))!=EOF){

printf(“%d\n”,num);}fclose(efp);

}

High level formatted I/O - fscanf( ) & fprintf( )

The functions fscanf( ) and fprintf( ) works exactly in similar way to that of scanf( ) and printf( ) functions. These functions handle mixed data such as integers, characters, floating point numbers etc.

fscanf( )

The syntax of fscanf( ) is:

Syntax:fscanf(fp,”Control String”,list);

Where fp is a file pointer, control string and list have the same meaning as in scanf( ) i.e., the variables specified in the list will take the values from the file specified by fp using the specifications provided in control string. For example, consider the statement

fscanf(fp,”%d %s %f”,&id,name,&salary);

Here the values for the variables id, name and salary are obtained from the file identified by the file pointer fp. This function returns the number of items that are successfully read fp. This function returns the number of items that are successfully read from the file identified by the file pointer fp.

fprintf( )

The function is similar to that of printf( ) except the syntax. The syntax of fprintf( ) is :

Syntax:-fprintf (fp, ”Control String”, list);

Where fp is a file pointer associated with a file that has been opened for writing. The control string and list have the same meaning as in printf( ) function i.e., the values of the variables specified in the list will be written into the file identified by file pointer fp using the specifications provided in control string. For example, consider the statement

fprintf(fp,”%d %s %f”,id,name,salary);

Here, the values for the variables id, name and salary are written into the file identified by file pointer fp. Consider the program shown in below example. Here the names of employees, the age and salary are written into a file. Also the contents of the file are displayed in the form of a table.

#include<stdlib.h>#include<stdio.h>

int main( ){

FILE *fp; //File pointer for the input file.int n; // Number of employees.char name[20]; //Name of an employee.

Page 50: 'C' Notes

int age; //Holds the age of an employee.float salary; //Holds the salary of an employee.int i; //Index variable.

printf(“Enter the number of employees\n”);scanf(“%d”,&n);

//Open a file in write mode.

fp=fopen(“INPUT”,”w”);

//Obtain employee detail and store in the file.

for(i=0;i<n;i++){

printf(“Enter name ,age and salary\n”);

//Obtain the name,age,salary from keyboard.

fscanf(stdin,”%s%d%f”,name,&age,&salary);

//Write name,age,salary into the file.

fprintf(fp,”%s%d%f”,name,age,salary);}fclose(fp);//Re-open the file in read mode..fp=fopen(“INPUT”,”r”);

for(i=0;i<n;i++){

//Read name,age and salary from the file .

fscanf(fp,”%s%d%f”,name,&age,&salary);

//Display name,age and salary on the screen.

fprintf(stdout,”%s%d%f”,name,age,salary);}

}

Error Handling:

During I/O operations, the errors such as:

Reading beyond end of file marker Unable to open a file Invalid file name Attempting to write-protected file etc.,

may occur. Such read and write errors results in abnormal behavior of the [program and so should not be ignored. If proper error checking is not provided, there may be premature termination of program or we may get incorrect output. The functions feof( ) and ferror( ) are used to detect I/O errors in the file.

feof( ):-

Page 51: 'C' Notes

This function is used to check for end of file. This function accepts file pointer as a parameter and returns either a non zero integer or a zero. If EOF is detected, a non-zero value is returned and if EOF is not detected, zero is returns. For example, if fp points to EOF and the statement

if (feof(fp))Printf (“End of file is reached\n”);

ferror ( ):-

This macro is used to get the status of a file. This function accepts file pointer as a parameter and returns a non-zero value if an error is detected and zero otherwise. For example, the statement

if (ferror(fp )!=0)printf (“Error in the file”);

displays the message “Error in the file” if there is an error in opening /reading/writing the file identified by fp. The program shown in below example provides how error-handling functions are used.

Example: -‘C’ program which provides error handling in files: -

#include<stdio.h>#include<process.h>void main( ){

FILE *fp;char file1[10];int i;char ch;printf(“Enter the file name:-\n”);scanf(“%s”,file1);fp=fopen(file1,”r”);if (fp==NULL){

printf(“Cannot open successfully\n”);exit(0);

}for(i=0;i<30;i++){

if(feof(fp)){

pintf(“\nVery few characters are present in file:-\n”);exit(0);

}ch=getc(fp);printf(“%c”,ch);

}}

In the above program, assume that file exists and is opened successfully. Using for loop, 30 characters have to be printed. But, if the file does not have so many characters, feof macro detects end of file of file and the message “Very few characters are present in the file” is displayed. If end of file is not reached, the first 30 characters from the input file are displayed.

Random access to files(File control functions):-

Page 52: 'C' Notes

The various file functions so far discussed read/write data sequentially. In some situations it may be necessary to point the file pointer to a specific position in the file. The various functions such as ftell( ), fseek( ), rewind ( ) are used for this specific purpose.

ftell( ):-

This function is used to obtain the current position of the file pointer. The syntax is:

long ftell (FILE* fp);

This function returns the current position of the file pointer on success and EOF on error. If this function return 1000, it indicates that 999characters have been read so far from the file and file pointer fp is pointing to the 1000 th

character in the file.

fseek ( ):-

This function is used to reposition the file pointer i.e. it is used to move the file pointer to the desired position within the file. Syntax int fseek (FILE *fp, long offset, int start-point);Where

fp is file pointer. offset can take positive, negative or zero value and specifies the number or bytes to be moved from the

location specified by start-point.

Start-point can take one of the values. 0 indicates from beginning of the file, 1 indicates from the current position and 2 indicate from the end of file.

This function returns 0 on success and non-zero value on failure. If offset is positive, the file pointer moves forwards. If it is negative, the file pointer moves backwards. For example –

fseek (fp,0,0) - file pointer moves to the beginning of the file

fseek(fp,0,1)-file pointer stays in the current position and is rarely used

fseek(fp,0,2)-file pointer moves to the end of file

fseek(fp,n,0)-file pointer moves n bytes from the beginning of the file

fseek(fp,n,1)-file pointer moves n bytes from the current position of file pointer

fseek (fp,-n,1)-file pointer moves n bytes backwards from the current position of file pointer

fseek(fp,-n,2)-file pointer moves n bytes backwards from the end of file.

rewind ( ):-

This function accepts file pointer as a parameter and resets the position of the file pointer to the start of the file. For example, if file pointer fp is in position 1000, by executing the statement-

rewind(fp);

Page 53: 'C' Notes

the file pointer fp is set to the very first position in the file. Note that the position of the first byte is 0, position of second byte is 1, the position of third byte is 2 and so on. Once a file is completely read the file pointer points to the end of file. By using this function, a file can be read more than once without closing and opening the file.

The program shown in below example finds the size of a given file and uses all the file control functions discussed.

Example:- ‘C’ program to print the size of a given file:-

#include<stdio.h>#include<process.h>

//function definition starts......long file_size(FILE *fp){

long curpos, length;

//Returns the current position of file pointer .curpos=ftell(fp);

// Move file pointer from begining of the file to EOF.

fseek(fp,0L, 2);

/* Obtain the current position of file pointer */

length=ftell(fp);

/* File pointer from the current position to the beginning. */

rewind(fp); // We can also use fseek(fp,curpos,0);

return length;}

// main function starts.......

main(){

FILE *fp;char file_name[20];printf(“Enter the file name:-“0;scanf(“%s”,file_name);

fp=fopen(file_name,”r”);if(fp==NULL ){

printf(“Error in opening file\n”);exit(0);

}printf(“Filesize of %s is %ldbytes\n”,file_name,filesize(fp);fclose(fp);

}

The program is self –explanatory with appropriate comments and the reader should read and understand the logic.

Page 54: 'C' Notes

Note: What is the difference between rewind (fp) and fseek (fp,0L,0) ? The answer is that ‘.’Functionality is same, but syntax and number of parameters are different”

Display contents of file :-

Now, let us write a program to display the contents of file. The file if specified in the command line, the user should be prompted for the file and that file should be opened and displayed. The complete program is shown in below example.

Example:- ‘C’ program to accept a file through command line or as specified by user during run and display the contents:-

#include<stdio.h>#include<process.h>#include<string.h>void main(int argc, char *argv[ ]) {

FILE *fp; //File [pointer used to display a file.char fname[10]; //File to be opened and displayed.char ch; // Holds the character to be displayed.if(argc==1){

/*No command line file name..*/printf(“Enter the file name:-“);scanf(“%s”,fname);

}else{

/* Command line file exist */strcpy(fname,argv[1]);

}

fp=fopen(fname,”r”);

if(fp==NULL){

printf(“File opening error\n”);exit(0);

}printf(“The contents of the file are:\n....................\n”);

//File opened successfully and display the contents.

while((ch=getc(fp))!=EOF){

printf(“%c”,ch);}

} Output:-

c:\>disp helloThe contents of file are:-....................Hello how are youThis is the first program using command line arguments.

Page 55: 'C' Notes

Good LuckHave Fun

Output:-

c:\>disp Enter the file name:- HelloThe contents of file are:-....................Hello how are youThis is the first program using command line arguments.Good LuckHave Fun

Note: The file name of this program is “disp.c” Before executing this program make sure that the file by name “Hello” exists in the current directory from where you are running the executable file “disp”. Also make sure that some text is stored in the file “Hello”. In the first output argv [0] corresponds to disp and argv [1] corresponds to the string “Hello” In the second output argv [1] is NULL.

In this program, in the beginning of the function main we are checking whether a file has been specified in the command line. If file not specified, the value of argc will be 1 and so the user is prompted to enter the file name during run time. But, if the value of argc is greater than 1, the control comes to else statement and the file specified in the command line is copied to fname which will be used for opening. Reset of the statements in the program is self-explanatory. Obtain text and create file (use only command line parameters)

Let us consider another program where to accept a file followed by a text only through command line parameters. The C program shown in below example achieves this and is self-explanatory using appropriate comments.

Example:- ‘C’ Program to accept a file and text through command arguments and create a file with the text

#include<stdio.h>#include<process.h>#include<string.h>void main(int argc, char *argv[ ]) {

FILE *fp; //File [pointer used to display a file.int i; //To access command line parameters.char str[30]; //Temporary storage.

//Check whether file name and text are missing in command line ..

if(argc==1){

printf(“File name missing in command line“);exit(0);

}

if(argc==2){

printf(“File name should be followed by some text.“);exit(0);

}//Command line has file name and text so create and open the file.

Page 56: 'C' Notes

fp=fopen(argv[1],”w”);

if(fp==NULL){

printf(“The file cannot be opened for writing\n”);exit(0);

}

//Write text in command line into file.

for(i=2;i<argc;i++){

//Note A single space after %s is required.

fprintf(fp,“%s”,argv[i]);}

fclose(fp);

//Open the file to read.

fp=fopen(argv[1],”r”);

if(fp==NULL){

printf(“Can not open for writing.\n”);exit(0);

}

//Display the file contents on the screen.

fscanf(fp,”%s”,str);

printf(“%s”,str);

fclose(fp);

}

Output:-

C:\>DISP temp This is the second programThis is the secod program

Note:- The name of file created is “temp” and will have the string “This is the second program” without any space in between the words.