2014 C Notes (Repaired) - 3
2014 C Notes (Repaired) - 3
UNIT – I
OVERVIEW OF C:
HISTORY OF C
‘C’ seems a strange name for a programming language. ‘C’is a structured, high-level,
machine independent language. It allows software developers to develop programs without
worrying about the hardware platforms where they will be implemented.
The root of all modem languages is ALGOL, introduced in the early 1960s. ALGOL
was the first computer language to use a block structure.
In 1970,Ken Thompson created a language using many features of BCPL and called it
simply B. B was used to create early versions of UNIX operating system at Bell Laboratories.
C was evolved from ALGOL, BCPL and B by Dennis Ritchie at the Bell Laboratories
in 1972. C uses many concepts from these languages and added the concept or data type and
other powerful features. Since it was developed along with the UNIX operating system, it is
strongly associated wilh UNIX.
B
1970 Ken Thompson
K&R C
1978 Kernighan and Ritchie
ANSI C
1989 ANSI Committee
ANSI/ISO C
1990 ISO Committee
C99
1999 Standardization Committee
MASC Programming in C
2
IMPORTANCE OF C
C has all the advantages of assembly Language and all the significant features of
modern high level ‘Language. So it is called middle Level Language.
Documentation section
link section
definition section
Global declaration section
main() function section
{
}
subprogram section
(user defined function)
subprogram section
(user defined function)
MASC Programming in C
3
1) Documentation section – It gives the name of the program, the author and any other details
about the program.
2) Link section – It provides instruction to the compiler to link functions from the system
library.
4) Main( ) function section – Every C program must have one main() function. The program
execution begins at the opening brace and ends at the closing brace of main function section.
5) Subprogram section – It contains all the user-defined functions that are called in the main
function.
CHARACTER SET
1. Letters
2. Digits
3. Special characters
4. White spaces
Digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Characters:
, -comma ‘ -apostrophe
\ -backslash ~ -tilde
_ -underscore . –period
MASC Programming in C
4
; -semicolon : -colon
^-caret *-asterisk
#-number sign
TRIGRAPH CHARACTERS
Each trigraph sequence consists of three characters (two question marks followed by another
character)
?? ( [ left bracket
?? / \ back slash
??- ~ tilde
C TOKENS
In an individual words and punctuation marks are called tokens. Similarly , In a C program
the smallest individual units are known as C tokens. C has fixed type of tokens as
follows.
1. Keywords ( float, while )
MASC Programming in C
5
2. Identifiers ( amount )
3. Constants ( 100 , 200)
4. Strings (“hello”)
5. Operators ( + - * % )
6. Special symbols { } []
KEYWORDS
Every c word is classified as either a keyword or an identifier. All key words have
fixed meanings cannot be changed. A keyword may not be used as a variable name. All
keywords must be written in lowercasae.
IDENTIFIERS
Identifiers refer to the names of variables, functions and arrays. These are user-
defined names and consist of a sequence of letters and digits, with a letter as a first character.
Both lowercase and uppercase letters are permitted. Rules for Identifiers
1. First character must be an alphabet or underscore.
2. Must consist of only letters, digits or underscore.
3. Only first 31 characters are significant.
4. Cannot use a keyword.
5. Must not contain white space.
Example: name, area, amount.
CONSTANTS
A constant is fixed values that do not change any value during the execution of a
program.
There are mainly two types of constants namely: Numeric and character constants.
CONSTANTS
Integer Constants
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
214 213 212 211 210 29 28 27 26 25 24 23 22 21 20
= 1*1 + 4*1 + 8*1 + 16*1 + 32*1 + 64*1 + 128*1 + 256*1 + 512*1 + 1024*1
+ 2048*1 + 4096*1 + 2*1 + 8192*1 + 16284*1
32768 is negative
-32767 is minimum
There are 3 types of integers, namely decimal integer, octal integer and hexadecimal
integer.
0 to 9 E.g: 49, 58, -62, … (40000 cannot come bcoz it is > 32767)
0 to 7
MASC Programming in C
7
Add “0” before the value.
Eg.: 045, 056, 067
0 to 9 and A to F
Add 0x before the value
E.g: 0x42, 0x56, 0x67
Real constants
The real or floating point constants are in two forms namely fractional form and the
exponential form.
In exponential form, the real constant is represented as two parts. The part lying before the
‘e’ is the ‘mantissa’, and the one following ‘e’ is the ‘exponent’.
The real constant in exponential form must follow the following rules:
The mantissa part and the exponential part should be separated by the letter ‘e’
The mantissa may have a positive or negative sign(default sign is positive)
The exponent must have at least one digit
The exponent must be a positive or negative integer(default sign is positive)
The range of real constants in exponential form is -3.4e38 and -3.4e38
MASC Programming in C
8
A single character constant is an alphabet, a single digit or a single special symbol
enclosed within inverted commas. The maximum length of a character constant can be 1
character. Allots 1 byte of memory
Character constants have integer values known as ASCII values. For example, the
statement
Printf(“%d” , ‘a’);
Would print the number 97, the ASCII value of the letter a. Similarly, the statement
Printf(“%d” , ‘97’);
These constants are used in output functions. Each one of them represents one
character although they consists two characters. These character combinations are known as
escape sequences.
Constants Meaning
‘\a’ Audible alert(bell)
‘\b’ Back space
‘\f’ Form feed
‘\n’ Newline
‘\r’ Carriage return
‘\t’ Horizontal tab
‘\v’ Vertical tab
‘\’ Single quote
‘\”’ Double quote
‘\?’ Question mark
‘\\’ Backslash
‘\0’ null
String Constants:
A combination of characters enclosed within a part of double inverted commas is called
as “String Constant”.
Example :
MASC Programming in C
9
“Salem” “35.675” ,
VARIABLES
Variable names are names given to locations in the memory. These locations can
contain integer, real or character constants.
An integer variable can hold only an integer constant, a real variable can hold only a
real constant and a character variable can hold only a character constant. Rules for
Constructing Variable Names
DATA TYPES
Data type allows the programmer to select the type appropriate to the needs of the
application as well as the machine.
1. Integral type
i. Integer types (signed and unsigned int,short int and long int)
MASC Programming in C
10
All c compilers support five fundamental data types namely integer (int), character
(char), floating point (float), double precision floating point (double) and void. The basic four
types are
i) Integer types
Integers are whole numbers with a range of values, range of values are machine
dependent. Generally an integer occupies 2 bytes memory space and its value range limited to -
32768 to +32767 (that is, -215 to +215-1). A signed integer use one bit for storing sign and rest
15bits for number.
To control the range of numbers and storage space, C has three classes of integer storage
namely short int, int and long int. All three data types have signed and unsigned forms.
A short int requires half the amount of storage than normal integer. Unlike signed
integer, unsigned integers are always positive and use all the bits for the magnitude of the
number. Therefore the range of an unsigned integer will be from 0 to 65535. The long integers
are used to declare a longer range of values and it occupies 4 bytes of storage space.
MASC Programming in C
11
The float data type is used to store fractional numbers (real numbers) with 6 digits of
precision. Floating point numbers are denoted by the keyword float. When the accuracy of the
floating point number is insufficient, we can use the double to define the number. The double is
same as float but with longer precision and takes double space (8 bytes) than float. To extend
the precision further we can use long double which occupies 10 bytes of memory space.
Character Type:
Character type variable can hold a single character. As there are singed and unsigned int
(either short or long), in the same way there are signed and unsigned chars; both occupy 1 byte
each, but having different ranges. Unsigned characters have values between 0 and 255, signed
characters have values from –128 to 127.
Example: a, b, g, S, j.
Void Type:
The void type has no values therefore we cannot declare it as variable as we did in case
of integer and float.
The void data type is usually used with function to specify its type. Like in our first C
program we declared “main()” as void type because it does not return any value. The concept of
returning values will be discussed in detail in the C function hub.
MASC Programming in C
12
2. Secondary Data Types
Array in C programming
An array in C language is a collection of similar data-type, means an array can hold
value of a particular data type for which it has been declared. Arrays can be created from
any of the C data-types int,
Pointers in C Programming
A pointer is derived data type in c. Pointers contain memory addresses as their values.
Structure in C Programming
We used variable in our C program to store value but one variable can store only single
piece information (an integer can hold only one integer value) and to store similar type of
values we had to declare...
C language supports a feature where user can define an identifier that characterizes an
existing data type. In short its purpose is to redefine the name of an existing data type.
Syntax: typedef <type> <identifier>; like
typedef int number;
The enumerated variables V1, V2, ….. Vn can have only one of the values value1,
value2 ….. value n
Example:
enum day {Monday, Tuesday, …. Sunday};
enum day week_st, week end;
week_st = Monday;
week_end = Friday;
if(wk_st == Tuesday)
week_en = Saturday;
DECLARATION OF VARIABLES
A variable can be used to store value of any data type. The general format of any declaration is
datatype v1, v2, v3, ……….. vn;
Where v1, v2, v3 are variable names. Variables are separated by commas. A declaration
statement must end with a semicolon.
Example:
int sum;
int number, salary;
double average, mean;
MASC Programming in C
14
Datatype Keyword Equivalent
Character char
Signed Short Integer signed short int (or) short int (or) short
Signed Long Integer signed long int (or) long int (or) long
here type represents existing data type and ‘identifier’ refers to the ‘row’ name given to
the data type.
Example:
The second type of user defined datatype is enumerated data type which is defined as
follows.
The identifier is a user defined enumerated datatype which can be used to declare
variables that have one of the values enclosed within the braces. After the definition we can
declare variables to be of this ‘new’ type as below.
MASC Programming in C
15
The enumerated variables V1, V2, ….. Vn can have only one of the values value1,
value2 ….. value n
Example:
Int m;
Main( )
int i;
float balance;
………
………
function1 ( );
function1 ( );
MASC Programming in C
16
int i;
float sum;
………
………
The variable m is called global variable and also known as external variable. It is used in
all the functions in the program.
The variable i, balance and sum is called local variables. It is visible and meaningfull
only inside the functions in which they are declared.
auto : It is a local variable known only to the function in which it is declared. Auto is the default
storage class.
static : Local variable which exists and retains its value even after the control is transferred to
the calling function.
extern : Global variable known to all functions in the file
register : Social variables which are stored in the register.
Another way of giving values to variables is to input data through keyboard using the scanf
function.
The general format of scanf is as follow:
scanf(“control string”, & variable1,&variable2,…….)
The values of some variable may be required to remain constant through-out the
program. We can do this by using the qualifier const at the time of initialization. Example:
Const int class_size = 40;
The const data type qualifier tells the compiler that the value of the int variable class_size may
not be modified in the program.
When we declare a variable as volatile, the compiler will examine the value of the
variable each time it is encountered to see whether any external alteration has changed the
value.
The value of the variable declared as volatile can be modified by its own program as
well. The value must not be modified by the program while it may be altered by some other
process, then we declare the variable as both const and volatile
Volatile const int location =100;
MASC Programming in C
18
OPERATORS:
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increments and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators
1. Arithmetic Operators
C allows us to carryout basic arithmetic operation like addition, subtraction,
multiplication and division. The following table shows the arithmetic operators and their
meaning.
Operator Meaning
* Multiplication
/ Division
% Modulo division
All the above operators are called binary operators as they acts upon two operands at a
time.
MASC Programming in C
19
Examples :
x+y
x-y
-x + y
Example
}
.
Integer Arithmetic
When an arithmetic operation is performed on two whole numbers or integers then such
an operation is called as integer arithmetic. It always gives an integer as the result.
Let x = 27 and y = 5 be 2 integer numbers. Then the integer operation leads to the
following results.
x + y = 32
x – y = 22
x * y = 115
x%y=2
x/y=5
In integer division the fractional part is truncated.
MASC Programming in C
20
point arithmetic operands.
Let x = 14.0 and y = 4.0 then
x + y = 18.0
x – y = 10.0
x * y = 56.0
x / y = 3.50
2. Relational Operators
Relational operators are used to compare two or more operands. Operands may be
variables, constants or expression. C supports the following relational operators.
Operator Meaning
== is equal to
!= is not equal to
A simple relational expression contains only one relational operator and takes the following
form.
Where exp1 and exp2 are expressions, which may be simple constants, variables or combination
of them.
MASC Programming in C
21
Given below is a list of examples of relational expressions and evaluated values.
6.5 <= 25 TRUE
-65 > 0 FALSE
10 < 7 + 5 TRUE
Relational expressions are used in decision making statements of C language such as if, while
and for statements to decide the course of action of a running program.
3. Logical Operators
C has the following logical operators; they compare or evaluate logical and relational
expressions.
Operator Meaning
|| Logical OR
! Logical NOT
a > b && x = = 10
The expression to the left is a > b and that on the right is x == 10 the whole expression is true
only if both expressions are true i.e., if a is greater than b and x is equal to 10.
Logical OR (||)
The logical OR is used to combine 2 expressions or the condition evaluates to true if any one of
the 2 expressions is true.
Example
a < m || a < n
The expression evaluates to true if any one of them is true or if both of them are true. It
evaluates to true if a is less than either m or n and when a is less than both m and n.
MASC Programming in C
22
Logical NOT (!)
The logical not operator takes single expression and evaluates to true if the expression is false
and evaluates to false if the expression is true. In other words it just reverses the value of the
expression.
For example
! (x >= y) the NOT expression evaluates to true only if the value of x is neither greater than or
equal to y
4. Assignment Operators
The Assignment Operator evaluates an expression on the right of the expression and substitutes
it to the value or variable on the left of the expression.
Example x=a+b
Example
x + = 1 is same as x = x + 1
a=a+1 a += 1
a=a–1 a -= 1
a = a * (n+1) a *= (n+1)
a = a / (n+1) a /= (n+1)
a=a%b a %= b
MASC Programming in C
23
Output
2
4
16
The increment and decrement operators are one of the unary operators which are very
useful in C language. They are extensively used in for and while loops. The syntax of the
operators is given below
++ variable name
variable name++
– –variable name
variable name– –
The increment operator ++ adds the value 1 to the current value of operand and the
MASC Programming in C
24
decrement operator – – subtracts the value 1 from the current value of operand. ++variable name
and variable name++ mean the same thing when they form statements independently, they
behave differently when they are used in expression on the right hand side of an assignment
statement.
For example
a = 10; b = 15; x = (a > b) ? a : b
Here x will be assigned to the value of b. The condition follows that the expression is false
therefore b is assigned to x.
MASC Programming in C
25
larger = i > j ? i : j; //evaluation using ternary operator
printf(“The largest of two numbers is %d \n”, larger); // print the largest number
} // end of the program
Output
Input 2 integers : 34 45
The largest of two numbers is 45
7. Bitwise Operators
A bitwise operator operates on each bit of data. Those operators are used for testing,
complementing or shifting bits to the right on left. Bitwise operators may not be applied to a
float or double.
Operator Meaning
| Bitwise OR
^ Bitwise Exclusive
8. Special Operators
C supports some special operators of interest such as comma operator, size of operator,
pointer operators (& and *) and member selection operators (. and ->).
First assigns 10 to x and 5 to y and finally assigns 15 to value. Since comma has the lowest
precedence in operators the parenthesis is necessary. Some examples of comma operator are
MASC Programming in C
26
In for loops:
In while loops
Exchanging values
t = x, x = y, y = t;
Example
m = sizeof (sum);
n = sizeof (long int);
k = sizeof (235L);
The size of operator is normally used to determine the lengths of arrays and structures
when their sizes are not known to the programmer. It is also used to allocate memory space
dynamically to variables during the execution of the program.
Example :
Notice the way the increment operator ++ works when used in an expression. In the
statement c = ++a – b; new value a = 16 is used thus giving value 6 to C. That is a is
incremented by 1 before using in expression.
However in the statement d = b++ + a; The old value b = 10 is used in the expression.We
can print the character % by placing it immediately after another % character in the control
string. This is illustrated by the statement.
MASC Programming in C
27
c>d?1:0
Assumes the value 0 when c is less than d and 1 when c is greater than d.
ARITHMETIC EXPRESSIONS
(m + n) (x + y) (m + n) * (x + y)
(ab / c) a*b/c
(x / y) + c x/y+c
EVALUATION OF EXPRESSIONS
Variable = expression;
Variable is any valid C variable name. When the statement is encountered, the
expression is evaluated first and then replaces the previous value of the variable on the left hand
side. All variables used in the expression must be assigned values before evaluation is
attempted.
Example of evaluation statements are
x=a*b–c
y=b/c*a
MASC Programming in C
28
z = a – b / c + d;
main ()
{
float a, b, c x, y, z;
a = 9;
b = 12;
c = 3;
x = a – b / 3 + c * 2 – 1;
y = a – b / (3 + c) * (2 – 1);
z = a – ( b / (3 + c) * 2) – 1;
printf (“x = %fn”,x);
printf (“y = %fn”,y);
printf (“z = %fn”,z);
}
output
x = 10.00 y = 7.00 z = 4.00
An arithmetic expression without parenthesis will be evaluated from left to right using
the rules of precedence of operators. There are two distinct priority levels of arithmetic
operators in C.
High priority * / %
Low priority + -
MASC Programming in C
29
Implicit type conversion
C permits mixing of constants and variables of different types in an expression. C
automatically converts any intermediate values to the proper type so that the expression can be
evaluated without loosing any significance. This automatic type conversion is known as
implicit type conversion during evaluation it adheres to very strict rules and type conversion. If
the operands are of different types the lower type is automatically converted to the higher type
before the operation proceeds. The result is of higher type.
1. If one operand is long double, the other will be converted to long double and result will be
long double.
2. If one operand is double, the other will be converted to double and result will be double.
3. If one operand is float, the other will be converted to float and result will be float.
4. If one of the operand is unsigned long int, the other will be converted into unsigned long int
and result will be unsigned long int.
a). If unsigned int can be converted to long int, then unsigned int operand will be converted as
such and the result will be long int.
b) Else Both operands will be converted to unsigned long int and the result will be unsigned
long int.
6. If one of the operand is long int, the other will be converted to long int and the result will be
long int.
7. If one operand is unsigned int the other will be converted to unsigned int and the result will
be unsigned int.
double
float
Conversion unsigned long int
Hierarchy
long int
unsigned int
int
short char
Explicit Conversion
Many times there may arise a situation where we want to force a type conversion in a
way that is different from automatic conversion.
MASC Programming in C
30
Consider for example the calculation of number of female and male students in a class
Since if female_students and male_students are declared as integers, the decimal part will
be rounded off and its ratio will represent a wrong figure. This problem can be solved by
converting locally one of the variables to the floating point as shown below.
The operator float converts the female_students to floating point for the purpose of
evaluation of the expression. Then using the rule of automatic conversion, the division is
performed by floating point mode, thus retaining the fractional part of the result. The process of
such a local conversion is known as explicit conversion or casting a value. The general form is
(type_name) expression
Each operator in C has a precedence associated with it. The precedence is used to
determine how an expression involving more than one operator is evaluated. There are distinct
levels of precedence and an operator may belong to one of these levels. The operators of higher
precedence are evaluated first. The operators of same precedence are evaluated from right to left
or from left to right depending on the level. This is known as associativity property of an
operator.
MASC Programming in C
32
UNIT-II
Introduction
at the beginning.
1 . READING A CHARACTER
The basic operation done in input output is to read a character from the standard input
device such as the keyboard and to output or writing it to the output unit usually the screen.
getchar() function
The getchar function can be used to read a character from the standard input device. It
has the following form.
Variable name = getchar();
Variable name is a valid ‘C’ variable, that has been declared already and that possess the type
char.
Example program :
# include < stdio.h > // assigns stdio-h header file to your program
MASC Programming in C
33
void main ( ) // Indicates the starting point of the program.
{
char C, // variable declaration
printf (“Type one character:”) ; // message to user
C = getchar () ; // get a character from key board and
Stores it in variable C.
Printf (” The character you typed is = %c”, C) ; // output
} // Statement which displays value of C on
// Standard screen.
getc() function
This is used to accept a single character from the standard input to a character variable. It
general syntax is
Character variable=getc();
Where character variable is the valid ‘c’ variable of the type of char data type.
Ex:
Char c;
C=getc();
2. WRITING A CHARACTER
Putchar() function
The putchar function which in analogues to getchar function can be used for writing characters
one at a time to the output terminal.
The general form is
putchar (variable name);
Where variable is a valid C type variable that has already been declared
Ex:-
Putchar ( );
Displays the value stored in variable C to the standard screen.
#include < stdio.h > // Inserts stdio.h header file into the Pgm
void main ( ) // Beginning of main function.
{
char in; // character declaration of variable in.
printf (” please enter one character”); // message to user
in = getchar ( ) ; // assign the keyboard input value to in.
putchar (in); // out put ‘in’ value to standard screen.
}
MASC Programming in C
34
Putc() function:
Syntax:
Putc(Character variable);
Ex: char x;
Putc(x);
gets() function
The function gets accepts the name of the string as a parameter, and fills the string with
characters that are input from the keyboard till new line character is encountered. (That is till we
press the enter key). All the end function gets appends a null terminator as must be done to any
string and returns.
gets (str)
Puts() function
The puts function displays the contents stored in its parameter on the standard screen.
The standard form for the puts character is
puts (str)
Scanf() function
The formatted input refers to input data that has been arranged in a particular format.
Input values are generally taken by using the scanf function.
The format field is specified by the control string and the arguments
arg1, arg2, …………….argn specifies the address of location where address is to be stored.
The control string specifies the field format which includes format specifications and
optional number specifying field width and the conversion character % and also blanks, tabs and
newlines.
The Blanktabs and newlines are ignored by compiler. The conversion character % is
followed by the type of data that is to be assigned to variable of the assignment. The field width
specifier is optional.
The below table illustrates code formats (control strings) in Input and output statements.
Format Code Meaning
The control string must be preceded with % sign and must be within quotations i.e
address of variable should be passed.
MASC Programming in C
36
If there is a number of input data items, items must be separated by commas and must be
preceded with & sign except for string input.
The control string and the variables going to input should match with each other.
It must have termination with semicolon.
The scanf() reads the data values until the blank space in numeric input or maximum
number of character have been read or an error is detected.
The integers can be read through scanf statements with the field specification along with the
control string.
MASC Programming in C
37
Ex: scanf(“%5s”,name);
printf()function
The most simple output statement can be produced in C’ Language by using printf statement. It
allows you to display information required to the user and also prints the variables we can also
format the output and provide text labels.
The general form of the printf ( ) function is
Syntax :
The conversion string includes all the text labels, escape character and conversion
specifiers required for the desired output. The variable includes all the variable to be printed in
order they are to be printed. There must be a conversion specifies after each variable.
For Example :
printf (“Hello!\n”);
Output:
Hello!
The printf ( ) function is quite flexible. It allows a variable number of arguments, labels and
sophisticated formatting of output.
Specifier Meaning
%c – Print a character
%d – Print a Integer
%i – Print a Integer
%e – Print float value in exponential form.
%f – Print float value
%g – Print using %e or %f whichever is smaller
%o – Print actual value
%s – Print a string
%x – Print a hexadecimal integer (Unsigned) using lower case a – F
%X – Print a hexadecimal integer (Unsigned) using upper case A – F
%a – Print a unsigned integer.
%p – Print a pointer value
%hx – hex short
%lo – octal long
%ld – long
The control string and the variables must match in their order
The control string must be in quotations and there we can also use any other text to print with
data.
1 2 3 4
Ex: printf(“%4d”,1234);
Printf(“%5d”,1234); 1 2 3 4
printf(“%07d”,1234); 0 0 0 1 2 3 4
MASC Programming in C
39
Printf(“%7.2f”,a) 2 8 . 4 4
Printf(“%10.2e”,a) 2 . 8 4 e + 0 1
h a r i s h k u m a r a
Print(“%15.8s”, name);
h a r i s h k u
MASC Programming in C
40
DECISION MAKING AND BRANCHING
Introduction
C language possesses such decision making capabilities and supports the following
statements known as control or decision-making statements.
1. if statement
2. switch statement
3. Conditional operator statement
4. goto statement
MASC Programming in C
41
IF STATEMENT
The if statement is a powerful decision making statement and is used to control the
flow of execution of statements. It is basically a two-way decision statement and is used in
conjunction with an expression. It takes the following form:
if (test expression)
It allows the computer to evaluate the expression first and then, depending on whether
the value of the expression (relation or condition) is ' true ' (non-zero) or ' false ' (zero), it
transfers the control to a particular statement. This point of program has two paths to follow,
one for the true condition and the other for the false condition.
1. Simple if statement
2. if...else statement
3. Nested if...else statement
4. else if ladder.
SIMPLE IF STATEMENT
if (test expression)
{
statement-block;
}
statement-x;
Example:
..........
if (x == 1)
{
y = y +10;
}
MASC Programming in C
42
printf("%d", y);
.........
The program tests the value of x and accordingly calculates y and prints it. If x is 1
then y gets incremented by 1 else it is not incremented if x is not equal to 1. Then the value of y
gets printed.
IF…ELSE STATEMENT
The if....else statement is an extension of the simple if statement. The general form is
if (test expression)
{
True-block statement(s)
}
else
{
False-block statement(s)
}
statement-x
If the test expression is true, then the true-block statement(s), are executed; otherwise the
false-block statement(s) are executed. In either case, either true-block or false-block will be
executed, not both.
Example:
........
if (c == 'm')
male = male +1;
else
fem = fem +1;
.......
When a series of decisions are involved, we may have to use more than one if.....else
statement in nested form as follows:
if (test condition1)
{
if (test condition 2)
{
statement-1;
}
MASC Programming in C
43
else
{
statement-2;
}
}
else
{
statement-3;
}
statement-x;
ELSE IF LADDER
There is another way of putting ifs together when multipath decisions are involved. A
multipath decision is a chain of it’s in which the statement associated with each else is an if. It
takes the following general form:
if (condition 1)
statement 1 ;
else if (condition 2)
statement 2;
else if (condition 3)
statement 3;
else if (condition n)
statement n;
else
default statement;
statement x;
This construct is known as the else if ladder. The conditions are evaluated from the top (of the
ladder), downwards. As soon as a true condition is found, the statement associated with is
executed and the control is transferred to the statement x (skipping the rest of the ladder).
When all the n conditions become false, then the final else containing the default
statement will be executed.
Example:
Let us consider an example of grading the students in an academic institution. The grading is
done according to the following rules:
MASC Programming in C
44
Average marks Grade
80-100 Honours
60- 79 First Division
50- 59 Second Division
40- 49 Third Division
0- 39 Fail
SWITCH STATEMENT
C has a built-in multi way decision statement known as a switch. The switch statement
tests the value of a given variable (or expression) against a list of case values and when a match
is found, a block of statements associated with that case is executed. The general form of the
switch statement is as shown below:
switch (expression)
{
case value-1:
block-1
break;
case value-2:
block-2
break;
......
.....
default:
default-block
break;
}
statement-x;
MASC Programming in C
45
The expression is an integer expression or characters. value1, value2, .... are constants or
constant expressions and are known as case labels. Each of these values should be unique within
a switch statement. block1, block2, are statement lists and may contain zero or more statements.
There is no need to put braces around these blocks. Note that case labels end with a colon.
On execution of the keyword switch, the value of the expression is successively
compared against the values value1, value2, ........If the value of the expression for a particular
case matches with a case value , then the block of statements that follows the case are executed.
The break statement at the end of each block signal the end of a particular case and causes an
exit from the switch statement, transferring the control to the statement-n following the switch.
The default is an optional case. When present, it will be executed if the expression does not
match any of the case values. If not present, no action takes place if all matches fail and the
control goes to the statement-n.
Consider a common program design in which a menu is provided by the switch statement.
........../* the value is accepted from the user and given to a identifier */
......... /* the data type of the value should match with that of the identifier */
switch (n)
{
case 1:
printf (" ADDITION /n");
break;
case 2:
printf (" SUBTRACTION /n);
break;
default:
break;
}
statement-x;
The value of variable n is accepted and then tested using the switch statement. Any
value other than 1 or 2 will lead to end of the default block.
CONDITIONAL OPERATOR
GOTO STATEMENT
In all the statements seen one common thing was that, there execution depended on some
condition. However we also have statements in which are unconditional. Like many other
languages, C supports the GOTO statement to branch unconditionally from one point to another
in the program. Although it may not be essential to use the GOTO statement in a highly
structured language like C, there may be occasions when the use of GOTO might be desirable.
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, must be followed by a colon. The label is placed
immediately before the statement where the control is to be transferred. The general forms of
GOTO and label statements are shown below:
GOTO label;
........ Forward jump
........
label: statement;
label: statement;
........ backward jump
........
GOTO label;
The label: can be anywhere in the program either before or after the goto label;
statement. During running of a program when a statement like goto begin; is met, the flow of
MASC Programming in C
47
control jumps to the statement immediately following the label begin. This happens
unconditionally.
A goto breaks the normal sequential execution of the program. If the label: is
before the statement goto label; a loop will be formed and some statements will be executed
repeatedly. Such a jump is known as a backward jump.
On the other hand, if the label is placed after the goto label; some statements will be skipped and
the jump is known as a forward jump.
Depending on the position of the control statement in the loop, a control may be
classified as the entry-controlled loop or as the exit-controlled loop. In the entry-controlled
loop, first the conditions are tested and if satisfied then only body of loop is executed. In the
exit-controlled, the test is made at the end of the body, so the body is executed unconditionally
first time.
The C language provides for three loop constructs for performing loop operations. They are:
MASC Programming in C
48
WHILE STATEMENT
This is one of the simplest looping structures. The basic format of the while statement
is
The while is an entry-controlled loop statement. The test condition is evaluated and
only if the condition is true the body is executed. After execution of the body, the test-condition
is once again evaluated and if it is true, the body is executed once again. This process of
repeated execution of the body continues until the test-condition finally becomes false and the
control is transferred out of the loop.
Example:
main( )
{
int x;
x = 10; ------------- Initialization
while (x < 16) ------------- Test condition
{
printf("%d",x); ------------- body of the loop
x = x+1;
}
}
The above example shows a simple position where the test condition is evaluated first
and since the test is satisfied the body is executed. This will continue exactly six times printing
out 10 to 15. Finally when x becomes 16 then test fails & so the loop ends. The program
continues with the statements after the loop.
DO STATEMENT
The while is an entry-controlled loop structure, in which the loop will not be executed if
the test condition comes out to be false. But in some situations it might be necessary to execute
the loop, even if the test-condition fails. So this kind of loops is called the exit-controlled loop
structure. This takes the form:
MASC Programming in C
49
do
{
body of the loop
}
while (test condition);
Example:
main( )
{
int x;
x = 10; ------------- Initialization
do
{
printf("%d",x); ------------- body of the loop
x = x+1;
} while (x < 16) ------------- Test condition
}
The above example shows a simple position where the body of the loop is executed first and the
then test condition is evaluated. If it is true the body of the loop is executed again. This will
continue exactly six times printing out 10 to 15. Finally when x becomes 16 then test fails & so
the loop ends. The program continues with the statements after the loop.
FOR STATEMENT
The for loop is another entry-controlled loop that provides a more concise loop control structure.
1. Initialization of the control variables is done first, using assignment statements such as i
= 1 and count = 0. The variables i and count are known as loop control variables.
2. The value of the control variable is tested using the test-condition. The test-condition is a
relational expression, such as i<10 that determines when the loop will exit. If the
condition is true, the body of the loop is executed; otherwise the loop is terminated and
MASC Programming in C
50
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.
Example:
The for loop will be executed 10 times. Each time a value equal to the current value of i will be
printed out.
1. More than one variable can be initialized at a time in the for statement. For example:
2. Like the initialization section, the increment section may also have more than one part.
For example,
For example
MASC Programming in C
51
4. One or more sections in the for statement can be omitted, if necessary. For example
e = 2;
for (; e != 10 ;)
{
printf("%d",e);
e = e + 2;
}
Both the initialization and increment sections are omitted in the for statement. In such cases, the
sections are left blank. However, the semicolons separating the sections must remain. If the test-
condition is not present, the for statement sets up an ‘infinite’ loop. Such loops can broken
using break or goto statements in the loop.
Nesting of loops i.e., one for statement within another for statement, is allowed in c.
For ex:
--------
}
JUMPS IN LOOPS:
Loops perform a set of operations repeatedly until the control variables fails to
satisfy the test conditions.
The number of times the loop is repeated is decided in advance and the test
conditions is returned to achieve this.
Some times, when executing a loop it becomes desirable to skip a part of the loop
or to leave the loop as soon as a certain conditions occurs.
C permits a jump form one statement to another within a loop as well as jump out of a
loop.
MASC Programming in C
52
Jumping Out of a Loop:
Exit from a loop can be accomplished by using the break statement or the goto
statement.
These statements can also be used within while, do or for loops.
When a break statement is encountered inside a loop, the loop is immediately exited and
the program continues with the statement immediately following the loop.
When the loops are nested the break would only exit from the loop containing it. i.e the
break will exit only a single loop.
while (------) do for (-------)
{ { {
------- ------- ------
if (condition) if (condition)
if(error)
break; break; break;
-------- -------- Exit --------
} } from }
------- while (-------); loop ---------
Since a goto statement can transfer the control to any place in a program, it is useful to
provide within a loop.
Another important use of goto statement is to exit from deeply nested loops when an
error occurs.
MASC Programming in C
53
Jumping within and Existing from the Loops with goto Statement
while (test-condition) do
{ {
------- -------
if (-------) if ( -----)
continue; continue;
--------- - --------
--------- --------
} }
while (test-condition);
UNIT - III
MASC Programming in C
54
ARRAYS
An array is a fixed-size sequenced collection of elements of the same data type. It
is simply a grouping of like-type data. In its simplest form, an array can be used to
represent a list of numbers or a list of items.
An array is a group of related data items that share a common name.
An array is a collection of similar quantities. It is referenced by a common
name.
Each element of an array is stored in successive locations of memory.
Arrays to represent not only simple list of values but also tables of data tin two,
three or more dimensions.
There are three types of arrays. They are
1. One-dimensional arrays.
2. Two-dimensional arrays.
3. Multidimensional arrays.
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 one-dimensional array.
Declaration of arrays:
Like any other variable arrays must be declared before they are used.
Where
The type specifies the type of the elements that will be contained in the array, such as
int, float or char
the size indicates the maximum number of elements that can be stored inside the array .
MASC Programming in C
55
a is the name of the array with 5 subscripts of integer data types 0 to 4 and the computer
reserves five storage location as shown below.
a[0]
a[1]
a[2]
a[3]
a[4]
A value stored into an element in the array simply by specifying the array element on the
left hand side of the equals sign. In the statement
grades [100]=95;
The value 95 is stored into the element number 100 of the grades array.
The ability to represent a collection of related data items by a single array enables us to develop
concise and efficient programs. For example we can very easily sequence through the elements
in the array by varying the value of the variable that is used as a subscript into the array. So the
for loop
Will sequence through the first 100 elements of the array grades (elements 0 to 99) and
will add the values of each grade into sum. When the for loop is finished, the variable sum will
then contain the total of first 100 values of the grades array (Assuming sum were set to zero
before the loop was entered)
Initialization of arrays:
At compile time
At run time
MASC Programming in C
56
Compile time initialization
We can initialize the elements in the array in the same way as the ordinary variables
when they are declared. The general form of initialization of arrays is:
The values in the list care separated by commas, for example the statement
int number[3]={0,0,0};
Will declare the array size as a array of size 3 and will assign zero to each element if the
number of values in the list is less than the number of elements, then only that many elements
are initialized. The remaining elements will be set to zero automatically.
In the declaration of an array the size may be omitted, in such cases the compiler allocates
enough space for all initialized elements. For example the statement
int counter[]={1,1,1,1};
Will declare the array to contain four elements with initial values 1. This approach works
fine as long as we initialize every element in the array.
An array can be explicitly initialized at run time. This approach is usually applied for
initializing large arrays. For example
------
-------
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 2.0 at run time.
MASC Programming in C
57
Two-Dimensional Arrays
Two dimensional arrays are used in situation where a table of values needs to be stored
in an array.
Example:
int a[3][3];
Two-dimensional arrays are stored in memory. The first index selects the row and the second
index selects the column within that row.
Column0 Column1 Column2
MASC Programming in C
58
[2][0] [2][1] [2][2]
Row 2- 310 275 365
The two-dimensional arrays may be initialized by following their declaration with a list of initial
values enclosed in braces.
Example:
int table[2][3] = { 0, 0, 0, 1, 1, 1};
initializes the elements of the first two row to zero and the second row to one. The
initialization is done row by row.
int table[2][3] = {{ 0, 0, 0}, {1, 1, 1}};
int table[2][3] = {
{0, 0, 0}, Matrix form
{1, 1, 1}
};
int table[ ][3] = {
{0, 0, 0}, is permitted
{1, 1, 1}
};
If the values are missing in an initializer, they are automatically set to zero.
int table[2][3] = {
{1, 1}, is permitted
{2}
};
MASC Programming in C
59
Where sales is the three dimensional array, contains 240 float type elements.
Initialization of multidimensional arrays:
Like the one dimension arrays, 2 dimension arrays may be initialized by following their
declaration with a list of initial values enclosed in braces
Example:
int table[2][3]={0,0,0,1,1,1};
Initializes the elements of first row to zero and second row to 1. The initialization is done
row by row. The above statement can be equivalently written as
int table[2][3]={{0,0,0},{1,1,1}}
DYNAMIC ARRAYS:
The process of allocating memory at compile time is known as static allocation and the
arrays that receive static memory allocation are called static arrays.
The process of allocate memory to arrays at run-time is known as dynamic memory
allocation.
The arrays created at run time are called Dynamic arrays.
The functions used in the dynamic memory management are :
1. malloc()
2. calloc()
3. realloc()
These functions are included in the header file <stdlib.h>.
The concept of dynamic arrays is used in creating and manipulating data structures
such as linked lists, stacks and queues.
MASC Programming in C
60
/* Program to add two matrices & store the results in the 3rd matrix */
#include< stdio.h >
#include< conio.h >
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,m,n,p,q;
clrscr();
printf(“enter the order of the matrixn”);
scanf(“%d%d”,&p,&q);
if(m==p && n==q)
{
printf(“matrix can be addedn”);
printf(“enter the elements of the matrix a”);
for(i=0;i < m;i++)
for(j=0;j < n;j++)
scanf(“%d”,&a[i][j]);
printf(“enter the elements of the matrix b”);
for(i=0;i < p;i++)
for(j=0;j < q;j++)
scanf(“%d”,&b[i][j]);
printf(“the sum of the matrix a and b is”);
for(i=0;i < m;i++)
for(j=0;j < n;j++)
c[i][j]=a[i][j]+b[i][j];
for(i=0;i < m;i++)
{
for(j=0;j < n;j++)
printf(“%dt”,&a[i][j]);
printf(“n”);
}
}
#include<stdio.h>
void main()
{
int a[20];
int i,n,max,min;
print f("enter no of elements:");
scan f("%d",&n);
print f("reading array elements:");
for(i=0;i<n;i++)
{
print f("enter a[%d]elements:");
scan f("%d",&a[i]);
}
print f("array elements:");
for(i=0;i<n;i++)
MASC Programming in C
61
{
print f("%dt",a[i]);
}
max=a[0];
min=a[0];
for(i=0;i<n;i++)
{
if(max<a[i])
{
max=a[i];
}
if(min>a[i])
{
min=a[i];
}
}
print f("n max=%dt min=%d",max,min);
}
How to write a 'C' program to read an array of 10 numbers and print the prime numbers?
#include <stdio.h>
void main ()
{
int arr[10], i, j, flag;
for (i=0;i<10;i++)
for (i=0;i<10;i++)
{
flag=1;
}
}
}
for (i=0;i<10;i++)
{
if (flag=1)
MASC Programming in C
62
}
}
#include<stdio.h>
main()
{
int a[10][10] b[10][10] c[10][10]:
int i j k;
printf("enter the elements in A matrix");
for(i 0;i< 5;i++)
for(j 0;j<+5;j++)
{
scanf(" d" &a[i][j]); }
printf("enter b matrix");
for(i 0;i< 5;i++)
for(j 0;j<+5;j++)
{
scanf(" d" &b[i][j]);
}
c[0][0] 0;
for(i 0;i< 5;i++)
{ [ this is main logic ]
for(j 0;j< 5;j++)
{
for(k 0;k< 5;k++)
{
c[i][j] c[i][j] c[k][j]+a[i][k]*b[k][j];
}
}
printf("multiplication matrix is");
for(i 0;i< 5;i++)
for(j 0;j< 5;j++)
printf(" d" c[i][j]):
}
INTRODUCTION:
Strings are stored in memory as ASCII codes of characters that make up the string appended
with ‘\0’(ASCII value of null). Normally each character is stored in one byte, successive
characters are stored in successive bytes.
character m y a g e i s
character 2 ( t w o ) \0
The last character is the null character having ASCII value zero.
A string variable is any valid C variable name and is always declared as an array.
The general form of declaration of string variable is
char string_name [size];
The size determines the no. of characters in the string name.
Some examples are
char city[10];
char name[30];
When the compiler assigns a character string to a character array, it automatically supplies
a null character (‘\0’) at the end of the string.
C permits the character array to be initialized in either of the following two forms.
char city[9] = ” NEW YORK”;
char city[9] = {‘ N’,’E’,’W’, ‘ ‘, ‘Y’, ‘O’, ‘R’, ‘K’, ‘\0’ };
C permits us to initialize a character array without specifying the number of elements.
The size of the array will be determined automatically, based on the number of elements
initialized.
Example: char string[ ] = {{‘ N’,’E’,’W’,’\0’};
We can also declare the size much larger than the string size in the initializer.
MASC Programming in C
64
Example: char str[10] = “NEW”;
char str[2] = “NEW” illegal
char s1[4] = “abc”;
char s2[4];
s2 = s1; * error *
It is one dimension array. Each character occupies a byte. A null character (\0) that has the
ASCII value 0 terminates the string. The figure shows the storage of string January in the
memory recall that \0 specifies a single character whose ASCII value is zero.
MASC Programming in C
65
\0
The function scanf with %s format specification is needed to read the character string from the
terminal.
Example:
char address[15];
scanf(“%s”,address);
Scanf statement has a draw back it just terminates the statement as soon as it finds
a blank space, suppose if we type the string new york then only the string new will be read and
since there is a blank space after word “new” it will terminate the string.
The scanf function automatically terminates the string that is read with a null character
and therefore the character array should be large enough to hold the input string plus the null
character.
In many applications it is required to process text by reading an entire line of text from the
terminal.
We can read a single character from the terminal, using the function getchar. We can use
this function repeatedly to read successive single characters from the input and place them into a
character array. Thus, an entire line of text can be read and stored in an array. The reading is
terminated when the newline character (‘\n’) is entered and the null character is then inserted at
the end of the string.
The getchar function call takes the form:
char ch;
ch = getchar ( );
MASC Programming in C
66
A more convenient method of reading a string of text containing whitespaces is to use
the library function gets available in the <stdlio.h> header file.
gets(str);
Here gets reads characters into str from the keyboard until a new line character is
encountered and then appends a null character to the string. Unlike the scanf, it does not skip
whitespaces. For ex:
char line [80];
gets (line);
printf (“%s”, line)
The printf statement along with format specifier %s to print strings on to the screen. The
format %s can be used to display an array of characters that is terminated by the null character
for example printf(“%s”,name); can be used to display the entire contents of the array name.
The putchar functions to output the values of character variable. It takes the following form
Char ch=’a’;
Putchar(ch);
We can use putchar function to write characters to the screen. We can use this function
repeatedly to output a string of characters stored in an array using a loop.
For ex:
Char name[6] =”APPLE”
For(i=0, i<5; i++)
Putchar(name[i];
Putchar(‘\n’);
MASC Programming in C
67
STRING – HANDLING FUNCTIONS
We can also get the support of the c library function to converts a string of digits into
their equivalent integer values the general format of the function in x=atoi(string) here x is an
integer variable & string is a character array containing string of digits.
To do all the operations described here it is essential to include string.h library header file in the
program.
strlen() function:
This function counts and returns the number of characters in a string. The length does not
include a null character.
Syntax n=strlen(string);
Where n is integer variable. This receives the value of length of the string.
Example
length=strlen(“Hollywood”);
The function will assign number of characters 9 in the string to a integer variable length.
/*Write a c program to find the length of the string using strlen() function*/
#include < stdio.h >
include < string.h >
void main()
{
MASC Programming in C
68
char name[100];
int length;
printf(“Enter the string”);
gets(name);
length=strlen(name);
printf(“\nNumber of characters in the string is=%d”,length);
}
strcat() function
The strcat function joins two strings together. This process is called concatenation. The strcat()
function joins 2 strings together. It takes the following form
strcat(string1,string2)
string1 & string2 are character arrays. When the function strcat is executed string2 is appended
to string1. the string at string2 remains unchanged.
Example
strcpy(string1,”sri”);
strcpy(string2,”Bhagavan”);
Printf(“%s”,strcat(string1,string2);
From the above program segment the value of string1 becomes sribhagavan. The string at str2
remains unchanged as bhagawan.
Strcmp() function:
In c you cannot directly compare the value of 2 strings in a condition like if(string1==string2)
Most libraries however contain the strcmp() function, which returns a zero if 2 strings are equal,
or a non zero number if the strings are not the same. The syntax of strcmp() is given below:
Strcmp(string1,string2)
String1 & string2 may be string variables or string constants. String1, & string2 may be string
variables or string constants some computers return a negative if the string1 is alphabetically
less than the second and a positive number if the string is greater than the second.
Example:
MASC Programming in C
69
strcmp(“Newyork”,”Newyork”) will return zero because 2 strings are equal.
strcmp(“their”,”there”) will return a 9 which is the numeric difference between ASCII ‘i’ and
ASCII ’r’.
strcmp(“The”, “the”) will return 32 which is the numeric difference between ASCII “T” &
ASCII “t”.
strcmpi() function
This function is same as strcmp() which compares 2 strings but not case sensitive.
Example
strcpy() function:
The strcpy function works almost like a string-assignment operator. It takes the following form
strcpy(string1,string2);
Strcpy function assigns the contents of string2 to string1. string2 may be a character array
variable or a string constant.
strcpy(Name,”Robert”);
strlwr () function:
This function converts all characters in a string from uppercase to lowercase.
syntax strlwr(string);
For example:
MASC Programming in C
70
For ex strrev(“program”) reverses the characters in a string into “margrop”.
strupr() function:
This function converts all characters in a string from lower case to uppercase.
Syntax strupr(string);
Strncpy : This function copies only the left most n characters of the source string to the target
string variable. This is a three parameter function and is invokes as follows:
Strncpy(s1,s2,5);
This statement copies the first 5 characters of the source string s2 into the target string s1.
Strncmp: A variation of the function strcpy is the function strncpy. This function has three
parameters as follows
Strncmp(s1,s2,n);
It compares the left most n characters of s1 and s2 and return.
0 if they are equal
Negative number, if s1 sub-string is less than s2; and
Positive number, otherwise.
Strncat: This is another concatenation function that three parameters as shown below,
Strncat(s1,s2,n);
This call will concatenate the left most n characters of s2 to the end of s1.
Strstr: It is a two parameter function that can be used to locate a sub string in a string. This
takes the forms;
Strstr(s1,s2);
Strstr(s1,”ABC”);
The function strstr 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. t
Ex:
If(strstr(s1,s2)==null)
Printf(“substring is not found”);
Else
Print(“s2 is a substring of s1”);
MASC Programming in C
71
Strchr & strrchr : We also have functions to determine the existence of a character in a
string. Consider the following function call:
Strchr(s1, ‘m’);
It will locate the first occurrence of the character ‘m’ in string s1.
Similarly the following function call will locate the last occurrence of the character ‘m’ in the
string s1.
Strrchr(s1,’m’);
MASC Programming in C
72
UNIT-IV
INTRODUCTION
We have mentioned earlier that one of the strengths of C language is that C functions are
easy to define and use. C functions can be classified into two categories, namely, library
functions and user-defined functions. main is an example of user defined function. printf and
scanf belong to the category of library functions. The main distinction between user-defined and
library function is that the former are not required to be written by user while the latter have to
be developed by the user at the time of writing a program. However the user defined function
can become a part of the C program library.
A function in C language is a block of code that performs a specific task. It has a name
and it is reusable i.e. it can be executed from as many different parts in a C Program as required.
It also optionally returns a value to the calling program
Every function has a unique name. This name is used to call function from “main()”
function. A function can be called from within another function.
MASC Programming in C
73
A function is independent and it can perform its task without intervention from or
interfering with other parts of the program.
A function performs a specific task. A task is a distinct job that your program must perform
as a part of its overall operation, such as adding two or more integer, sorting an array into
numerical order, or calculating a cube root etc.
A function returns a value to the calling program. This is optional and depends upon the
task your function is going to accomplish. Suppose you want to just show few lines
through function then it is not necessary to return a value. But if you are calculating area of
rectangle and wanted to use result somewhere in program then you have to send back
(return) value to the calling function.
Functions are easier to write, debug and understand. Simple function can be
written to do unique specific tasks. Programs containing the functions are also easier to
maintain. Functions are also put in a library and later used by many programs
1. It facilitates top-down modular programming. In this programming style, the high level
of the overall problem is solved first while the details of each lower-level function are
addressed later.
2. The length of a source program can be reduced by using functions at a appropriate
places.
It is easy to locate and isolate a faulty function for further investigations.
3. A function may be used by many other programs. This means that a C programmer can
build on what others have already done, instead of starting from scratch.
A MULTI-FUNCTION PROGRAM
A function in simple terms can be viewed as a black box which takes in some value (if
required) and outputs some result. The internal details of the function are hidden from rest of the
program. Every C program can be designed using a collection of these black boxes.
Consider an example as follows:
MASC Programming in C
74
displayname()
{
printf("\nResult of displayname function call");
}
Above function can be used as follows
main()
{
printf("\nThis demonstrates user-defined functions");
displayname();
}
First the printf statement in the main program is executed. This is followed by the
call to the user-defined function displayname(), which results in execution of the statements
within the body of the function
In order to make use of a user-defined function, we need to establish three elements that
are related to functions.
1. Function definition
2. Function call
3. Function declaration
1. FUNCTION DEFINITION
Function name
Function type
MASC Programming in C
75
List of parameters
Local variable declaration
Function statements and
a return statement.
All the six elements are grouped into two parts
Function header( first three elements) and
Function body(second three elements)
We begin here, the general format of a function definition is
Function –type function-name(argument list)
{
local variable declarations;
executable statement1;
executable statement2;
----------
----------
return (expression);
}
All parts are not essential. Some may be absent. For example, the argument list and its
associated argument declaration parts are optional. The declaration of local variables is required
only when any local variables are used in the function.
Function header-> it consists of three parts: function type, the function name and the formal
parameter list
Name and type-> The function name is any valid c identifier. The function type specifies the
type value that the function is expected to return to the program calling the function.
Formal parameter list-> The parameter list declares the variables that will receive the data sent
by the calling program. They serve as input data to the function to carry out the specified task.
The parameters are also known as arguments.
The parameter list separated by commas and surrounded by parentheses. And there is
no semicolon after the closing parentheses. The declaration of parameter variables cannot be
combined. Ex( int a,b) is illegal.
A function need not always receive values from the calling program. In such cases
function have no formal parameters. It is empty, so we can use the keyword void between the
parentheses.
MASC Programming in C
76
Function body-> The function body contains the declarations and statements. The body
enclosed in braces, contains three parts.
1. Local declarations that specify the variables needed by the function
2. Function statements that perform the task of the function
3. A return statement that return the value evaluated by the function
A function does not return any value we can omit the return statement.
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. While it is possible to pass to
the called function any number of values, the called function can only return one value per call,
at the most we can have
return
or
return(expression)
The first, the 'plain' return does not return any value; it acts much as the closing brace of the
function. 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;
The second form of return with an expression returns the value of the expression. For example,
mul(x,y)
int x,y;
{
int p;
p = x*y;
return(p);
}
return(x*y);
Now by default all functions return int type data. If a function wants to return some other type of
value (can be float, character, string, structure, pointer, etc) whether it is user-defined or inbuilt
data type, it can be achieved by giving a type specifier in the function header.
MASC Programming in C
77
Example:
double sum(w,r)
char rait(c)
When a value is returned it is automatically cast to the function's type. In functions that do
computations using double, yet return int, the returned value will be truncated to an integer.
FUNCTION CALLS-> A function can be called by simply using the function name followed
by a list of actual parameters, if any, enclosed parentheses.
Note:
If the actual parameters are more than the formal parameters, the extra actual arguments
will be discarded.
On the other hand, if the actual are less than the formals, the unmatched formal
arguments will be initialized to some garbage.
Any mismatch in data types may also result in some garbage values.
FUNCTION DECLARATION-> All functions in c program must be declared, before they are
invoked. A function declaration consists of four parts
Function type(return type)
Function name
Parameter list
Terminating semicolon
Its general form is
Function type function name(parameter list);
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)
When the declared types do not match with the types in the function definition, compiler
will produce an error.
TYPES OF FUNCTIONS
A function may belong to any one of the following categories:
MASC Programming in C
78
1. Functions with no arguments and no return values.
2. Functions with arguments and no return values.
3. Functions with arguments and return values.
4. Functions that return multiple values.
5. Functions with no arguments and return values.
1. #include<stdio.h>
2. #include<conio.h>
3. void add(int x,int y)
4. {
5. int result;
6. result = x+y;
7. printf("Sum of %d and %d is %d.\n\n",x,y,result);
8. }
9. void main()
10. {
11. clrscr();
12. add(10,15);
13. add(55,64);
14. add(168,325);
15. getch();
16. }
MASC Programming in C
79
Program Output
A C function without any arguments means you cannot pass data (values like int, char etc) to the
called function. Similarly, function with no return type does not pass back data to the calling
function. It is one of the simplest types of function in C. This type of function which does not
return any value cannot be used in an expression it can be used only as independent statement.
Let’s have an example to illustrate this.
1. #include<stdio.h>
2. #include<conio.h>
3. void printline()
4. {
5. int i;
6. printf("\n");
7. for(i=0;i<30;i++)
8. {
9. printf("-");
10. }
11. printf("\n");
12. }
13. void main()
14. {
15. clrscr();
16. printf("Welcome to function in C");
17. printline();
18. printf("Function easy to learn.");
19. printline();
MASC Programming in C
80
20. getch();
21. }
Output
A C function with arguments can perform much better than previous function type. This type of
function can accept data from calling function. In other words, you send data to the called
function from calling function but you cannot send result data back to the calling function.
Rather, it displays the result on the terminal. But we can control the output of function by
providing various values as arguments. Let’s have an example to get it better.
#include<stdio.h>
MASC Programming in C
81
#include<conio.h>
void add(int x, int y)
{
int result;
result = x+y;
printf("Sum of %d and %d is %d.\n\n",x,y,result);
}
void main()
{
clrscr();
add(30,15);
add(63,49);
add(952,321);
getch();
}
Output
MASC Programming in C
82
This type of function can send arguments (data) from the calling function to the called
function and wait for the result to be returned back from the called function back to the calling
function. And this type of function is mostly used in programming world because it can do two
way communications; it can accept data as arguments as well as can send back data as return
value. The data returned by the function can be used later in our program for further
calculations.
#include<stdio.h>
#include<conio.h>
int add(int x, int y)
{
int result;
result = x+y;
return(result);
}
void main()
{
int z;
clrscr();
z = add(952,321);
printf("Result %d.\n\n",add(30,55));
printf("Result %d.\n\n",z);
getch();
}
MASC Programming in C
83
Logic of the function with arguments and return value.
We may need a function which does not take any argument but only returns values to the
calling function then this type of function is useful. The best example of this type of function is
“getchar()” library function which is declared in the header file “stdio.h”. We can declare a
similar library function of own. Take a look.
1. #include<stdio.h>
2. #include<conio.h>
3. int send()
4. {
5. int no1;
6. printf("Enter a no : ");
7. scanf("%d",&no1);
8. return(no1);
9. }
10. void main()
11. {
12. int z;
13. clrscr();
14. z = send();
15. printf("\nYou entered : %d.", z);
16. getch();
17. }
MASC Programming in C
84
We have used arguments to send values to the called function, in the same way we can
also use arguments to send back information to the calling function. The arguments that are used
to send back data are called Output Parameters. It is a bit difficult for novice because this type
of function uses pointer. Let’s see an example:
1. #include<stdio.h>
2. #include<conio.h>
3. void calc(int x, int y, int *add, int *sub)
4. {
5. *add = x+y;
6. *sub = x-y;
7. }
8. void main()
9. {
10. int a=20, b=11, p,q;
11. clrscr();
12. calc(a,b,&p,&q);
13. printf("Sum = %d, Sub = %d",p,q);
14. getch();
15. }
We have used arguments to send values to the called function, in the same way we can
also use arguments to send back information to the calling function. The arguments that are used
to send back data are called Output Parameters.It is a bit difficult for novice because this type of
function uses pointer. Let’s see an example:
1. #include<stdio.h>
2. #include<conio.h>
3. void calc(int x, int y, int *add, int *sub)
4. {
5. *add = x+y;
6. *sub = x-y;
7. }
8. void main()
9. {
10. int a=20, b=11, p,q;
11. clrscr();
12. calc(a,b,&p,&q);
13. printf("Sum = %d, Sub = %d",p,q);
MASC Programming in C
85
14. getch();
15. }
NESTING OF FUNCTIONS
C permits nesting of functions freely. Main can call function1, which calls functions2,
which calls function3 etc…. and so on. Consider the following program.
Void main()
{
void add();
add()
}
void add ()
{
printf(“ PROGRAMMING”);
add1();
}
void add1()
{
printf(“LANGUAGE”);
}
RECURSION
Eg:
Void main()
{
void add();
int a[10],i,n
for(I=1;I<=n;I++)
{
scanf(“%d”,&a[I]);
}
add(a,n);
}
void add( a,n)
{
int t,sum=0;
for(t=1;t<=n;t++)
{
sum=sum+a[t];
}
printf(“%d”,sum);
The scope of variable refers to visibility or accessibility of a variable. The life time of
a variable refers to the existences of a variable in memory.
1. automatic
2. external
3. static
4. register.
Automatic variables
MASC Programming in C
87
Automatic variables are declared inside a function. They are created as soon as a function
starts execution , and used within in the function. At end of the execution of the program, it
is destroyed.
Eg:
Main()
{
int age;
--
--
}
External variables
External variables are active throughout the program execution. They are also known as
global variables. External variables can be accessed by any function in the program. External
variables are declared outside a function.
Eg
#include<stdio.h>
int m;
void main()
{
m=100;
---
--
}
fn1()
{
m=m+100; }
Static Variables
The value of the static variables persists until the end of the program. Static
variable will not loss the storage location or their values when the control leaves the
function or blocks where in they are defined. The initial value assigned to a static must be a
constant or an expression Involving constants.
Eg:
void main()
{
int I;
void fn();
for (I=0;I<10;I++)
fn();
}
void fn()
MASC Programming in C
88
{
static int I=99;
I++;
Printf(“%d”,I);
}
Register Variables
Register variables are placed in one of the machine registers , instead of using
memory. Accessing the register is very fast compared to memory so frequently used
variables are placed in register. This will increase the execution speed.
Syntax:
Eg:
Register int k;
MASC Programming in C
89
UNIT -IV
Arrays are used to store large set of data and manipulate them but the disadvantage is
that all the elements stored in an array are to be of the same data type. If we need to use a
collection of different data type items it is not possible using an array.
When we require using a collection of different data items of different data types we can
use a structure. Structure is a method of packing data of different types. A structure is a
convenient method of handling a group of related data items of different data types.
DEFINING A STRUCTURE
struct tag_name
{
data type member1;
data type member2;
…
…
}
Example:
struct lib_books
{
char title[20];
char author[15];
int pages;
float price;
};
MASC Programming in C
90
the keyword struct declares a structure to holds the details of four fields namely title,
author pages and price. These are members of the structures. Each member may belong to
different or same data type. The tag name can be used to define objects that have the tag names
structure. The structure we just declared is not a variable by itself but a template for the
structure.
Note: Array vs structures
1. An array is a collection of same data elements of same type. Structure can have
elements of different types.
2. An array is derived data type whereas a structure is a programmer-defined one.
We can declare structure variables using the tag name any where in the program. It includes the
following elements
The keyword struct
The structure tag name
List of variable names separated by commas
A terminating semicolon
struct lib_books
{
char title[20];
char author[15];
int pages;
float price;
};
struct lib_books, book1, book2, book3;
Structures do not occupy any memory until it is associated with the structure variable such
as book1. The template is terminated with a semicolon. While the entire declaration is
considered as a statement, each member is declared independently for its name and type in a
MASC Programming in C
91
separate statement inside the template. The tag name such as lib_books can be used to declare
structure variables of its data type later in the program.
We can also combine both template declaration and variables declaration in one
statement, the declaration
struct lib_books
{
char title[20];
char author[15];
int pages;
float price;
} book1,book2,book3;
is valid. The use of tag name is optional for example
struct
{
…
…
…
}
book1, book2, book3 declares book1,book2,book3 as structure variables representing 3 books
but does not include a tag name for use in the declaration.
A structure is usually defines before main along with macro definitions. In such cases the
structure assumes global status and all the functions can access the structure.
As mentioned earlier the members themselves are not variables they should be linked to
structure variables in order to make them meaningful members. The link between a member and
a variable is established using the member operator ‘.’ This is known as dot operator or period
operator.
For example
MASC Programming in C
92
Book1.price
Is the variable representing the price of book1 and can be treated like any other ordinary
variable. We can use scanf statement to assign values like
scanf(“%s”,book1.file);
scanf(“%d”,& book1.pages);
Or we can assign variables to the members of book1
strcpy(book1.title,”basic”);
strcpy(book1.author,”Balagurusamy”);
book1.pages=250;
book1.price=28.50;
STRUCTURE INITIALIZATION
Like any other data type, a structure variable can be initialized at compile time.
Example:
Struct student
{
int id_no;
char name[20];
char address[20];
char combination[3];
int age;
}newstudent={12345, “kapildev” ,“ Pes college”, “Cse”, 19};
this initializes the id_no field to 12345, the name field to “kapildev”, the address field to “pes
college” the field combination to “cse” and the age field to 19. There is one to one
correspondence between the members and their initializing values.
Another method is to initialize a structure variable outside the function as shown below
Struct st_record
{ int weight;
Float height;
} student1={50,120.7}
Main()
{
struct st_record student2={60,124.4};
------
------
}
MASC Programming in C
94
C language does not permit the initialization of individual structure members within the
template. This initialization must be done in the declaration of the actual variables.
Rules for initializing structures
We cannot to initialize individual members inside the structure template
The order of values enclosed in braces must match the order of members in the structure
the remaining blank. The uninitialized members should be only at the end of the list
It is permitted to have a partial initialization. We can initialize only the first few
members and leave the remaining blank. The uninitialized members should be only at
the end of the list.
The uninitialized members will be assigned default values as follows
Zero for integer and floating point members
‘\0’ for characters and strings.
COPYING AND COMPARING STRUCTURE VARIABLES
Two variables of the same structure type can be compared the same way as
ordinary variables. If person 1 and person2 belong to the same structure, when the
following operations are valid.
Person1=person2
Person2 = person1
The following statements are invalid as c does not any logical operations on structure variables
Person1==person2
Person1!=person2
Eg:
Struct personal
{
char name[20];
int day;
float salary;
};
main()
{
struct personal p;
scanf(“%s %d%f”,p.name,&p.day,&p.salary);
printf(“%s %d%f”,p.name,p.day,p.salary);
}
ARRAYS OF STRUCTURE
MASC Programming in C
95
C language permits to declare an array of structure variable.
Struct booke
{
char name[20];
int price;
int pages;
}
struct book b[3];
output
Enter the bookname price and pages:
Maths 200 180
Enter the bookname price and pages:
English 100 135
Enter the bookname price and pages:
Tamil 80 100
For example:
struct mars
MASC Programming in C
96
{
int number;
float subject[3]
} student[2];
Here the member subject contains the three elements, subject[0], subject[1],
subject[2] These elements can be accessed using appropriate subscripts.
the structure student contains another structure date as its one of its members.
We can pass structures as arguments to functions. There are three methods by which the
values of a structure can be transferred from one function to another.
Pass each member of the structure as an actual argument of the function call
MASC Programming in C
97
When a structure is used as a parameter to a function, the entire structure is passed to the
function using the call by value method. Here also, there is no change made effects on the
parameter.
While using a structure as parameter, the type of the argument must match the type of
parameter in function and both must be declared as the type of structure.
#include<stdio.h>
Struct std
{
int no;
Float avg;
};
Void fun(struct std p);
Void main()
{
Struct std a;
a.no=14;
a.avg=120.45;
fun(a);
}
Void fun(struct std p)
{
Printf(“number is %d\n”,p.no);
Printf(average is %f”,p.avg);
}
UNIONS
Union is another compound data type like structure. Union is used to minimize memory
utilization. In structure each member has the separate storage location. but in union all the
members share the common place of memory. so a union can handle only one member
at a time.
The general form is:
union tagname
{
datatype member1;
datatype member2;
..
...
datatype member N;
};
MASC Programming in C
98
Where
union is the keyword.
tagname is any user defined data types.
For Ex:
union item
{
int m;
float p;
char c;
}
code;
This declares a variable code of type union item. The union contains three members each
with a different data type. However we can use only one of them at a time. This is because if
only one location is allocated for union variable irrespective of size. The compiler allocates a
piece of storage that is large enough to access a union member we can use the same syntax that
we use to access structure members. That is
code.m
code.p
code.c
are all valid member variables. During accessing we should make sure that we are
accessing the member whose value is currently stored.
For example a statement such as
code.m=456;
code.p=456.78;
printf(“%d”,code.m);
In effect a union creates a storage location that can be used by one of its members at a
time. When a different number is assigned a new value the new value super cedes the previous
members value. Unions may be used in all places where a structure is allowed. The notation for
accessing a union member that is nested inside a structure remains the same as for the nested
structure.
SIZE OF STRUCTURES
We normally use structures , union and arrays to create variables of large size.
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 the structure.
MASC Programming in C
99
Sizeof(struct x);
Will evaluate the no. of bytes required to hold all the members of the structure x.
BIT FIELDS
Bit field is a set of adjacent bits whose size can be from one to sixteen bits in
length. A word can be therefore we divided into a number of bit fields. The name and
size of the bit fields are defined using a structure .
Syntax:
Struct tag-name
{
datatype name1: bit_length;
datatype name2: bit_length;
…
…
datatype namen: bit_length;
the data type is either int or unsigned int or signed int and the bit length is the number
of bits used for the specified name.
Eg:
Struct pack
{
unsigned a:2;
int count;
unsigned b:3;
};
POINTERS
INTRODUCTION
In c a pointer is a variable that points to or references a memory location in which data is stored.
Each memory cell in the computer has an address that can be used to access that location so a
pointer variable points to a memory location we can access and change the contents of this
memory location via the pointer. It is a derived data type.
MASC Programming in C
100
Benefits of pointers:
UNDERSTANDING POINTERS
Definition: A pointer is a variable; it may contain the memory address of another variable.
Pointer can have any name that is legal for other variable. It is declared in the same manner like
other variables. It always denoted by *
A pointer is a variable whose value is also an address. Each variable has two attributes:
address and value. A variable can take any value specified by its data type. A pointer to an
integer is a variable that can store the address of that integer.
Assigning values directly to variables, we can indirectly manipulate a variable by
creating a variable called a pointer, which contain the memory address of another variable.
Value at address 30 4567-> address of the variable
The second variable contains the address of the first variable. 30 is the value at the address,
4567 is the address of the first variable.
ACCESSING THE ADDRESS OF A VARIABLE
The actual location of a variable in the memory is system dependent and therefore, the
address of a variable is not known to us. It can be done with the help of & operator. The
operator & immediately preceding a variable returns the address of the variable associated with
it.
For ex:
MASC Programming in C
101
S=&quality;
This would assign the address 5000(the location of quality) to the variable s. The & operator can
be named as ‘address of’.
Note: the & operator can be used only with a simple variable or an array element.
For defining a pointer variable ‘*’ symbol is used. A pointer variable must be declared
with * preceding the variable name. The general structure for declaring a pointer variable is
data_type*ptr_name;
For example
int*p
This declares the variable p as a pointer variable that points to an integer data type.
For example:
main()
{
int*p;
int i=30;
p=&i;
}
p 30
We can also use different pointers to point to the same data variable. Example
int x P1 P2 P3
int *p1=&x;
int *p2=&y;
int *p3=&z;
---- x
-------
Once the pointer is declared and assigned to the address of another variable. The variable
can be accessed through its pointers. This is done by using another unary operator * (asterisk),
usually known as the indirection operator. Another name for the indirection operator is the
dereferencing operator.
Example:
int *p;
x=15;
p=&x;
#include<stdio.h>
main()
{
/* local definition */
int a=22, *a;
MASC Programming in C
103
float b=2.25, *b;
/* statements */
a=&a; /* ‘&’ is a address of letter and it represents the address of the variable */
b=&b;
printf(“\n Value of a =%d”,*a);
printf(“\n value of b=%d”,*b);
}
Output
Value of a=22
Value of b=2.25
CHAIN OF POINTERS
Any pointer variable points to another pointer variable to access the content of other
memory location of variable is called chain of pointers.
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
For example:
Main()
{
int x, *p1,**p2;
X=100;
P1=&x; /* address of x*/
P2=&p1; /* address of p1 */
Printf(“%d”,**p2);
}
This code will display the value 100. Here p1 is declared as a pointer to an integer and p2 as a
pointer to a pointer to an integer.
Like other variables pointer variables can be used in expressions. For example if p1 and
p2 are properly declared and initialized pointers, then the following statements are valid.
y=*p1**p2;
sum=sum+*p1;
z= 5* - *p2/p1;
*p2= *p2 + 10;
MASC Programming in C
104
C allows us to add integers to or subtract integers from pointers as well as to subtract one
pointer from the other. We can also use short hand operators with the pointers p1+=; sum+=*p2;
etc.,
we can also compare pointers by using relational operators the expressions such as p1 >p2 ,
p1==p2 and p1!=p2 are allowed.
/*Program to illustrate the pointer expression and pointer arithmetic*/
#include< stdio.h >
main()
{
int ptr1,ptr2;
int a,b,x,y,z;
a=30;b=6;
ptr1=&a;
ptr2=&b;
x=*ptr1+ *ptr2 –6;
y=6*- *ptr1/ *ptr2 +30;
printf(“\nAddress of a +%u”,ptr1);
printf(“\nAddress of b %u”,ptr2);
printf(“\na=%d, b=%d”,a,b);
printf(“\nx=%d,y=%d”,x,y);
ptr1=ptr1 + 70;
ptr2= ptr2;
printf(“\na=%d, b=%d”,a,b);
}
POINTER TO ARRAYS
When an array is declared, the compile allocates a base address and sufficient amount of
storage to contain all the elements of the array in contiguous memory locations. The base
address is the location of the first element (index 0) of the array. The compiler also defines the
array name as a constant pointer to the first element. Suppose we declare an array x as follows
int x[5]=1,2,3,4,5}
Suppose the base address of x is 1000 and assuming that each integer requires two bytes,
the five elements will be stored as
MASC Programming in C
105
The name x is defined as a constant pointer pointing to the first element, x[0] and therefore the
value of x is 1000, the location where x[0] is stored. That is x=&x[0]=1000
If we declare p as an integer pointer, then we can make the pointer p to point to the array x by
the following assignment: p=x; This will be equivalent to p=&x[0];
Strings are treated like character arrays and therefore, they are declared and initialized as
follows:
Char str[5]=”good”;
The compiler automatically inserts the null character’\0’ at the end of the strings. C
supports an alternative method to create strings pointer variables of type char.
This creates a string for the literal and then stores its address in the pointer variable str.
The pointer str now points to the first character of the string “good” as shown in fig.
g o o d \0 str
ARRAY OF POINTERS
Pointer arithmetic
Array notation is form of relative addressing. The compiler treats the subscripts as a relative
offset from the beginning of the array. When a pointer variable set to the start of an array and is
incremented to find the next element, absolute addressing is being implemented.
MASC Programming in C
106
It has the following advantages:
Accessing arrays through pointers is marginally faster than using array notation.
Pointer allows us to perform certain functions that are externally difficult with array notation.
Program:
#include<stdio.h>
main()
{
int *a[3];
int b=10,c=20,d=30,i;
a[0] =&b;
a[1] =&c;
a[2] =&d;
for(i=0;i<3;i++)
{
Printf(“address=%u”,a[i]);
Printf(“value=%d”,*(a[i]));
}
}
b c d
10 20 30
a[0] a[1] a[2]
400 500 600
0 0 0
Output
Address=4000 value=10
Address=5000 value=20
Address=6000 value=30
POINTERS AS FUNCTION ARGUMENTS
When we pass addresses to function, the parameters receiving the addresses should be
pointers. The process of calling a function using pointers to pass the addresses of variable is
known as call by reference. (You know, the process of passing the actual value of variables is
known as call by value.) The function which is called by ‘reference’ can change the value of
the variable used in the call. Consider the following code:
Main()
MASC Programming in C
107
{
int x;
x = 20;
change(&x);
printf(“%d \n”,x);
}
change(p);
int *p;
{
*p = *p + 10;
}
The statement *p=*p+10 to the value stored at the address p. Since p represents the address of x,
the value of x is changed from 20 to 30. Therefore, the output of the program will be 30, not 20.
A function can return a single value by its name or return multiple values through pointer
parameters to the calling function.
The function large receives the address of the variables a and b, decides which one is
lager using the pointers x and y and then returns the address f its location. The returned value is
then assigned to the pointer variable p in the calling function. In this case, the address of b is
returned and assigned p and therefore the output will be the value of b, namely 20.
MASC Programming in C
108
POINTERS TO FUNCTIONS
A function has a type and an address location in the memory. It is therefore possible to
declare a pointer to a function , which can be used as an argument in another function.
A pointer to a function is described as follows.
Type (* fptr) ();
This tells the compiler that fptr is a pointer to a function, which returns type value. The
parentheses around *fptr are necessary.
We can make a function pointer to point to a specific function b simply assigning the name of
the function to the pointer.
For example
double mul (int, int);
double (*p1) ();
p1=mul;
Here p1 as a pointer to a function and mul is a function to which p1 points. To call the
function mul, we may now use the pointer p1 with the list of parameters, i.e.,
(*p1) (x,y) /* function call*/
We know the name of an array stands for the address of its zeroth element the same
concept applies for names of arrays of structures. Suppose item is an array variable of struct
type. Consider the following declaration:
struct products
{
char name[30];
int manufac;
float net;
}
item[2],*ptr;
this statement declares item as array of two elements, each type struct products and ptr as a
pointer data objects of type struct products, the following assignment statement is
MASC Programming in C
109
ptr=item;
would assign the address of zeroth element of product to ptr. The pointer ptr will now point to
item[0]. Its members can be accessed by using the following notation.
ptr- >name;
ptr- >manufac;
ptr- >net;
The symbol - > is called arrow pointer and is made up of minus sign and a greater than
sign. Note that ptr- > is simple another way of writing product[0].
When the pointer is incremented by one it is made to pint to next record ie item[1]. The
following statement will print the values of members of all the elements of the product array.
We could also use the notation (*ptr).number to access the number. The parenthesis around
*ptr are necessary because the member operator ‘.’ has a higher precedence than the operator *.
MASC Programming in C
110
UNIT -V
FILE MANAGEMENT
INTRODUCTION
File is a collection of records. It is used to store a large amount of data in a disk. Handling
of large volume of data through keyboards has the following disadvantages.
It is time consuming.
The entire data is last when either the program is terminated or when the power is
turned off.
A file is a group of related data, stored on the disk.
C supports a number of functions that have the ability to perform basic file operations,
which include:
1. Naming a file
2. Opening a file
3. Reading from a file
4. Writing data into a file
5. Closing a file
MASC Programming in C
111
fseek() Sets the position to a desired point in the file
If we want to store data in a file into the secondary memory, we must specify certain
things about the file to the operating system. They include the filename, data structure, purpose.
FILE*fp;
fp=fopen(“filename”,”mode”);
The first statement declares the variable fp as a pointer to the data type FILE. As stated earlier,
File is a structure that is defined in the I/O Library. The second statement opens the file named
filename and assigns an identifier to the FILE type pointer fp. This pointer, which contains all
the information about the file, is subsequently used as a communication link between the system
and the program.
The second statement also specifies the purpose of opening the file. The mode does this job.
In these statements the p1 and p2 are created and assigned to open the files data and
results respectively the file data is opened for reading and result is opened for writing. In case
the results file already exists, its contents are deleted and the files are opened as a new file. If
data file does not exist error will occur.
MASC Programming in C
112
CLOSING A FILE:
The input output library supports the function to close a file; it is in the following
format.
fclose(file_pointer);
A file must be closed as soon as all operations on it have been completed. This
would close the file associated with the file pointer.
Observe the following program.
….
FILE *p1 *p2;
p1=fopen (“Input”,”w”);
p2=fopen (“Output”,”r”);
….
…
fclose(p1);
fclose(p2)
The above program opens two files and closes them after all operations on them are
completed, once a file is closed its file pointer can be reversed on other file.
INPUT / OUTPUT OPERATIONS ON FILES
The getc and putc functions are analogous to getchar and putchar functions and handle
one character at a time. The putc function writes the character contained in character variable c
to the file associated with the pointer fp1. Ex putc(c,fp1); similarly getc function is used to read
a character from a file that has been open in read mode. c=getc(fp2).
The program shown below displays use of file operations. The data enter through the
keyboard and the program writes it. Character by character, to the file input. The end of the data
is indicated by entering an EOF character, which is control-z. The file input is closed at this
signal.
MASC Programming in C
113
while((c=getchar())!=EOF) /*get a character from key board*/
putc(c,f1); /*write a character to input*/
fclose(f1); /*close the file input*/
printf(“nData outputn”);
f1=fopen(“INPUT”,”r”); /*Reopen the file input*/
while((c=getc(f1))!=EOF)
printf(“%c”,c);
fclose(f1);
}
These are integer-oriented functions. They are similar to get c and putc functions and are
used to read and write integer values. These functions would be usefull when we deal with only
integer data. The general forms of getw and putw are:
putw(integer,fp);
getw(fp);
The fprintf and fscanf functions are identical to printf and scanf functions except that
they work on files. The first argument of theses functions is a file pointer which specifies the
file to be used.
Where fp id a file pointer associated with a file that has been opened for writing. The
control string is file output specifications list may include variable, constant and string.
fprintf(f1,%s%d%f”,name,age,7.5);
Here name is an array variable of type char and age is an int variable
the general format of fscanf is
fscanf(fp,”controlstring”,list);
This statement would cause the reading of items in the control string.
Example:
fscanf(f2,”5s%d”,item,&quantity”);
Like scanf, fscanf also returns the number of items that are successfully read.
An error may occur during input/output operations of a file. Some of the situations in
which the error occurs are as follows.
When reading the data beyond the EOF marks.
device over flow ( no space in disk)
Trying to use a file that has not been opened.
Trying to perform an operation on a file, when the file is opened for another type of
operation. For example it is not possible to perform.
Opening f file an invalid file name.
The two library functions feof and ferror is used to detect I/O errors in the files.
FEOF ():
This function is used to test for an end of file condition. This function has only
one argument. This argument is a FILE pointer. This function returns a non zero integer
value if all the data from the specified file has been read otherwise it returns zero for
example the statement
MASC Programming in C
116
if (feof(ptrf))
printf(“end of thefile\n”);
displays the message “ End of file “, on the reaching the end of condition.
ferror();
This function is used to report the status of the file specified. This function also
takes only one argument, FILE pointer. This function returns a non zero integer if an error
has been detected up to that point, during processing otherwise it will return zero for
example ,
if (ferror(ptrf)!=0)
printf(“there will be error\n”);
display the message” there will be error”, if the reading is not successful.
In random access mode, it is possible to access only a particular part of files. when we
are interested in accessing only a particular part of a file and not in reading the other
parts. The functions available for random access operations are:
fseek();
ftell();
rewind();
ftell() function
This function returns the current offset position in the file. For example as soon
as a file is opened, this function returns 0. This function is used to save the current position
of a file.
long int position = ftell(ptrf);
rewind () function
This function resets the pointer position to the beginning of the file. For example
the statement
rewind(ptrf);
position =ftell(ptrf);
Assigns the value o to position. The first byte in the file is numbered as o, second as 1
and so on.
MASC Programming in C
117
This function is used to read a file more than once, without having to
close and open the file.
fseek() function
Where the variable argc is an argument counter that counts the number of arguments on
the command line.
The argv is an argument vector and represents an array of character pointers that point to the
command line arguments.
To access the command line arguments, we must declare the main function and its parameter as
follows.)
MASC Programming in C
118
main(int argc, char *argv[])
{ ………..
………..
}
The first parameter in the command line is always the program name and therefore argv[0]
always represents the program name.
THE PREPROCESSOR
INTRODUCTION:
The preprocessor 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 Function
#define Define a macro substitution
#undef Undefine a macro
#include Specifies the file to be included
Three
#ifdef Test for a macro definition
#endif Specifies the end of $if
#ifndef Tests whether a macro is not defined
#if Test a compile-time condition
#else Specifies alternatives when #if test fails.
Categories of directives are
1. File Inclusion Directives
2. Macro Substitution Directives
3. Compiler Control Directives
FILE INCLUSION
An external file containing functions or macro definitions can be included as a part of a
program so that we need not rewrite those function or macro definitions. This is achieved by
the preprocessor directives
# include “filename”
MASC Programming in C
119
Where filename is the name of the file containing the required definitions or functions.
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.
SYNTAX.C contains syntax definitions.
TEST.C contains test functions.
STAT.C contains statistical functions.
Syntax: #include <filename>
Example: #include “TEST.C”
#define M 100
main()
{
-------
--------
--------
}
MACRO SUBSTITUTION
Macro substitutions is a process where an identifier in a program is replaced by
a predefined string composed of one or more tokens. The preprocessor accomplished this
task under the direction of #define statement. This statement, usually know as a macro-
definition (or simply called macro) takes the following
General form:
#define identifier string
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
Simple Macro substitution
Simple string replacement is commonly used to define constant.
Examples of definition of constants are:
#define COUNT 100
#define FALSE 0
#define SUBJECT 6
#define CAPITAL “DELHI”
Macros with Arguments
MASC Programming in C
120
The preprocessor permits us to define more complex and more useful form of
replacements. It takes the form:
#define identifier (f1, f2, .fn) string
The identifiers f1, f, …. 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)
Volume = CUBE (side);
Volume = (side * side * side);
Nesting of Macros
We can use one macro in the definition of another macro.
Example: #define M 5
#define N M+1
Undefining a Macro
A defined macro can be undefined, using the statement
#undef identifier
FILE INCLUSION
An external file containing functions or macro definitions can be included as a part of a
program so that we need not rewrite those function or macro definitions. This is achieved by
the preprocessor directives
# include “filename”
Where filename is the name of the file containing the required definitions or functions.
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.
SYNTAX.C contains syntax definitions.
TEST.C contains test functions.
STAT.C contains statistical functions.
#include <filename>
Example: #include “TEST.C”
#define M 100
main()
MASC Programming in C
121
{
-------
--------
--------
}
MASC Programming in C