• No results found

'C' Notes

N/A
N/A
Protected

Academic year: 2021

Share "'C' Notes"

Copied!
57
0
0

Loading.... (view fulltext now)

Full text

(1)

‘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:-

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

.

(2)

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 time because 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.

(3)

(F) Character

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)

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 program

String - Collection of Characters

Operator - 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)

‘C’ Tokens

Keywords

Identifiers

Constants

Special Symbols

Operators

Strings

Constants

Numeric Constant

Character Constant

Integer Constant

Real Constant

Single Character

(4)

(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

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)

(5)

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.

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 )

char

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

(6)

( K) Storage classes :-

‘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 .

(7)

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=a×10  a ×=10; 5) Increment AND decrement

operator-++ (Increment) -- (Decrement)

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

(8)

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 ; else

x=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

(9)

(typename) Expression; (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 Section

Function1( )

Function2( )

Function3( )

.

.

.

FunctionN( )

(10)

Important points about ‘C’ program

1. 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 starts

8. 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)

12. goto statement cannot jump between functions. 13. exit(0) forcefully terminates the program .

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 int

l for long int or double L 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

(12)

{

statement block ; }

statement – x ;

(b)The if else statement

SYNTAX –

If ( condition )

{

True –block statements ; }

else {

False- block statements ; } Statement X; Is Condition ?

Statement Block

False

Statement - X

Next statement

Is Condition ?

False Block Statement False

Statement - X

Next statement

True Block Statement

(13)

(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; } . . . .

(14)

else if ( test condition n) { 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 Statement

The 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;

(15)

default :

Default block statement ; }

statement x;

Here the “Expression” is an integer expression or characters. value-1, value-2, are constants or constant 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;

(16)

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 certain Point 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; else printf(“%d%d%d\n”,I,j,k); } } } out:

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

Dicision Making and looping

Looping : - 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.

(17)

‘C’ language provides three loop constructs for performing loop operation. 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

(18)

printf(“Input a number\n”); number=getnum( ); } 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. loops-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.

(19)

loop:-The for loop in C has several capabilities that are not found in other loop constructs. 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:-………….. …………..

(20)

for( I=1 ; I<10 ; ++I) { ---for(j=1; j ! = 5; ++j) { ` ---} ---}

---Nesting can be performed on any one of the loops.

Jumps in Loops:-

(Break & goto statements)

Inner

Loop Outer loop

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)

(21)

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 )

(22)

Arrays

Definition: - 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];

(23)

Float height [50]; Declaration of twodimensional 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

(24)

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 characters

Definition :- 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 11 21 15 13 22 12

45 3 5 31 35

56 19 91 1 18

(25)

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);

or

scanf(“%[^\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.

(26)

characters:-‘ C characters:-‘ 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.

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.

(27)

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.) 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.

(28)

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.

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-

(29)

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.

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

(30)

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 Value 2.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.

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 ( )

{

(31)

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. 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);

(32)

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

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; ………..

……….. }

(33)

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);

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 ); }

(34)

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>

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++) {

(35)

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;

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); }

(36)

/* 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:

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.

(37)

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.

Pointers

Definition 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.

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.

(38)

For example:-int a, *p; p=&a; *p=100;

Types of pointer variable declaration: Example :

char *cptr; pointer to character type variables int *iptr; *num pointer to integer type variables float *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 *)

# 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.

1006

100

1006

(39)

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( ); 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 */

(40)

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;

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.

(41)

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); }

Structures

Definition :

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:

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; };

(42)

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: 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.

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; };

(43)

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) }

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; 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]

(44)

File Handling

Introduction

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.

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.

(45)

Return values

 file pointer if successful  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:

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 lost 2. 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

(46)

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 Level

Unformatted Formatted

I/O Character

I/O Numeric I/O String I/O getc( ) 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( ).

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:

(47)

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);

/*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) }

References

Related documents

In another study, 168 middle-aged men with at least two cardiovascular risk factors who were physically inactive (physical activity &lt; 3 times per week) were divided into

tomb furniture - presumably represented by the 'well- preserved body ,16) - has been identified as Amenemopet called Pairy, brother to Sennufer and mayor of Thebes and vizier

Produces another cobol have usage pointer data items which holds a sum clause, so is specified the index values can be any report group consisted of contents.. Followed only

There any data type usually does not assigned a null and assignment error depend on one location in memory or standard libraries that assigning anything... The current state of

○ If BP elevated, think primary aldosteronism, Cushing’s, renal artery stenosis, ○ If BP normal, think hypomagnesemia, severe hypoK, Bartter’s, NaHCO3,

Copyright and assign a pointer holds the array using the allocated chunk of the value is called pointer points to access that the memory which we not.. Place an address that value

For the broad samples of men and women in East and West Germany every first graph in Fig- ure 1 to 4 (Appendix) shows considerable and well-determined locking-in effects during the