C Programming Full
C Programming Full
UNIT– I
UNIT– II
1
UNIT – IV
UNIT – V
File Management: Introduction – Defining and opening a file –
Closing a file – Input/Output operation onfiles – Error handling during I/O
operations – Random access files – Command line arguments.
TEXT BOOK
REFERENCE BOOKS
2
UNIT-I
OVERVIEW OF C
History of C:
C is general-purpose, imperative computer programming language, supporting structured
programming language.
ALGOL was the first computer language to use a block structure. Although it never
became popular in USA, it was widely used in Europe.
In 1967, matrix Richards developed a language called BCPL (basic combined
programming language) primarily for writing system software.
C was evolved from ALGOL, BCPL by Dennis Ritchie at the bell laboratories in 1972.
C uses many concepts from these languages & added the concept of data types and other
powerful features.
During 1970s, C had evolved in to what is now known as “traditional C”.
ANSI (American national standard institute) approved by the international standards
organization (ISO) in 1990.
Importance of C:
It is a robust language whose rich set of built-in functions and operators can be used to
write any complex program.
There are only 32 keywords in ANSI C and its strength lies in its built-in-function.
C is highly portable. This means that C programs written for one computer can be run on
another with little or no modification.
C language is well suited for structured programming, thus requiring the user to think of a
problem in terms of function modules or blocks.
Another important features of C it its ability to extend itself. A C program is basically a
collection of functions that are supported by the C library.
Sample program:
Main ()
{ / * ………sample program ………*/
printf(“how are u”);
/ * ……………. End of program ………*/
}
This program when executed will produce the following output:
how are u
The main ( ) is a special function used by the C system to tell the computer where the
program starts.
Every program must have exactly one main function. The empty pair of parentheses
immediately following main indicates that the function main has no arguments.
The opening brace “{“ in the second line marks the beginning of the function main and
the closing brace “}” in the last line indicates the end of the function.
All the statements between these two braces form the function body.
The lines beginning with /* and ending with */ are known as comment line.
3
Documentation section
Link section
Definition section
Global variables declaration
Main( )
{
declaration part
executable part
}
Subprogram section
Function 1
Function 2
………
……….
Function n
The documentation section consists of a set of comment lines giving the name of the
program, another and other details, which the programmer would like to use later.
The link section provides instructions to the compiler to link functions from the system
library.
The definition section defines all symbolic constants. There are some variables that are
used in more than one function. Such variables are called global variables and are declared in the
global declaration section that is outside of all the function.
The declaration part declares all the variables used in the executable part. There is at
least one statement in the declaration and executable parts end with a semicolon (;).
The subprogram section contains all the user-defined that are called in the main function.
User defined functions are generally placed immediately after the main function,
although they may appear in any order.
All sections, except the main function section may be absent when they are not required.
Character set:
The characters that can be used to form words, numbers and expressions depend upon the
computer on which the program is run.
The characters in C are grouped into the following categories:
Letters
Digits
Special characters
4
White spaces
The compiler ignores white spaces unless they are a part of a string constant.
Trigraph characters:
Many non-English keyboards do not support all the characters mentioned below. ANSI C
introduces the concept of “trigraph” sequences to provide a way to enter certain characters that
are not available on some keyboards.
Each trigraph sequence consists of three characters. For, if a keyboard does not support
square brackets, we can still use them in a program using the trigraphs ??(and ??).
Letters -> A to Z.
Lower case -> a to z.
Decimal digits -> 0 to 9.
Special characters:
, comma
. period
; semicolon
: colon
? question mark
‘ apostrophe
“ quotation mark
! exclamation mark
+ plus
- minus
trigraph sequences:
C tokens:
In a passage of text, individual words and punctuation marks are called tokens. Similarly,
in a C program the smallest individual units are known as C tokens.
C tokens
5
Keywords:
Keywords are those words of C which have predefined meaning assigned by the C
language
They are also called reserved words
There are 32 keywords supported by ANSI C
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Identifier:
An identifier is one which is used to designate program elements like variables,
constants, array names and function names
There are a couple of rules governing the construction of valid identifiers. They are:
1. An identifier can have maximum 31 characters (ANSI C standard)
2. The permissible characters in identifiers include letters, digits, and an optional underscore
symbol
3. It should start with a letter
4. Special characters other than underscore are not permitted
5. It should not be a keyword
Valid Identifier:
Number
A1
A_1
A1b
Invalid Identifier:
1astarts with a digit
a 1space in between is not allowed
a,b, is not allowed
Keywords: Identifier:
1.It is a predefined one 1.It is a user-defined one
2.Also called reserved words 2.Also called variables, constants, array
names etc
3.It cannot used as an identifier 3.Space,comma,symbols are not used
4.caps are not allowed 4.Only hyphen in between the variables are
used
5.Eg:int,char,float,boolean 5.Eg:sum,num,a,b,g,a1,b1
Constants:
A constant is one where the value does not change during the execution of the program
enclosing it
A constant also gets stored in a memory location but, the address of the location is not
accessible to the programmer
6
Types of constants
1) Numeric constants
2) Character constants
1)Numeric constants:
It consists only of numerals
(ie)
An optional sign and an optional period
Two types
a) Integer constants
b) Real constants
a) Integer constants:
Integer constants are whole numbers (ie) without fractional part).They are classified in to
three types
(i)Decimal Integer constants
(ii)Octal Integer constants
(iii)Hexadecimal Integer constants
(i)Decimal Integer constants:
It is a sequence of one (or) more digits [0…….9]
It may have an optional + (or) – sign
It should not have a period as part of it
Commas and blank spaces are not permitted
Valid Decimal Integer constants:
345
-987
Invalid Decimal Integer constants:
3.45
3,34
(ii)Octal Integer constants:
It is a sequence of one (or) more digits [0…….7]
It may have an optional + (or) – sign
It should start with the digit 0
It should not have a period as part of it
Commas and blank spaces are not permitted
Valid Octal Integer constants:
0345
-054
+023
Invalid Octal Integer constants:
03.45
03,34
x45
678
(iii)Hexadecimal Integer constants:
It is a sequence of one (or) more digits [0…….9][A……….Z][a………..z]
It may have an optional + (or) – sign
It should start with the symbols 0X (or) 0x
It should not have a period as part of it
Commas and blank spaces are not permitted
Valid Hexadecimal Integer constants:
0x345
7
-0x987
0x34
0xA23
Invalid Hexadecimal Integer constants:
0x3.45
0x3,34
b)Real constants:
The real constants also known as floating point constants
Two types
(i)Fractional form
(ii)Exponent form
(i)Fractional form:
1. They must have at least one digit and a decimal point
2. An optional sign (+ (or) -) can precede a real constant
3. Commas (or) blank spaces are not permitted as part of a real constant
Valid Eg:
345.67
-987.87
Invalid eg:
3 45
3,34
123
(ii)Exponent form
It offers a convenient way for writing very large and small real constants
Eg:
23000000.0023*(10)8
0.23E8
(or) 0.23e8
0.0000001230.123*(10)-6
0.123E-6
(or) 0.123e-6
EExponent form
A real constant expressed in exponential form has two parts
(i)Mantissa part
(ii)Exponent part
(i)Mantissa part:
It is the part of the real constant to the left of E (or) e
(ii)Exponent part:
It is the part of the real constant to the right of E (or) e
Eg:
Mantissa Exponent Mantissa Exponent
8
Valid Eg:
1E3
12e-5
0.12E5
Invalid eg:
12E
12e3.4
12,3e4
234*e9
2)character constant:
It consists of one (or) more characters of the alphabet of c
Two types
i) Single character constant
ii) String constant
i)Single character constant:
A single character constant consists of only one character and it is enclosed with in a pair
of single quotes
Eg:
A
a
9
ii)String constant:
A string constant consists of one (or) more characters and it is enclosed with in a pair of
double quotes
Eg:
12bn
abc
Explain about variables. Differentiate Variables and Keywords
Variables:
A Variable is a named memory location
The value of which can change during the execution of the program enclosing it
Name of a variable should be a valid c identifier
Syntax1:
Data-type Variable;
They should declared at the beginning
They are ended with a semicolon
Eg:
int a;
Syntax2:
Data-type Variable1, Variable2………………………. Variable n;
Eg:
int a,b,c;
Keywords Variables
1.They are predefined 1.They are user-defined
2.They are also called as Reserved words 2.They are also used as a named memory
location
3.int 3.data-type variable;
char Eg:
float int a;
9
Boolean int a,b,c;
Global variables:
They are required to be accessed by all the functions defined after their declarations
Main ( ):
The documentation section, Inclusion section, Definition section are optional (not
compulsory)
But the main( ) function is compulsory and it has opening brace-{ and closing
brace-}
It contains two parts
i) Local variables declaration
ii) Statements
(ie) main( )
{
Local variables declaration;
Statements;
}
Some times it includes functions also
(ie) main( )
{
Local variables declarations;
Statements;
function1 ( );
function2 ( );
……………
……………
……………
functionn( );
}
function1( )
{
statements;
}
function2( )
{
statements;
}
Sample C program:
/* To find out the area and circumference of a circle */
#include<stdio.h>
#include<conio.h>
void main( )
{
int r;
float area,circumference;
clrscr( );
printf(“Enter radius \n”);
scanf(“%d”,&r);
area= PI*r*r;
circumference=2*PI*r;
printf(“Area=%f \n”,area);
10
printf(“circumference =%f \n”, circumference);
getch( );
}
Output:
Enter radius
2
Area = 12.56
Circumference=50.24
Execution of a C program:
There are four general steps involved in execution of a program
i)Creating the source program
ii)compiling the source program
iii)Linking the program with the function in the standard library
iv)Executing the program to get the expected outputs
a)Under MS-DOS Environment:
1.Creating the source program
edit demo.c
2.compiling the source program
tc demo.c [tc-turbo C compiler]
3.Linking the program with the functions in the standard library
link demo.obj
4.Executing the program to get the expected outputs
demo
Declaration of storage class:
Variables in C can have not only data types but also storage class that
provides information about their location & visibility.
The storage class decides the portion of the program within which the
variables are recognized. Consider the following example:
Ex:
int m;
main( )
{ int i;
float balance;
……….
Function1();
}
function 1()
{ int 1;
float sum();
………
…………….
}
The variable m which has been declared before the main is called global
variables. It can be used in all the functions in the program. It need not be declared in other
functions. A global variable is also known as an external variable.
The variable i, balance & sum are called local variables because they are
declared inside a function. Local variables are visible and meaningful only inside the function in
which they are declared. They are not known to other functions.
11
C provides a variety of storage class specifiers that can be used to declare
explicitly the scope & lifetime of variables.
12
The control string “%d” specifies that an integer value is to read from the terminal, we have
to have to type in the value in integer form.
Ex:
Main()
{ int no;
printf(“enter an integer number\n”);
scanf(“%d”,&number);
if (number < 100)
printf(“your no is smaller than 100\n\n”);
else
printf(“your no contains more than digits\n”);
}
output:
enter an integer number
65
your no is smaller than 100.
Enter an integer number
119
your no contains more than two digits.
13
# define PASS_MARK 50.
Symbolic names are sometimes called constant identifiers. Since the symbolic names are
constants, they do not appear in declarations. The following rules apply to #define statement
which define a symbolic constant.
1. Symbolic names have the same form as variable names.
2. No blank space between the pound sign “#” and the word define is permitted.
3. ‘#’ must be the first character in the line.
4. A blank space is required between the symbolic name & the constant.
5. # define statements must not end with a semicolon.
6. After definition, the symbolic name should not be assigned any other value within the
program by using an assignment statement.
7. Symbolic names are NOT declared for data types. Its data type depends on the type of
constant.
8. # define statements may appear anywhere in the program but before it is referenced in the
program.
OPERATORS & EXPRESSIONS
Operator:
An operator is a operators and expression computer to perform the specified manipulation
over some data
Expression:
The operators are used in combination with either variables (or) constant (or) with
combination of variables and constants and they are said to form expressions
Operand:
The variables (or) constants used with an operator are the ones which are subjected to the
operation specified by the operator and hence they are called operands for the operator
Types of operators
1) Assignment operator (=)
2) Arithmetic operator (+,-,*, /,%,unary +,unary -)
3) Relational operator (< <= > >= = = !=)
4) Logical operator (&&, ||,!)
5) Increment/Decrement (++,--)
6) Shorthand arithmetic assignment operator (+=,-=,*=,/=,%=)
7) Conditional operator (?:)
8) Bitwise operator (&,|, ^,<<,>>)
9) Comma operator (,)
1) Assignment operator(=):
It is used to assign the values of an expression to a variable
The statement used for the purpose is called the assignment statement
Syntax:
Variable = Expression;
Eg:
int a ;
a=10 ;
int a,b=10 ;
a=b;
int a=5,b=10,c;
c=a+b;
Program:
#include<stdio.h>
void main( )
14
{
int a=10,b=20,c;
c=a+b;
printf(“%d”,c);
}
Output: 30
2) Arithmetic operator(+,-,*,/,%,unary +,unary -):
operandsvariables and constants
operators+,-, *, /,%, unary +,unary –
unary +,unary - They are defined over a single operand
Syntax:
+operand
-operand
Unary + has no effect on the value of operand
Eg:
a=10
+a10
-a-10
Binary Arithmetic operators:
+-*/%
Syntax:
Operand1 operator operand2
Eg:
a+b
a-b
a*b
a/b
a%b
Arithmetic Meaning Example Output
operators
+ Addition 4+5 9
- Subtraction 4-5 -1
* Multiplication 4*5 20
/ Division 4/2 2
% Remainder 4/3 1
Proram:
#include<stdio.h>
void main( )
{
int a=10,b=7,s,d,m,g,mod;
s=a+b;
d=a-b;
m=a*b;
g=a/b;
mod=a%b;
printf(“%d%d%d%d%d”,s,d,m,g,mod);
}
Output:
17
3
70
15
1
3
EVALUATION OF EXPRESSIONS
Types of arithmetic expressions:
i) Integer mode expression
ii) Real mode expression (Floating point mode expression)
iii) Mixed mode expression
i) Integer mode expression:
If the operands of an expression are integers (char, unsigned char, int short, long,
unsigned int), the expression is called an integer mode expression
The resultant value of an integer mode expression is always an integer
Eg: 4+5=9
ii)Real mode expression:
If all the operands used in expression are real value (float, double) then it is called a real
mode expression
The resultant value of an real mode expression is always a float value
Eg:5.4+4.0=9.4
iii) Mixed mode expression:
If some operands are of integer type and some are of float type in an expression then it is called
a mixed mode expression
The resultant value of a mixed mode expression is always be of float type
Eg:5.4+4=9.4
PRECEDENCE OF ARITHMETIC OPERATORS
Operator precedence determines the order of evaluation of an arithmetic expression
and ensures that the expression produce only one value
Precedence Level Operators Associativity:
I Unary +,Unary - Right-Left
II */% Left-Right
III +- Left-Right
Associativity:
If an arithmetic expression has more than one operator, which is at the same level, then the
order of evaluation is determined by a rule called Associativity
Eg:
int a=4,b=12,c=6,d=7;
a+b/c*d
4+12/6*7
=4+2*7
=4+14
=18
Eg:
int a=4,b=5,c=6;
(a+b)*c
=(4+5)*6
=9*6
=54
Program:
16
#include<stdio.h>
void main( )
{
int a=4,b=6,c=3,e;
e=(a+b)*c;
printf(“%d”,e);
}
Output:
30
3) Relational operator(< <= > >= = = !=):
Syntax:
Operand1 operator operand2
The relational operators are used to construct relational expressions which are used to compare
two quantities
Operator relational operator
Operand1
operand2 Variables (or) constants
A relational expression is also called a conditional expression (or) a Boolean Expression
Relational Operators
< Less than 4<5 1
<= Less than (or) Equal to 4<=5 1
> Greater than 4>5 0
>= Greater than(or) Equal 4>=5 0
to
== Equal to 4= =5 0
!= Not Equal to 4!=5 1
Program:
#include<stdio.h>
void main( )
{
int a,b,c,d,e,f,g;
Printf(“Enter two numbers \n”);
Scanf(“%d%d”,&a,&b);
c=a+b;
g = a = = b;
e = a > b;
printf(“%d%d%d”,c,g,e);
}
Output:
1 0 0
Precedence Level Operators Associativity:
I < <= > >= Left-Right
II = = != Left-Right
4) Logical operator(&&,||,!):
The logical operators are used to construct compound conditional expression
Logical AND(&&)
logical OR( || )
logical NOT(!)
17
Logical AND(&&):
Syntax:
c1&& c2
c1 ,c2conditional expressions
C1 C2 c1&& c2
T T T
T F F
F T F
F F F
Logical OR( | |):
Syntax:
c1| | c2
c1 ,c2conditional expressions
C1 C2 c1|| c2
T T T
T F T
F T T
F F F
logical NOT(!):
C1 !c1
T F
F T
Program:
#include<stdio.h>
void main( )
{ int a=5,b=6,c=7,d,e,g;
d=(a<b) && (b>c);
e=(a<b) | | (b<c);
g=!(a<b);
printf(“%d \n”,d);
printf(“%d \n”,e);
printf(“%d \n”,g);
}Output:
0
1
0
Precedence Level Operators Associativity:
I ! Right-Left
II && Left-Right
III || Left-Right
5.Shorthand arithmetic assignment operators(+=,-=,*=,/=,%=)
The assignment statement can be written as a+=5 [a=a+5]
Syntax:
Operand1 operator operand2
Eg:
18
a=a+5 a+=5
a=a-5 a-=5
a=a*5 a*=5
a=a/5 a/=5
a=a%5 a%=5
19
a=4
a=4
20
c=(a>b)?a:b;
printf(“%d”,c);
}
Output:
20
8) Bitwise operators(&,|,^,~,<<,>>):
It performs manipulations over data at bit level
Bitwise OR(|):
Syntax:
Operand1 | Operand2
Operand1
Operand2 integer expressions
Bit1 Bit2 Bit1 & Bit2
0 0 0
0 1 1
1 0 1
1 1 1
Eg:
int a=4,b=5
Binary Equivalent of a=0100
Binary Equivalent of b=0101
21
Bitwise Exclusive OR(^):
Syntax:
Operand1 ^ Operand2
Operand1
Operand2 integer expressions
Eg:
int a=4,b=5
Binary Equivalent of a=0100
Binary Equivalent of b=0101
22
4 shift 0000 0000 0000 0000
23
Output:
char=1
unsigned char=1
int=2
short int=2
long int=4
unsigned int=2
float=4
double=8
long double=10
24
The operators of the same precedence are evaluated either from left to right or from ‘right
to left’, depending on the level. This is known as the associativity property of an
operation.
It is very important to note carefully, the order of precedence & associativity of operators.
Consider the following conditional statement:
If(x == 10 + 15 && y < 10)
The precedence rules say that the addition operator has a higher priority that the logical
operator (&&) and the relational operators (= = and <).
Therefore, the addition of 10 and 15 is executed first. This is equivalent to
If (x = = 25 && y < 10)
The next step is to determine whether X is equal to 25 and y is less than 10.
If we assume a value of 20 for x and 5 for y. then
X = = 25 is FALSE(0)
Y < 10 is TRUE(1)
Since the operator < enjoys a higher priority compared to = =, y < 10 is tested first and
then x = = 25is tested.
Accepting the required inputs from input devices and displaying the produced results on
output devices
are referred to as input/output operations
There are three types of I/O depending on the source devices for input and target devices for
output. They are
1.Console I/O
2.Disk I/O
3 .Port I/O
Console I/O uses keyboard as the standard input device and screen as the standard output
device
The aspects of Input-Output operations are as follows,
1. The Getchar( ) and putchar( ) functions
2. The scanf( ) and printf( ) functions
3. Formatting of outputs
i) Formatting of integers
ii) Formatting of floating point values
iii) Formatting of character
25
iv)Displaying data in tabular form
26
Scanf(“%d”,&n);
Eg:
int i;
char c;
float f;
scanf(“%d%f%c”,&i,&f,&c);
(or)
int i;char c;float f;
scanf(“%d”,&i);
scanf(“%f”,&f);
scanf(“%c”,&c);
printf( ):
The printf( ) is used to display data on the screen
Syntax:
Printf(“control string”,arg1,arg2,arg3,………..argn);
Control string consists of the following three items:
1. Format specifier similar to those discussed in the case of scanf( )
2. Some sequence of characters, which will be displayed on the screen as they are
3. Characters like \n,\t and \b etc
The characters are called escape sequence characters
Format specifier Meaning
%c A character
%d A decimal integer
%ld A long integer
%f A floating point value
%e A point value
%h A short integer
%lf A long float (double)
%s A string
27
%u An unsigned integer
%p A pointer
%o An octal number
%x An hexadecimal number
Escape sequence Meaning
\n New line
\t Horizontal tab
\v Vertical tab
\f Form feed
\b Back space
\a Alert character
\\ Backslash
\? Question mark
\’ Single quote
\” Double quote
3) Formatting of outputs:
It refers to displaying the outputs in more readable and comprehensible manner
i) Formatting of integers
ii) Formatting of float point values
iii) Formatting of characters
iv) Displaying data in tabular form
i) Formatting of integers:
type int (%d)
The modified control string would be %wd
where w-is an integer specifying the width
Eg:
1.printf(“%6d”,i); i=3456
3 4 5 6
2.printf(“%3d”,i); i=3456
3 4 5 6
3.printf(“%6d”,i); i=3456
3 4 5 6
4.printf(“%06d”,i); i=3456
0 0 3 4 5 6
Program:
#include<stdio.h>
#include<conio.h>
void main( )
{
int a=6789;
printf(“%d\n”,a);
printf(“%3d\n”,a);
printf(“%6d\n”,a);
28
printf(“%-6d\n”,a);
printf(“%06d\n”,a);
}
output:
6789
6789
6789
6789
006789
29
Enhancing the readability of output:
Computer outputs are used as information for analyzing certain relationships
between variables and for making decisions. Therefore the correctness and clarity of outputs are
of utmost importance. While the correctness depends on the solution procedure, the clarity
depends on the way the output is presented.
Following are some of the steps we can take to improve the clarity and hence the readability and
understandability of outputs.
Provide enough blank space between two numbers.
Introduce appropriate headings & variable names in the output.
Print special messages whenever peculiar condition occurs in the output.
Introduce blank lines between the important sections of the output.
For ex the statement
Printf(“a=%d\t b =%d”, a, b);
Will provide four blank spaces between the two fields.
UNIT-II
DECISION MAKING AND BRANCHING:
If the execution executes depending on the condition/selection it is called conditional
statement/selection
SequentialIf the set of operations are executed in sequential then it is called sequential
Types
1) Simple if statement
2) if-else statement
3) Nested if else statement
4) else-if ladder statement
5) Switch statement
6) Go to statement
1) simple if statement:
syntax:
if (test expression)
{
statements;
}
If the condition is true it will execute a set of statements
if- keyword
It is basically a two-way decision statement and is used in conjunction with an expression.
program:
#include<stdio.h>
#include<conio.h>
void main( )
{
int a=10,b=20;
if(a>b)
{
printf(“a is BIG”);
}
printf(“b is BIG”);
}
output:
30
b is BIG
2) If-else statement:
syntax:
if (test expression)
{
statements;
}
else
{
statements;
}
Explanations:
If test-exp is true, it will execute the statement1; otherwise it will execute the statements
program:
#include<stdio.h>
#include<conio.h>
void main( )
{
int a=30,b=20;
if(a>b)
{
printf(“a is BIG”);
}else
{
printf(“b is BIG”);
}
}
output:
a is BIG
3) nested if else statement:
syntax:
if (test expression)
if (test expression)
{
statements;
}
else
{
statements;
}
else
{
statements;
}
Explanations:
There will be more than one if else statements according to that the statements will be executed.
program:
#include<stdio.h>
#include<conio.h>
void main( )
{
31
int n;
pritnf(“enter a number”);
scanf(“%d”,&n);
if(n<=0)
if(n<0)
printf(“%d is negative”,n);
else
printf(“zero”);
else
printf(“%d is positive”,n);
}
output:
Enter a number
2
2 is positive
Enter a number
-7
-7 is negative
4) else-if ladder statement:
Syntax:
if (test expression)
{
statements;
}
else if (test expression)
{
statements;
}
else if (test expression)
{
statements;
}
……….
……….
else if (test expression)
{
statements;
}
else
{
statements;
}
Explanations:
The else if ladder indicates the number of else if (condition)
Program1:
#include<stdio.h>
void main( )
{
int a,b,c,l;
printf(“Enter three numbers”);
scanf(“%d%d%d”,&a,&b,&c);
32
if(a>b) &&(a>c)
l=a;
else if((b>a) &&(b>c))
l=b;
else
l=c;
printf(“%d%d%d”,a,b,c);
printf(“%d”,l);
}
output:
2
3
4
l=4
5) switch statement:
The switch statement tests the value of a given variable against a list of case values and
when a match is found, a block of statements associated with that case is executed.
The general form of the switch statement is shown below.
syntax:
switch (expression)
{
case 1:
statements-1;
break;
case 2:
statements-2;
break;
case 3:
statements-3;
break;
……………..
…………….
case n:
statements-n;
break;
default:
statements-1;
break;
}
The expression is an integer expression or character. Value-1, value-2 ….. are
constants or constant expressions and are known as case labels.
Each of these values should be unique within a switch statement.
Block-1, block-2… are statement lists and may contain zero or more statements.
There is no need to put braces around these blocks.
The case labels end with a colon (:).
When the switch is executed the value of the expression is successfully compared
against the values value1, value2…
33
If a case is found whose value matches with the value of the expression, then the
block of a statement that follows the case are executed.
The break statement at the end of each block signals the end of a particular case
and cause an exit from the switch statement, transferring the control to the
statement-x following the switch.
The default is an optional case.
When present, it will be executed if the value of the expression does not match
with any of the case values.
If not present, no action takes place if all matches fail and the control goes to the
statement-x.
Rules for switching statement:
The Switch expression must be an integral type.
Case labels must be constants or constant expressions.
Case labels must be unique. No two labels can have the same value.
Case labels must end with semicolon.
The break statement transfers the control out of the switch statement.
The break statement is optional. If present, it will be executed when the expression does
not find a matching case label.
The default may be placed anywhere but usually placed at the end.
It is permitted to nest switch statements.
program:
#include<stdio.h>
void main( )
{
int c;
printf(“Enter a colour”);
scanf(“%d”,&c);
switch(c)
{
case 1:
printf(“blue”);
break;
case 2:
printf(“green”);
break;
case 3:
printf(“red”);
break;
default:
printf(“invalid”);
break;}}
output:
2
green
3
blue
6) The goto statement:
Explain about GOTO statement.
The goto statement is an unconditional branching statement
It causes the control to be transferred from one part to another part of the same function
Syntax:
34
go to label;
where, labelis a valid c identifier and it marks the place where the control has to be transferred
to in a function
The statement to which the control is to be transferred is preceded by the label and a colon.
forward jumping;
goto label;
s1;
s2;
label1;
s4;
Backward jumping:
Label;
Statement;
………
………..
go to label;
example program:
for(i=1;i<10;i++)
{
statements;
for(j=0;j<10;j++)
for(k=0;k<10;k++)
{
if(condition)
goto abc;
}
}
abc: s1;
s2;
DECISION MAKING & LOOPING
Looping:
The repetition of execution of a block of statements as long as same condition is true is
called looping.
Looping is also called iteration. A program loop therefore consists of two segments:
1. body of the loop
2. control statement
The control statement tests certain conditions and then directs the repeated
execution of the statements contained in the body of the loop.
Depending on the position of the control statement in the loop, a control structure
may be classified either as the entry controlled loop or as the exit controlled loop.
In the entry controlled loop, the control conditions are tested, before the start of
the loop execution.
If the conditions are not satisfied, then the body of the loop will not be executed.
program:
#include,stdio.h>
void main( )
{
int i;
for(i=1;i<10;i++)
{
35
printf(“%d”,i);
}
}
output:
1
2
3
4
5
6
7
8
9
10
Looping variable:
The variable should be involved in all the three steps
(ie) (a) Initialization
(b) checking test-expression
(c) updation
C provides three looping structure .They are
1. The while loop
2. The do-while loop
3. The for loop
1.The while statement:
syntax:
while (test-expression)
{
statements;
}
whilekeyword
test-expcondition (it may be arithmetic ,relational (or) logical expression)
Entry controlled (or) pre tested:
The test expression is first evaluated before entering in to the body of the loop, the looping
construct is called entry-controlled (or) pre-tested looping construct
Since the test-expression is evaluated in the beginning itself, if it evaluates to false in the loop
is not entered at all
The statements would simply be skipped and the control is transferred to the first statement
following the looping construct
Example program:
#include<stdio.h>
void main( )
{
int i=1’
while(i<=5)
{
printf(“%d”,i);
}}
output:
1
36
2
3
4
5
2)The do-while loop:
syntax:
do
{
statements;
}
while (test-expression);
do, whilekeyword
Exit-controlled (or) post-tested:
Since the test-expression is evaluated at the end, the looping construct is called Exit-
controlled (or) post-tested looping construct.
The statements in the body of the loop are generated to be executed at least once.
program:
#include<stdio.h>
void main( )
{
int i=1;
do
{
printf(“%d”,i);
i++;
}
while(i<=5);
}
output:
1
2
3
4
5
3) The for statement:
syntax:
for(initialization; test-expression; updation)
{
statements;
}
Execution sequence effected by the FOR loop is as follows:
initialization statement is executed
test-expression is evaluated
If the test-expression evaluates to true, the statements in the body of the loop would gets
executed
control goes to the updation statement, the updation statement is evaluated ,which changes
the value of the loop variable
1. test-expression is again evaluated
2. control once again goes back to the updation statement, which updates the
looping variable
The sequence of statements is repeated as long as the test-expression evaluates to true.
37
Once the test-expression evaluates to false, the loop is exited and the control is transferred to
the first statement following the looping construct
38
break;
statements;
}
program:
#include<stdio.h>
void main( )
{
int ch;
scanf(“%d”,&ch);
switch(ch)
{
case 1:
printf(“one”);
break;
case 2:
printf(“two”);
break;
case 3:
printf(“three”);
break;
default:
printf(“Invalid”);
break;
}}
output:
1
one
2
two
3
three
10
invalid
2) continue:
It causes the control to be transferred back to the beginning of the loop
Syntax:
continue;
program:
#include<stdio.h>
void main( )
{
int i,n,sum;
for(i=1;i<=5;i++)
{
scanf(“%d”,&n);
if(n<0)
continue;
sum+=n;
}}
Difference between break and continue statements:
39
break statements: continue statements:
1)It can be used in switch statement 1)It can not be used in switch statement
2)It causes premature exit of the loop 2)It causes skipping of the statements
enclosing it following it in the body of the loop
3)The control is transferred to the statement 3)The control is transferred back to the loop
following the loop
4)The loop may not complete the intended 4)The loop completes the intended number
number of iterations of iterations
Nesting of loops:
Looping refers to repeated execution of a block of statements as long as some condition is
true
Enclosing one loop with in another loop is called nesting of loops
The enclosing loop is called outer-loop
The enclosed loop is called inner-loop
program:
#include<stdio.h>
void main( )
{
int i,j,p;
for(i=1;i<=5;i++)
{for(j=1;j<=5;j++)
{
p=i*j;
printf(“%4d”,p);
}
printf(“\n”);
}}
output:
12345
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
ARRAYS
One-dimensional arrays:
We need to handle large amounts of data, we need a powerful data type that would
facilitate efficient storing, accessing and manipulation of data items.
An array is a fixed size sequenced collection of elements of the same data type. Arrays in
C are similar to those found in other languages. It has only one subscript value or variable stored
in the 1-D arrays. It uses only one index value or variables.
Ex:
SALARY [10]
It represents the salary of 10th employee. While the complete set of values is referred to as an
array, individual values are called elements.
Three types of arrays:
One dimensional arrays
Two dimensional arrays
Multi dimensional arrays
40
Arrays & structure are referred to as structured data types because they can be used to represent
data values that have a structure of some sort.
In addition to arrays & structures, C supports creation & manipulation of the following data
structures:
Linked lists
Stacks
Queues
Trees
One dimensional array:
A list of items can be given one variable name using only one subscript and such a
variable is called a single subscripted variable or a one-dimensional array.
A=
We use this equation to calculate the average of n values of x. the subscripted variable xi
refers to the ith element of x.
In C, single subscripted variable xi can be expressed as x[1],x[2],x[3]…….x[n]. The
subscript can begin with number 0. The values to the array elements can be assigned as follows:
Number[0]=35;
Number[1=37;
Number[2]=40;
Number[3=23;
Number[4]=19;
Ex: a=number[0]+10;
41
The values in the list are separated by commas. For ex, the statement
int number[3]={0,0,0};
it will declare the variable number as an array of size 3 and will assign zero to each
element. The remaining elements will be set to zero automatically. For instance
float total[5]={0,0,15.76,-10);
It will initialize the first three elements to 0.0,15.75 and -10.0 and the remaining two
elements to zero.
Runtime initialization:
An array can be explicitly initialized at run time. This approach is usually applied for
initializing large arrays.
Ex;
For(i=0;i<100;i=i+1)
{ if(i<50)
sum[i]=0.0
else
sum[i]=1.0;
}….
……..
The first 50 elements of the array sum are initialized to zero while the remaining 50
elements are initialized to 1.0 at run time.
We can also use a read function such as scanf to initialize an array. For ex, the statement,
int x[3];
sacnf(“%d%d%d”, &x[0],&x[1],&x[2]);
It will initialize array elements with the values entered through the keyboard.
Two-dimensional arrays:
int tableofnumbers[50][50];
r- number of rows-[50]
c- number of columns-[50]
Multi-dimensional arrays can be defined as follows:
For further dimensions simply add more [ ]:
int table[50][50][40][30]......[50];
Elements can be accessed in the following ways:
anumber=tableofnumbers[2][3];
Multidimensional arrays:
The exact limit is determined by the compiler. The general form of a multi-dimensional
array is,
Type array-name[s1][s2][s3]………[sn]. Where s1 is the size of the ith dimension.
Ex:
int survey[3][5][12];
survey is a three dimensional array to contain 180 integer type elements.
Dynamic arrays:
An array created at compile time by specifying size in the source code has a fixed size
and cannot be modified at run time. The process of allocating memory at compile time is known
as static memory allocation and the arrays that receive static memory allocation are called static
arrays.
42
In C it is possible to allocate memory to arrays at run time. This feature is known as
dynamic memory allocation and the arrays created at run time are called dynamic arrays.
UNIT-III
Char string_name[size];
Ex:
i)Char str1[5]={‘a’,’s’,’d’,’f’,’\0’);
ii)char str2[5]={“abf”};
iii)char s[]={“abcd”};
iv)char s1[]={‘a’,’b’,’c’,’\0’};
Reading strings from terminal:
The familiar input function scanf can be used with %s format specification to read in a string of
characters.
Ex:
Char str[10];
Scanf(“%s”,str);
Reading line of text:
C supports a format specification known as the edit set conversion code %[..] that can be
used to read a line containing a variety of characters, including whitespaces.
Ex:
Char line [80];
Sacnf(“%[^\n]”,line);
Printf(“%s”,line);
43
It will read a line of input from the keyboard and display the same on the screen.
Writing strings to screen:
Using printf function:
printf(it displays a string using a string variable)
getchar( ) (it is a macro used to read a character through standard input)
putchar( ) (it is a macro used to write a character through standard input)
gets( )(it is used to accept a string up to a new line character in to a string variable)
puts( )(it is used to display a string up to a new line character through to a string variable)
%scontrol string used for string
ex:
Printf(“%s”,str)
getchar( ) and putchar( ):
getchar( ) it is a macro used to read a character through standard input
putchar( ) it is a macro used to write a character through standard input
syntax:
c=getchar( );
----------------
------------------
putchar( );
Program:
#include<stdio.h>
#include<conio.h>
void main( )
{
char text[80],c;
int i;
printf(“Enter a line of text \n”);
i=0;
c= getchar( );
while(c != ‘\n’)
{
text[i]=c;
c= getchar( );
i++;
}
text[i]=’\0’;
printf(“The line of text entered is \n”);
for(i=0;text[i] !=’\0’;i++)
putchar(text[i] );
getch( );
}
output:
Enter a line of text
I am going to Hyderabad and Tamilnadu
The line of text entered is
I am going to Hyderabad and Tamilnadu
gets( ) and puts( ):
44
gets( )it is used to accept a string up to a new line character in to a string variable
puts( )it is used to display a string up to a new line character through to a string variable
syntax:
char str[40];
gets(str);
---------
---------
puts(str);
Program:
#include<stdio.h>
#include<conio.h>
void main( )
{
char s1[]={“welcome”};
char s2[]={‘a’,’s’,’d’,’f’,’g’,’\0’};
char s3[]={“welcome”};
char s4[10];
clrscr( );
printf(“s1=%s\n”,s1);
printf(“s2=%s\n”,s2);
printf(“s3=%s\n”,s3);
printf(“Enter a string in to s4 \n”);
scanf(“%s”,s4);
printf(“s4=%s \n”,s4);
getch( );}
Output:
S1=welcome
S2=adfg
S3=welcome
Enter a string in to s4
Programming
S4=programming
String handling functions:
Finding the length of a string
Copying one string to another string
Concatenation of two strings
Comparing two strings
5 .Searching substring in a string
1.Finding the length of a string:(strlen())
It is used to define the number of characters in it excluding the null characters ‘\0’
prototypeint strlen(s);
eg:
char s[20]={“abcdgfg”};
int l;
l=strlen(s);
program:
#include<stdio.h>
#include<conio.h>
void main( )
{
45
char str[40];
int i.,len;
printf(“Enter a name”);
scanf(“%s”,str);
len=0;
for(i=0; str[i] !=’\0’;i++)
len++;
printf(“Length of %s=%d\n”,str,len);
len=strlen(str);
printf(“Length of %s using strlen( )=%d\n”,str,len);
getch( );
}
output:
Enter a name
Harsha
Length of Harsha =6
Length of Harsha using strlen( )=6
2.copying one string to another string:(strcpy())
It is used to copy one string to another string
strcpy(s1,s2);
program:
#include<stdio.h>
#include<conio.h>
void main( )
{
char str1[40]=”abcd”,str2[20],str3[20],str4[20];
int i;
printf(“string in str1=%s \n”,str1);
for(i=0; str1[i] !=’\0’;i++)
str2[i]= str1[i];
str2[i]=’\0’;
printf(“string in str2=%s \n”,str2);
strcpy(str3,str1);
printf(“string in str3=%s \n”,str3);
strcpy(str4,”mno”);
printf(“string in str4=%s \n”,str4);
getch( );}
output:
string in str1=abcd
string in str2=abcd
string in str3=abcd
string in str4=mno
3.Concatenation of two strings:(strcat())
The process of appending(adding) one string to the end of another string is called
Concatenation
prototype-strcat(s1,s2);
Eg:
Char s1[10]={“abc”},s2[10]={“xyz”};
Strcat(s1,s2);
program:
#include<stdio.h>
46
#include<conio.h>
void main( )
{
char str1[40]={”abc”},str2[20]={“def”},str3[20]={“ghi”};
int i,j;
printf(“str1=%s str2=%s \n”,str1,str2);
for(i=0; str1[i] !=’\0’;i++)
for(j=0; str1[j] !=’\0’;j++)
str1[i+j]= str2[j];
str2[i+j]=’\0’;
printf(“After concatenation str1=%s \n”,str1);
strcat(str1,str2);
printf(“str1=%s \n”,str1);
strcat(str1,”jkl”);
printf(“str1=%s \n”,str1);
getch( );
}
output:
str1= abc str2=def
After concatenation
str1= abcdef
str1= abcdefghi
str1= abcdefghijkl
4.comparing two strings:(strcmp())
It is used to compare two strings
Relational operators > and < are not used
prototype-int strcmp(s1,s2);
both are
equal0
not equal1(or)-1
Eg:
Char s1[20]={“abc”},s2[20]={“aac”};
Int i;
I=strcmp(s1,s2);
Other string functions:
Strncpy:
It copies only the left most n characters of the source string to the target string variable.
This is a three parameter function and is invoked as follows:
Strncpy(s1,s2,5);
Strncmp:
Strncmp(s1,s2,n);
This compares the left most n characters of s1 to s2 and returns.
i) 0 if they are equal;
ii) negative number, is s1 substring is less than s2
iii) positive number, otherwise.
Strncat:
Strncat(s1,s2,n);
This call will concatenate the left most n characters of s2 to the end of s1.
Strstr:
This is a two parameter function that can be used to locate a sub string in a string.
47
Ex:
Strstr(s1,s2)
This function searches the string s1 to see whether the string s2 is contained in s1. If yes,
the function returns the position of the first occurrence of the sub string. Otherwise, it returns a
NULL pointer.
Table of strings:
A list of names can be treated as a table of strings and a two dimensional character array
can be used to store the entire list. For ex, a character array student [30][15] may be used to
store a list of 30 names, each of length not more than 15 characters.
Ex:
Char city[] []
{
“Bombay”
“delhi”
“madras”
“trichy”
}
To access the name of the ith city in the list, we write
city[i-1].
Other features of strings:
Manipulating strings using pointers
Using string as function parameters
Declaring and defining strings as member of structures
USER-DEFINED FUNCTIONS
Introduction:
The subprogram in C is called a function. A function is defined to be a self-contained
program which is written for the purpose of accomplishing some task.
Because of the flexibility provided by C in designing functions and the fact that each
logical unit of work is accomplished by means of a function, C is referred to as a language of
functions
Classification:
1.Built-in functions
2.User-defined functions
Built-in functions:
Built-in functions are those which already made available as part of C library
scanf( ),printf( ),strlen( ),strcpy( )
Need for User-defined functions:
It is one which is written by a user to solve a problem
main( )
Advantages:
1. Minimization if memory space usage
2. Improvisation of overall organization of a program
3. Facilitation of team work
4. Simplification of software engineering tasks like testing and debugging
A multi-function program:
A function is a self contained block of code that performs a particular task. Once a
function has been designed and packed, it can be treated as a ‘black box’ that takes some data
from the main program and returns a value.
Ex:
Void printline(void);
48
Main()
{
printline();
printf(“this is a multi function program”);
printline();
}
void printline(void)
{
int I;
for(i=1;i<40;i++)
printf(“-“);
printf(“\n”);
}
Elements of user defined function:
Similarities between functions and variables in C:
Both function names and variables names are considered identifiers and therefore they
must adhere to the rules for identifiers.
Like variables, functions have types associated with them.
Like variables, function names and their types must be declared and defined before they
are used in a program.
Elements that related to functions:
Function definition
Function call
Function declaration
The function definition is an independent program module that is specially written to
implement the requirements of the function.
In order to use this function we need to invoke it at a required place in the program. This is
known as function call.
The calling
Definition of function:
A function definition, also known as function implementation shall include the
following elements:
Function name
Function type
List of parameters
Local variable declarations
Function statements
A return statement
All the six elements are grouped into two parts, namely,
Function header
Function body
Syntax:
return_type function_name function header
{
local variables;
statements; function body
return(expression);
}
function header:
49
The first line consisting of return_type, function name and arguments declaration enclosed
with in a pair of parenthesis is usually referred to as the function header
function body:
The function header is followed by the local variables declaration part and a set of executable
statements of the function enclosed with in a pair of opening brace and closing brace
The local variables declaration part and the set of statements enclosed with in the braces in
referred to as the function body
function header
+ function definition
function body
Return values and their types:
A function may or may not send back any value to the calling function. If it does, it is
done through the return statement. The return statement can take one of the following forms:
Return;
Or
Return (expression);
When a return is encountered, the control is immediately passed back to the calling
function. An example of the use of a simple return is as follows:
if (error)
Return;
Function calls:
A function can be called by simply using the function name followed by a list od actual
parameters, if any, enclosed in parentheses.
Ex:
Main()
{
int y;
y=mul(10,5);
printf(“%d\n”,y);
}
when a compiler encounters a function call, the control is transferred to the function
mul(). This function is then executed line by line as described and a value is returned when a
return statement is encountered.
Function declaration:
It consists of four parts:
Function type
Function name
Parameter list
Terminating semicolon
They are coded in the following format:
Function-type function-name(parameter list);
Ex:
int mul(int m,int n);
Points to note:
The parameter list must be separated by commas.
The parameter names do not need to be the same in the prototype declaration and the
function definition.
The types must match the types of parameters in the function definition, in number and
order.
Use of parameter names in the declaration is optional.
If the function has no formal parameters, the list is written as void.
50
The return type is optional, when the function returns int type data.
The retype must be void if no value is returned.
When the declared types do not match with the types in the function definition, compiler
will produce an error.
calling function:
A function which invokes another function is called calling function
main( )
Called function:
A function which is invoked is termed called function
scanf( ),printf( )
Category of function:
Types:
1.Functions with no arguments and no return values
2.Functions with arguments and no return values
3.Functions with arguments and return values
1.Functions with no arguments and no return values
Syntax:
Void f( )
{
variables;
statements;
}
Explanations :
f( ) is a function which does not require arguments to be passed and does not require any
value to its calling program
Program:
#include<stdio.h>
#include<conio.h>
void sum( )
{
int a,b,c,l;
printf(“Enter three numbers \n”);
scanf(“%d%d%d”,&a,&b,&c);
l=a;
if(b>1)
l=b;
if(c>1)
l=c;
pritnf(“largest=%d \n”,l);
}
void main( )
{
clrscr( );
sum( );
getch( );
}
output:
Enter three numbers
3
4
51
5
largest=5
Points to observe:
1.A called function can be defined either before (or) after its calling function
2.If called function does not return any value, it has to be used as an independent statement
3.A function cannot be defined with in the body of another function as it is treated as an external
variable
4.If a function f1( ) invokes another function f2( ) then f2( ) is said to have been called by f1( )
2.Functions with arguments and no return values:
Syntax:
Void f( arguments)
{
variables;
statements;
}
Explanations :
f( ) is a function which requires arguments to be passed and does not require any value to its
calling program
Program:
#include<stdio.h>
#include<conio.h>
void om(int a,int b,int c)
{
int l;
l=a;
if(b>1)
l=b;
if(c>1)
l=c;
pritnf(“largest=%d \n”,l);
}
void main( )
{
int a,b,c,l;
int x,y,z;
clrscr( );
printf(“Enter three numbers \n”);
scanf(“%d%d%d”,&a,&b,&c);
om(a,b,c);
printf(“Enter values of x,y,z \n”);
scanf(“%d%d%d”,&x,&y,&z);
om(x,y,z );
getch( );
}
output:
Enter three numbers
3
4
5
largest=5
Enter values of x,y,z
52
6
3
2
largest=6
Points to observe:
1.The names of the formal arguments and the names of the actual arguments can be same (or)
different
2.The number of formal arguments and the number of actual arguments should be same
3.Types of the actual arguments should be compatible with those of the formal arguments
4.We can even pass constants as actual arguments
3.Functions with arguments and return values:
Syntax:
data_type f( arguments)
{
variables;
statements;
return(expression)
}
Explanations :
f( ) is a function which requires arguments to be passed and also returns a value to its calling
program
Program:
#include<stdio.h>
#include<conio.h>
int large(int a,int b,int c)
{
int l;
l=a;
if(b>1)
l=b;
if(c>1)
l=c;
return(l);
}
void main( )
{
int a,b,c,l;
int x,y,z;
clrscr( );
printf(“Enter three numbers \n”);
scanf(“%d%d%d”,&a,&b,&c);
l=large(a,b,c);
printf(“largest=%d \n”,l);
printf(“Enter values of x,y,z \n”);
scanf(“%d%d%d”,&x,&y,&z);
getch( );
}
output:
Enter three numbers
53
3
4
5
largest=5
Enter values of x,y,z
4
5
6
largest=6
Points to observe:
1. A function cannot return more than one value. By default, it returns a value of int type
2. If a function returns a value then the function call would be like a variable
54
2.The return statement causes the exit of the 2.The exit( ) enclosed with in a function,on its
function in which it is enclosed and transfers execution,terminates the entire program and
the control to the calling function the control is transferred to the underlying
operating system itself
3.It returns the integer values alone 3.It includes stdlib.h (or) process.h header files
Nesting of functions:
C permits nesting of functions freely. This is nothing but a function within a function.
Example:
float ratio(int x, int y, int z);
int difference(int x, int y);
main()
{
int a,b,c;
scanf(“%d %d %d”, &a,&b,&c);
printf(“F”,ratio(a,b,c);
}
float ratio(int x, int y, int z)
{
if(difference(y,z))
return(x/(y-z));
else
return(0.0);
}
int difference(int p,int q)
{
if(p != q)
return(1);
else
return(0);
}
In the above program we have three functions:
main ()
ratio()
difference()
Recursion:
Define Recursion
Definition:
The phenomenon of a function calling itself is called recursion. The function involved in
the process is referred to as a recursive function
Finding the factorial of a number 4
Solution:
4!=4*3!
=4*3*2!
=4*3*2*1!
=4*3*2*1
=24
In general,factorial of a number n denoted by n! can be written as
n!=n*(n-1)!
=n*(n-1)*(n-2)!
……….
55
=n*(n-1)*(n-2) …………*1!
=n*(n-1)*(n-2)………….*1
We know that factorial of 1 is 1.Thus when n takes 1,we do not call the function fact( ) but we
simply return 1.This happens to be a terminating condition.
Passing arrays to functions:
1) One dimensional arrays as Arguments to functions
2) Passing Two dimensional arrays to functions
1)One dimensional arrays as Arguments to functions:
Syntax:
Data-type function-name(data-type array-name[],int size)
{
local variables;
statements;
}
Eg:
Void display(int a[],int n)
{
local variables;
statements;
}
Program:
#include<stdio.h>
#include<conio.h>
int display(int[],int);
void main( )
{
int i,n,a[20];
printf(“Enter the elements”);
scanf(“%d”,&n);
printf(“Enter %d values”,n);
for(i=1;i<=n;i++)
scanf(“%d”,&a[i]);
printf(“the elements are\n”);
display(a,n);
}
void display(int a[],int n)
{
int i;
for(i=1;i<=n;i++)
printf(“%d”,a[i]);
}
Output:
Enter the elements
4
Enter 4 values
4231
the elements are
1234
2)Passing Two dimensional arrays to functions:
The function must be called by passing only the array name.
56
In the function definition, we must indicate that the array has two dimensions by
including two sets of brackets.
The size of the second dimension must be specified.
The prototype declaration should be similar to the function header.
Syntax:
Data-type function-name(data-type array-name[][],int rowsize,int columnsize)
{
local variables;
statements;
}
Eg:
Void display(int a[][10],int m,int n)
{
local variables;
statements;
}
Program:
#include<stdio.h>
#include<conio.h>
void display(int[][10],int,int);
void main( )
{
int i,j,,m,n,a[10][10];
printf(“Enter the size of the elements”);
scanf(“%d%d”,&m,&n);
printf(“Enter the elements”);
for(i=1;i<=m;i++)
for(j=1,j<=n,j++)
scanf(“%d”,&a[i][j]);
display(a,m,n);
}
void display(int a[][10],int m,int n)
{
int i,j;
for(i=1;i<=m;i++)
{
for(j=1,j<=n;j++)
{
printf(“The matrix %d\n”,a[i][j]);
}
}
}
output:
Enter the size of the elements
23
Enter the elements
123456
The matrix
123
456
57
Passing strings to functions:
The strings are treated as character array in C and therefore the rules for passing strings to
functions are very similar to those for passing arrays to functions.
Basic rules:
The string to be passed must be declared as a formal argument of the function when it is
defined.
Void display(char item-name[])
{……………}
The function prototype must show that the argument is string. For the above function
definition, the prototype can be written as
Void display(char str[]);
A call to the function must have a string array name without subscripts as its actual
argument.
Ex:
Display(names);
Where names is a prototype declared string array in the calling function.
UNIT-IV
INTRODUCTION:
C supports a constructed data type known as structures, a mechanism for packing data of
different types. A structure is a convenient tool for handling a group of logically related data
items.
The concept of a structure is analogous to that of a ‘record’ in many other languages.
More examples of such structure are:
TIME: seconds, minutes, hours
DATE: day, month, year
BOOK: author, title, price, year.
DEFINING A STRUCTURE:
A structure can be defined to be a group of logically related data items, which may be of
different types,stored in contiguous memory locations, sharing a common name, but
distinguished by its members
Structure is a user-defined keyword. Using structure we can allocate memory.
Syntax:
Struct tag-name
{
data-type member1;
data-type member2;
……………………
……………………
data-type membern;
};
structkeyword
tag-nameuser defined name
58
data-typeValid data type
member1, member2,………….. membernvariables
DECLARING STRUCTURE VARIABLES:
After defining a structure format we can declare variables of that type. A structure
variable declaration is similar to the declaration of variable of any other data types.
Syntax:
Struct tag-name variable-name;
Eg:
Struct emp
{
int empno;
char name[20];
float salary;
};
Member operator( ): .
Dot is used to access each individual member and it is called member operator. The dot operator
expects the structure variable name to the left of it and member name to the right of it. The link
between a member and a variable is established using the “member operator”.
Eg:
Struct emp
{
int empno;
char name[20];
float salary;
};
struct emp e;
e.empno e.name e.salary
59
{
int empno;
char name[20];
float salary;
};
struct emp e;
scanf(“%d%s%f”,&e.empno,&e.ename,&e.salary);
printf(“%d%s%f”,e.empno,e.ename,e.salary);
STRUCTURE INITIALIZATION:
Like any other data type, a structure variable can be initialized at compile time.
main()
{
struct
{
int weight;
float height;
}
Student={30,190};
……………..
…………….
}
This assigns the value 30 to student.weight and 190 to student.height. There is one to
one correspondence between the members and their initializing values.
C does not support the initialization of individual structure members within the
template. The initialization must be done only in the declaration of the actual variables.
The compile time initialization of structure variable must have the following
elements:
The keyword struct
The structuring tag name
The name of the variable to be declared
The assignment operator =.
A set of values for the members of the structure variable, separated by commas and
enclosed in braces.
A terminating semicolon.
Operations on structures:
1.Accessing the individual members of a structure variable with the help of member
operator(Dot operator)
struct emp e;
e.empno=10;
2. Assigning one structure variable to another of the same type
struct emp e1={108,”OM”,50000},e2;
60
e2=e1;
e1 has been assigned to e2
3. Retrieving the size of a structure variable using sizeof() operator
struct emp e;
int s;
s=sizeof(e);
4. Retrieving the address of a structure variable using &(address of) operator
struct emp e;
&e gives the address of e
5. Passing and returning a structure variable value to and from a function
6. Checking whether two structure variables of same type are equal using = =.
7. Checking whether two structure variables of same type are not equal using ! =.
PROGRAM:
#include<stdio.h>
#include<conio.h>
struct emp
{
int empno;
char name[20];
float salary;
};
void main( )
{
struct emp e1,e2;
int size;
printf(“Enter empno,name and salary \n”);
scanf(“%d%s%f”,&e.empno,e.ename,&e.salary);
size=sizeof(e1);
printf(“\n No of bytes required for e1=%d \n\n”,size);
e2=e1;
printf(“after assigning e1 to e2 “);
printf(“e2.empno=%d\n”,e2.empno);
printf(“e2.name=%s\n”,e2.name);
printf(“e2.salary=%8.2f\n”,e2.salary);
printf(“”address of e1=%u\n”,&e1);
getch();
}
OUTPUT:
Enter empno,name and salary
108 om 50000
No of bytes required for e1=26
after assigning e1 to e2
e2.empno=108
e2.empno=om
e2.empno=50000
address of e1=500
ARRAYS OF STRUCTURES:
Explain about structures with arrays.
In analyzing the marks obtained by a class of students, we may use a template to describe
student name and marks obtained in various subjects and then declare all the students as structure
61
variables. In such cases, we may declare an array of structures, each element of the array
representing a structure variable.
Syntax:
Struct emp e[10];
Explanations:
If the structure variable constrains the array values then it is called as array of
structures
It will have from e[0],e[1],e[2],…………………..e[9] are variables of struct emp
type
Program:
#include<stdio.h>
#include<conio.h>
struct emp
{
int empno;
char name[20];
float salary;
};
void main( )
{
struct emp e[10];
int I,n;
float f,*fp;
fp=&f;
printf(“Enter no of employees [1-10] \n”);
scanf(“%d”,&n);
printf(“Enter %d employees details \n”,n);
for(i=0;i<n;i++)
scanf(“%d%s%f”,&e[i].empno,e[i].name,&e[i].salary);
printf(“Employees details\n”);
for(i=0;i<n;i++)
printf(“%d%s%f”,e[i].empno,e[i].name,e[i].salary);
}
Output:
Enter no of employees [1-10]:
2
Employees details
108 om 50000
109 sakthi 50000
62
{
int number;
float sub[3];
student[2];
}student[2];
Here the member subject contains three elements, subject[0],subject[1] and subject[2].
Program:
#include<stdio.h>
#include<conio.h>
struct emp
{
int regno;
char name[20];
int marks[5];
int total;
float per;
};
void main( )
{
struct stud s[10];
int i,n,j;
printf(“Enter no of students \n”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
printf(“Enter reg_no and name of student -%d \n”,n);
scanf(“%d%s”,&s[i].regno,e[i].name);
printf(“Enter marks in five subjects of %s \n”,s[i].name);
for(j=0;j<5;i++)
scanf(“%d”,&s[i].marks[j]);
}
for(i=0;i<n;i++)
{
s[i].total=0;
for(j=0;j<5;i++)
s[i].total +=s[i].marks[j];
s[i].per=(float)s[i].total/5;
}
printf(“\n Reg-no name percentage \n”);
for(i=0;i<n;i++)
printf(“%d%s%f”,s[i].regno,s[i].name,s[i].per);
}
output:
Enter no of students
2
Enter reg_no and name of student 1
108 Om
Enter marks in five subjects of Om
90 91 97 95 99
Enter reg_no and name of student 1
109 Sakthi
63
Enter marks in five subjects of Sakthi
91 91 97 95 99
Output:
Enter empno,name,doj and salary
64
108 om 02 04 1999 50000
Empno =108
Name =om
Doj =02 04 1999
Salary =50000
STRUCTURES AND FUNCTIONS:
Three approaches to passing structure members to functions
1. Passing members of a structure individually
2. Passing entire structure at once
3. Passing address of a structure variable
1. Passing members of a structure individually:
Limitations (Disadvantages):
(a)If the number of members of the structure to be passed is more, this method turns out to be
prohibitive
(b)If some changes are made to the members of the structure by the called function, the calling
function can not be made known about the changes (Only one value can be returned by a
function)
void display(int,char[],float);
void main( )
{
struct student s;
printf(“Enter regno name and percent\n”);
scanf(“%d%s%f”,&s.regno,s.name,&s.percent);
display(s.regno,s.name,s.percent);
}
void display(int regno,char name[],float per)
{
printf(“%d%s%f”,regno,name,percent);
}
Output:
Enter regno name and percent
108
Om
99
108 Om 99
65
2.Passing entire structure at once:
The entire structure is passed in to the function
Program:
#include<stdio.h>
#include<conio.h>
struct student
{
int regno;
char name[20];
float per;
};
void display(struct student);
void main( )
{
struct student s;
printf(“Enter regno name and percent\n”);
scanf(“%d%s%f”,&s.regno,s.name,&s.percent);
display(s.regno,s.name,s.percent);
}
108 Om 99
66
display(&s);
} void display(struct student *sp)
{ printf(“%d%s%f”,spregno,spname,sppercent);
}
Output:
Enter regno name and percent
108
Om
99
108 Om 99
UNIONS:
The concept of union is derived from the concept of structure. The common thing
between structure and union are they identify a group of data items of different data types of
common name.
In structure, the number of allocations would be equal to the number of the case of structure
In union, a single location can accommodate values of different type at different types gets
allocated
Syntax:
union tag-name
{
data-type member1;
data-type member2;
……………………
……………………
data-type membern;
};
structkeyword
tag-nameuser defined name
data-typeValid data type
member1, member2,………….. membernvariables
Syntax:
Union tag-name variable-name;
Eg:
Union temp
{
int i;
float f;
char c;
};
union temp t;
Program:
#include<stdio.h>
#include<conio.h>
struct temp
67
{
int i;
char c;
float f;
};
union temp1
{
int i;
char c;
float f;
};
void main( )
{
struct temp st;
union temp1 ut;
st.i=10;
st.f=18.99;
st.c=’s’;
printf(“st.i=%d \n”,st.i);
printf(“st.f=%f \n”,st.f);
printf(“st.c=%c \n”,st.c);
ut.i=10;
printf(“ut.i=%d \n”,ut.i);
ut.f=18.99;
printf(“ut.f=%f \n”,ut.f);
ut.c=’s’;
printf(“ut.c=%c \n”,ut.c);
}
Output:
size of struct temp=7
size of union temp=4
st.i=10
st.f=18.99
st.c=s
ut.i=10
ut.f=0
ut.c=s
68
SIZE OF STRUCTURES:
The actual size of these variables in terms of bytes may change from machine to machine.
We may use the unary operator sizeof to tell us the size of a structure. The expression
sizeof(struct x)
will evaluate the number of bytes required to hold all the members of the structure x. if y
is a simple structure variable of type struct x, then the expression
sizeof(y) would also give the same answer.
BIT FIELDS:
C permits us to use small bit fields to hold data items and thereby to pack several data
items in a word of memory. Bit fields allow direct manipulation of string of a string of
preselected bits as if it is represented an integral quantity.
Syntax:
Struct tag-name
{
data-type m1 : size;
data-type m2 : size;
……………………
……………………
data-type mn : size;
};
Points:
The first field always starts with the first bit of the word.
A bit field cannot overlap integer boundaries.
There can be unnamed fields declared with size, example:
o Unsigned : bit-length
There can be unused bits in a word.
We cannot take the address of a bit field variable
Bit fields cannot be arrayed.
Bit fields should be assigned values that are within the range of their size.
Program:
#include<stdio.h>
#include<conio.h>
struct temp
{
int a : 3;
int b : 3;
unsigned int c : 3;
};
void main( )
{
struct temp t;
t.a=3;
t.b=3;
t.c=3;
printf(“t.a=%d \n”,t.a);
printf(“t.b=%d \n”,t.b);
printf(“t.c=%d \n”,t.c);
69
printf(“size =%d \n”,sizeof(struct temp));
}
Output:
t.a=3
t.b=2
t.c=7
size=2
POINTERS
INTRODUCTION:
A pointer is a derived data type in C. it is built from one of the fundamental data types
available in C.
Pointers are used frequently in C, as they offer a number of benefits to the programmers.
They include:
Pointers are more efficient in handling arrays and data tables.
Pointers can be used to return multiple values from a function via function arguments.
Pointers permit references to functions and thereby facilitating passing of functions as
arguments to other functions.
The use of pointer arrays to character strings results in saving of data storage space in
memory.
Pointers allow C to support dynamic memory management.
Pointer provide an efficient tool for manipulating dynamic data structures such as structures,
linked lists, queues, stacks and trees.
It reduces length and complexity of programs.
They increase the execution speed and thus reduce the program execution time.
It used to get the address of a variable
UNDERSTANDING POINTERS:
The computer’s memory is a sequential collection of storages cells as shown below. Each
cell commonly known as a byte, has a number called address associated with it.
Typically, the addresses are numbered consecutively, starting from zero. The last address
depends on the memory size. A computer system having 64 K memory will have its last address
as 65,535.
70
Memory organization
A variable which can store the address of another variable is called a pointer variable. A
pointer variable is, therefore, nothing but a variable that contains an address, which is a location
of another variable in memory.
CHAIN OF POINTERS:
It is possible to make a pointer to point to another pointer, thus creating a chain of
pointers as shown below.
P2 P1 variable
Address 2 Address 1 Value
Here the pointer variable P2 contains the address of the pointer variable P1, which points
to the location that contains the desired value. This is known as multiple directions.
A variable that is a pointer to a pointer must be declared using additional indirection
operator symbols in front of the name. ex: int **p2;
POINTER EXPRESSIONS:
Example:
71
Y = *p1 * *p2;
Sum = sum + *p1;
Invalid:
Z = 5* - *p2 /*p1;
The symbol /* is considered as the beginning of a comment and therefore the
statement fails.
Operations over pointers are as follows:
1. Adding an integer value to a pointer
2. Subtracting an integer value from a pointer
3 .Comparing two pointers if they point the elements of the same array
4. Subtracting one pointer from another pointer provided both are of same type
5. Assigning one pointer to another pointer provided both are of same type
*a= *(a+0)=a[0]
*(a+1)=a[1]
*(a+2)=a[2]
*(a+3)=a[3]
*(a+4)=a[4]
……………
……………
*(a+i)=a[i]
In general,(a+i) gives the address of ith element in the array a and *(a+i) is the element stored
in the ith location of the array
Program:
#include<stdio.h>
#include<conio.h>
void main( )
{ int a[10],n,i;
printf(“Enter no of elements \n”);
for(i=0;i<n;i++)
scanf(“%d”,a+i);
printf(“The list of element \n”);
for(i=0;i<n;i++)
printf(“%d”,*(a+i));
72
}
Output:
Enter no of elements
2
Enter 2 elements
10
20
The list of element
10
20
2) Pointers and two-dimensional arrays:
It includes two subscript (or) two index value
int a[10][10];
Program:
#include<stdio.h>
#include<conio.h>
void main( )
{
int a[10][10],n,m,i,j;
printf(“Enter the elements \n”);
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf(“%d”,*(a+i)+j);
printf(“Matrix a \n”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf(“%d”,*(*(a+i)+j));
printf(“\n”);
}}
Output:
Enter the elements
1 2 3 4
Matrix a
1 2
3 4
POINTERS AND CHARACTER STRINGS:
The string is a sequence of characters terminated by a null character ‘\0’
The null character marks the end of the string
Eg:
Char s[20];
Char *cp;
Cp=s;
Program:
#include<stdio.h>
#include<conio.h>
void main( )
{
char str[20],*cp;
printf(“Enter a string \n”);
scanf(“%s”,str);
73
cp=str;
printf(“string in str=%s \n”,cp);
cp=”abcd”;
printf(“%s \n”,cp);
}
Output:
Enter a string
Program
string in str= Program
abcd
Comparison between an ARRAY OF CHAR and a POINTER TO CHAR:
ARRAY OF POINTERS:
We can use an array of pointers to char type to represent the strings
char *ptr[10];
ptr[0], ptr[1], ptr[2],…………………. ptr[9] are all pointers to char type
Program:
#include<stdio.h>
#include<conio.h>
void main( )
{
char *names[3]={“om”,”om1”,”om2”};
int i;
printf(“The list of three names \n”);
for(i=0;i<3;i++)
printf(“%s \n”,names[i]);
}
Output:
The list of three names
Om
Om1
Om2
74
Function-name (type *ptr);
a) Call by value
b) Call by reference
a)Call by value:
The mechanism of calling a function by passing values is called call by value
b)Call by reference:
The mechanism of calling a function by passing pointers is called call by value
Program 1:
#include<stdio.h>
#include<conio.h>
void inc(int);
void incr(int*);
void main()
{
int a=10,b=10;
printf(“call by value”);
printf(“a=%d”,a);
inc(a);
printf(“After calling inc()”);
printf(“a=%d”,a);
printf(“call by reference”);
printf(“b=%d”,b);
incr(&b);
printf(“After calling incr()”);
printf(“b=%d”,b);
}
void inc(int x)
{
x++;
printf(“x=%d”,x);
}
void incr(int *p)
{
(*p)++;
}
output:
call by value
a=10
x=11
After calling inc()
a=10
call by reference
b=10
After calling incr
b=11
Program 2:
#include<stdio.h>
#include<conio.h>
75
void swap(int,int);
void swap1(int*,int*);
void main()
{
int a=5,b=6,c=7,d=8;
printf(“call by value”);
printf(“a=%d b=%d”,a,b);
swap(a,b);
printf(“After calling swap()”);
printf(“a=%d b=%d”,a,b);
printf(“call by reference”);
printf(“c=%d d=%d”,c,d);
swap1(&c,&d);
printf(“After calling swap1()”);
printf(“c=%d d=%d”,c,d);
}
void swap(int x, int y)
{
int t;
t=x;
x=y;
y=t;
printf(“x=%d y=%d”,x,y);
}
void swap1(int *p, int *q)
{
int t;
t=*p;
*p=*q;
*q=t;
output:
call by value
a=5 b=6
x=6 y=5
call by reference
c=7 d=8
After calling swap1
c=8 d=7
Points to note:
The function parameters are declared as pointers.
The dereferenced pointers are used in the function body.
76
When the function is called, the addresses are passed as actual arguments.
void *sum(int,int);
void main()
{
int a,b,*s;
printf(“Enter two numbers”);
scanf(“%d%d”,a,&b);
printf(“a=%d b=%d”a,b);
s=sum(a,b);
printf(“sum=%d”,*s);
}
int *sum(int a,int b)
{
int s;
s=a+b;
return(&s);
}
Output:
Enter two numbers
45
a=4 b=5 s=9
POINTERS TO FUNCTIONS:
A pointer invokes a function before which the pointer has to be declared appropriately
and assigned the address of the function
Syntax:
Data-type (*variable-name)(argument-types);
Eg:
int (*fnp)(int,int);
77
Program:
#include<stdio.h>
#include<conio.h>
int sum(int,int);
void main()
{
int a,b,s,(*fnp)(int,int);
printf(“Enter two numbers”);
scanf(“%d%d”,a,&b);
printf(“a=%d b=%d”a,b);
fnp=sum;
s=(*fnp)(a,b);
printf(“sum=%d”,*s);
}
int sum(int a,int b)
{
int s;
s=a+b;
return s;
}
Output:
Enter two numbers
4 6
a=4 b=6 s=10
POINTERS AND STRUCTURES:
i) Pointers to structures
ii) Structures containing pointers
i) Pointers to structures:
We use & operator to retrieve the address of a structure variable
Eg:
Struct temp
{
int i;
float f;
char c;
} struct temp t,*tp;
The members of t are accessed through tp with the help of operator known as structure-
pointer operator
Program:
#include<stdio.h>
Struct temp
{
int i;
float f;
char c;
};
78
void main( )
{
Struct temp t={123,18.99,’g’},*tp;
tp=&t;
printf(“t.i=%d \n”,tpi);
printf(“t.f=%d \n”,tpf);
printf(“t.c=%d \n”,tpc);
}
Output:
t.i=123
t.f=18.99
t.c=g
79
UNIT-V
FILE MANAGEMENT
Introduction:
Many real life problems involve large volumes of data and in such situations, the console
oriented I/O operations pose two major problems:
o It becomes cumbersome and time consuming to handle large volumes of data
through terminals.
o The entire data is lost when either the program is terminated or the computer is
turned off.
A file is defined to be a collection of related data stored on secondary storage device like
disk, tapes, and floppy. The concept of files enables us to store large amount of data permanently
on the secondary storage devices
Operations on files:
1. Opening a file
2. Reading from a file
3. Writing to a file
4. Appending to a file (adding to the end of the file)
5. Updating a file
6. Deleting a file
7. Renaming a file
8. Closing a file
Defining & opening a file:
If we want to store data in a file in the secondary memory, we must specify certain things
about the file, to the operating system. They include,
File name
80
Data structure
Purpose
File name is a testing of characters that make up a valid file name foe the operating system. It
may contain two parts, a primary name and an optional period with the extension.
Ex: Student.data
Life.C
Data structure of a file is defined as FILE in the library of standard I/O function definitions.
FILE is a defined data type.
fopen( )
fclose( )
Syntax:
FILE *fp;
fp=fopen(“file name”,”mode of opening”);
mode of opening Purpose
W To create a text file for reading
R To open a text file for writing
A To open a text file for appending
w+ To create a text file for both reading and
writing
r+ To open a text file for both reading and
writing
a+ To open a text file for both reading and
appending
Wb To create a binary file for writing
Rb To open a binary file for reading
Ab To open a binary file for appending
wb+ To create a binary file for both reading and
writing
rb+ To open a binary file for both reading and
writing
ab+ To open a binary file for both reading and
writing
Closing a file:
A file must be closed as soon as all operations on it have been completed. This ensures
that all outstanding information associated with the file is flushed out from the buffers and all
links to the file are broken.
syntax:
fclose(fp);
Where fp is the pointer to FILE type and represents a file
Example:
…………….
…………….
FILE *p1,*p2;
p1=fopen(“input”,”w”);
p2=fopen(“output”, “r”);
…………………
……………………
fclose(p1);
fclose(p2);
……………
81
Input & output operations on files:
i)fputc( ) and fgetc( )character oriented file I/O functions
ii)fputs( ) and fgets( )string oriented file I/O functions
The getc( ) and putc functions:
putc( ):
It is used to write a character
syntax:
putc(c,fp);
Where c represents a character
fprepresents a pointer to file
getc( ):
It is used to read a character
syntax:
c=fgetc(fp);
where c represents a variable of character
fprepresents a pointer to file
82
{
scanf(“%d%s%f”,&e.eno,e.n,&e.salary);
fprintf(fp,”%d%s%f”,e.eno,e.name,e.salary);
}
fclose(fp);
}
Output:
2
101 om 50000
102 sakthi 50000
Error handling during files I/O operations:
Following are the circumstances under which the file I/O operations fail:
1. Trying to read beyond the end of file mark
2. Device overflow.
3. Trying to use a file that has not been opened.
4. Trying to perform an operation over a file when the file has been opened for some other
purpose
5. Opening a file with an invalid file name.
6. Attempting to write to a write protected file.
Eg:
1.fp=fopen(“student.dat”,”r”);
........................................
.........................................
if(fp= =NULL)
{
printf(“The file does not exist”);
Exit(1);
}
2. fp=fopen(“student.dat”,”w”);
........................................
.........................................
if(fp= =NULL)
{
printf(“The filecan not be created”);
Exit(1);
}
3.if(ferror(fp))
{
printf(“Error”);
exit(0);
}
4.while(!feof(fp))
{
reading statements
}
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
83
fp=fopen(“books.dat”,”r”);
if(fp= = NULL)
{
printf(“The file books.dat does not exist”);
getch();
}
fp=fopen(“students.dat”,”w”);
if(fp= = NULL)
{
printf(“The read-only file students.dat can not be opened in write mode”);
getch();
}
fp=fopen(“text.dat”,”r”);
fputc(‘a’,fp);
if(ferror(fp))
{
printf(“The file text.dat has been opened in read mode”);
printf(“But you are writing to it”);
}
getch();
}
Output:
The file books.dat does not exist
The read-only file students.dat can not be opened in write mode
The file text.dat has been opened in read mode But you are writing to it
84
struct emp
{
int eno;
char n[20];
float salary;
};
void main()
{
FILE *fp;
Int n,l;
Fp=fopen(“emp.dat”,”r”);
Fseek(fp,0,SEEK_END);
l=ftell(fp);
n=l/sizeof(struct emp);
printf(“No of records = %d”,n);
fclose(fp);
}
output:
No of records=2
85
fout=fopen(argv[2],”w”);
while(!feof(fin))
{
c=fgetc(fin);
fputc(c,fout);
}
fclose(fin);
fclose(fout);
}
Output:
C:\>copy om.dat om1.dat
As a result the contents of om.dat are copied to om1.dat
THE PREPROCESSOR
The preprocessor, as its name implies, is a program that processes the source code before
it passes through the compiler. It operates under the control of what is known as preprocessor
command lines or directives.
Preprocessor directives:
Directive functions
#define defines a macro substitution
#include specifies the files to be included
#end if specifies the end of #if.
#if test a compile time condition
#else specifies alternatives when #if test fails.
MACRO SUBSTITUTION:
Macro substitution is a process where an identifier in a program is replaced by a
predefined string composed of one or more tokens.
The general form is:
#define identifier string
If this statement is included in the program at the beginning, then the preprocessor
replaces every occurrence of the identifier in the source code by the string.
The keyword #define is written followed by the identifier and a string, with at least one
blank space between them.
The string may be any text, while the identifier must be a valid C name.
There are different forms of macro substitution. The most common forms are:
Simple macro substitution
Argumented macro substitution
Nested macro substitution
86
Simple macro substitution:
Simple string replacement is commonly used to define constants.
Ex:
#define COUNT 100
#define CAPITAL “DELHI”
In the above example, they replace all occurrences of COUNT & CAPITAL with 100 &
DELHI, starting from the line of definition to the end of the program.
There is no space between the macro identifier and the left parentheses.
The identifier f1,f2 ………fn are the formal macro arguments that are analogous to the
formal arguments in a function definition.
Subsequent occurrence of a macro with arguments is known as a macro call.
When a macro is called, the preprocessor substitutes the string, replacing the formal
parameters with the actual parameters.
Example:
#define CUBE(x) (x*x*x)
If the following statement appear in the program,
volume = CUBE(side);
Then the preprocessor would expand this statement to:
volume = (side * side * side );
Nesting of macros:
we can also use one macro in the definition of another macro.
Ex:
#define M 5
#define SQUARE(x) ((x) * (x))
#define CUBE(x) (SQUARE(x) * (x))
for example,
(( CUBE(x) * CUBE(x))
first expanded into
(( SQUARE(x) * (x)) * (SQUARE(x) * (x))
Since SQUARE(x) is still a macro, it is further expanded into
(( (x) * (x) * (x)) * ((x) * (x) * (x))
File inclusion:
An external file containing functions or macro definition can be included as part of a
program so that we need not rewrite those functions or macro definitions. This is achieved by
preprocessor directive
#include “file name”
Where filename is the name of the file containing the required definitions or functions. At this
point, the preprocessor inserts the entire contents of filename into the source code of the
program. When the filename is included within the double quotation marks, the search for the
file is made first in the current directory and then in the standard directories.
Alternatively this directive can take the form
#include <filename>
In this case, the file is searched only in the standard directories.
87
Nesting of included files is allowed. That is, included files can other files. How ever, a
file cannot include itself.
If an included file is not found, an error is reported and compilation is terminated.
Let us assume that we have created following three files:
SYNTAX.C contains syntax definitions.
STAT.C contains statistical functions.
TEST.C contains test functions.
We can make use of a definition or function contained in any of these files by including them in
the program as:
# include <stdio.h>
# include “SYNTAX.C”
# include “STAT.C”
# include “TEST.C”
# define M 100
main ()
While developing large programs, you may face one or more of the following situations:
We have included a file containing some macro definition. It is not known whether a
particular macro has been defined in that header file.
Suppose a customer has two different types of computers and we are required to write a
program that will run on both the systems.
We are developing a program for selling in the open market. Some customers may insist
on having certain additional features.
Suppose we are in the process of testing your program, which is rather a large one. We
would like to have print calls inserted in certain places to display intermediate results and
messages in order to trace the flow of execution and errors, if any. Such statements are
called “debugging statement”.
88
MODEL QUESTIONS :
PROGRAMMING IN C
1. What is Tokens?
2. Define: Keywords and Identifiers.
3. What is use of if statement?
4. write a syntax of while loop?
5. What is function?
6. Explain recursion?
7. What is pointer?
8. Difference between union and structure.
9. Explain any two file handling function?
10. List any three file mode in C?
SECTION – B (5 x 5 = 25 Marks)
89
b) Differentiate between relational and logical operators used in
C? 12.a) Explain syntax and use of Do-While statement
(or)
b) Expalin one dimensional array with an example
13.a) Explain any 4 string functions with suitable example?
(or)
b) What is the difference between call by value and call
by reference
SECTION – C (3 x 10 = 30 Marks)
PROGRAMMING IN C
1. Define constants.
2. What is known as type conversion?
3. Explain about if-else statement.
90
4. Define array.
5. What is character array
6. Define recursion.
7. Define structure.
8. Define bit fields with syntax .
9. Explain about file management.
10. Define preprocessor.
SECTION – B (5 x 5 = 25 Marks)
91
16. Explain about the different types of operators.
17. Explain about different types of array with example program.
18. Explain in detail about nesting of functions with example program.
19. Explain in detail about the pointers.
20. Explain about the file management with example program.
PROGRAMMING IN C
SECTION – A (10 x 2 = 20 Marks)
1. Define constants.
2. Define: Keywords and Identifiers.
3. Explain about if-else statement.
4. write a syntax of while loop?
5. What is character array
6. What is function?
7. Define structure.
8. Define bit fields with syntax .
9. Explain any two file handling function?
10. Define preprocessor.
SECTION – B (5 x 5 = 25 Marks)
92
(Or)
(b) Explain about function call.
14. (a) Write a short note on pointers and
arrays. (Or)
(b) Explain pointer to structure in detail
15. (a) Explain about error handling.
(Or)
(b) Explain about Input/ Output operation on files.
SECTION – C (3 x 10 = 30 Marks)
93