0% found this document useful (0 votes)
22 views121 pages

2014 C Notes (Repaired) - 3

Uploaded by

t.ambika1991
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views121 pages

2014 C Notes (Repaired) - 3

Uploaded by

t.ambika1991
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 121

1

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 1967, Martin Richards developed a language called BCPL (Basic Combined


Programming Language) primarily for writing system software.

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.

Today, C is running under a variety of operating system and hardware platforms.


During 1970. C had evolved now known as “traditiono1 C”

1960 ALGOL International Group

1967 BCPL Martin Richards

B
1970 Ken Thompson

1972 TRADITIONAL C Dennis Ritchie

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.

C Language is a very powerful and flexible language.

 It consist of rich set of operators.


 Provides dynamic storage allocation.
 It supports a number of data types.
 C Language is a portable Language. A code written in c on a Particular machine can
be compiled and run on another machine.
 C is used for all kinds of applications because of its portability and efficiency.
 Its ability to extend itself.
 It is basically consists of a collection of functions that are supported by c library.
 C is a robust language which is used to write any complex program using of its rich
set of built in functions and operators.

BASIC STRUCTURE OF C PROGRAMS


A C program may consist of one or more following sections:

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.

3) Global declaration section – Global variables are declared in this section.

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.

CONSTANTS, VARIABLES AND DATA TYPES:

CHARACTER SET

A character denotes any alphabet, digit or symbols to represent information. The


following are the valid alphabets, numbers and special symbols permitted in C .

The charater in C are catgorised into the following categories:

1. Letters

2. Digits

3. Special characters

4. White spaces

Digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Letters: a, b,.…z A, B, ……...Z

Arithmetic Operators: +, -, *, /, %(Mod)

Special Characters:

, -comma ‘ -apostrophe

“ -quotation mark ! -exclamation mark

| -vertical bar / -slash

\ -backslash ~ -tilde

_ -underscore . –period

MASC Programming in C
4
; -semicolon : -colon

? -question mark $ - dollar sign

% - percent sign &-ampersand symbol

^-caret *-asterisk

- Minus sign +-plus sign

<-opening angle bracket >-closing angle bracket

(-left paranthesis )-right paranthesis

[-left bracket ]-right bracket

{-left brace }-right brace

#-number sign

TRIGRAPH CHARACTERS

Each trigraph sequence consists of three characters (two question marks followed by another
character)

Trigraph sequence Translation

??= # number sign

?? ( [ left bracket

??) ]Right bracket

??< { left brace

??> }Right brace

??! | vertical bar

?? / \ 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.

auto Double int struct

break else long switch


case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

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, VARIABLES AND DATA TYPES:


MASC Programming in C
6

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

Numeric constants Character constants

Integer Real Single character String


Constants Constants Constants Constants

Integer Constants

The integer constant is

 Whole Numbers (Eg. 25, 35, -25, -46 )


 Computer allocates only 2 bytes in memory.
 16th bit is sign bit. (if 0 then +ve value, if 1 then –ve value)

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

= 32767 (32767 Bits can be stored for integer constants)

 32768 is negative
 -32767 is minimum

There are 3 types of integers, namely decimal integer, octal integer and hexadecimal
integer.

(i) Decimal Integer Constant:

 0 to 9 E.g: 49, 58, -62, … (40000 cannot come bcoz it is > 32767)

(ii) Octal Integer Constant:

 0 to 7

MASC Programming in C
7
 Add “0” before the value.
 Eg.: 045, 056, 067

(iii) Hexadecimal Integer:

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

A real constant in fractional form must:

 Have at least one digit


 It must have a decimal point
 Could have positive or negative sign(default sign is positive)
 Must not have commas or spaces within it
 Allots 4 bytes in memory

Ex: +867.9, -26.9876, 654.0

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

Ex: +3.2e-4, 4.1e8, -0.2e+4, -3.2e-4

Single Character Constants

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

Ex: ’B’, ’l’, ’#’

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

Would print the value ‘a’.

Backslash character constants

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 is a quantity whose value changes during the execution of a program.

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

A variable name is any combination of 1 to 31 alphabets, digits or underscores. Some


compilers allow variable names whose length could be up to 247 characters.

 The first character in the variable name must be an alphabet


 It should begin with a letter. Some systems permit underscore as the first character.
 Uppercase and lowercase are significant.
 No commas or blanks are allowed within a variable name.
 No special symbol other than an underscore (as in net_sal) can be used in a variable
name.
 It should not be a keyword.
 White space is not allowed.

Ex.: si int e_hra pod_e_81

DATA TYPES

Data type allows the programmer to select the type appropriate to the needs of the
application as well as the machine.

C language data types can be broadly classified as

Primary (or fundamental ) data type


Derived data type
User-defined data type

Primary data types as:

1. Integral type

i. Integer types (signed and unsigned int,short int and long int)

ii. Character types (signed and unsigned char )

2. Floating point type (float, double, long double)

MASC Programming in C
10

A programming language is proposed to help programmer to process certain kinds of


data and to provide useful output. The task of data processing is accomplished by executing
series of commands called program. A program usually contains different types of data types
(integer, float, character etc.) and need to store the values being used in the program. C language
is rich of data types. A C programmer has to employ proper data type as per his requirement.

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.

Syntax: int <variable name>; like


int num1;
short int num2;
long int num3;

Example: 5, 6, 100, 2500.

Integer Data Type Memory Allocation

Floating Point Types:

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.

Syntax: float <variable name>; like


float num1;
double num2;
long double num3;

Example: 9.125, 3.1254.

Floating Point Data Type Memory Allocation

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.

Syntax: char <variable name>; like


char ch = ‘a’;

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

3. User defined type declaration

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;

User defined type declaration


In C language a user can define an identifier that represents an existing data type. The user
defined data type identifier can later be used to declare variables.

The general syntax is


typedef type identifier;
here type represents existing data type and ‘identifier’ refers to the ‘row’ name given to
the data type.
Example:
typedef int salary;
typedef float average;
Here salary symbolizes int and average symbolizes float. They can be later used to
declare variables as follows:
Units dept1, dept2;
Average section1, section2;
Therefore dept1 and dept2 are indirectly declared as integer datatype and section1 and
MASC Programming in C
13
section2 are indirectly float data type.
The second type of user defined datatype is enumerated data type which is defined as
follows.
Enum identifier {value1, value2 …. Value n};
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.
enum identifier V1, V2, V3, ……… Vn

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

The declaration does two things.

1. Tells the compiler the variables name.


2. Specifies what type of data the variable will hold.
a) Primary type declaration

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 Character signed char


Unsigned Character unsigned char
Signed Integer signed int (or) int

Signed Short Integer signed short int (or) short int (or) short

Signed Long Integer signed long int (or) long int (or) long

UnSigned Integer unsigned int (or) unsigned

UnSigned Short Integer unsigned short int (or) unsigned short

UnSigned Long Integer unsigned long int (or)


unsigned long

Floating Point float

Double Precision Floating Point double

Extended Double Precision Floating Point long double

b) User defined type declaration


The user defined data type identifier can later be used to declare variables.
The general syntax is

typedef type identifier;

here type represents existing data type and ‘identifier’ refers to the ‘row’ name given to
the data type.

Example:

typedef int salary;


typedef float average;

The second type of user defined datatype is enumerated data type which is defined as
follows.

Enum identifier {value1, value2 …. Value n};

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

enum identifier V1, V2, V3, ……… Vn

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 STORAGE CLASS


Variables in C have not only the data type but also storage class that provides
information about their location and visibility. The storage class divides the portion of the
program within which the variables are recognized.

/* Example of storage classes*/

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.

ASSIGNING VALUES TO VARIABLES

Variables are created for use in program statements


a)Assignment Statement:
Values can be assigned to variables using the assignment operator = as follows:
Syntax:
variable_name = constant;
Eg: initial_value = 0;
C permits multiple assignments in one line
Eg: initial_value = 0; final_value = 100;
It is possible to assign a value to a variable at the time the variable is declared.
data-type variable_name = constant;

Example: int final_value = 100;


char yes = ‘x’;
MASC Programming in C
17
The process of giving initial values to variables to called initialization.
Example: p = q = s = 0;
x = y = z = MAX;

b) Reading Data From Keyboard

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

Example: scanf(“%d”, &number);

c) Declaring Variable As Constant

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.

d) Declaring Variable As Volatile


The qualifier volatile used to tell explicitly the compiler that a variable’s value may be
changed at any time by some external sources.

Volatile int date;

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 AND EXPRESSIONS:

OPERATORS:

An operator is a symbol that specifies an operation to be performed on the operands. The


data items that operators act upon are called operands. Some operators require two operands
called binary operators, while other acts upon only one operand called unary operator. C has a
rich set of operators which can be classified as

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

+ Addition or Unary Plus

– Subtraction or Unary Minus

* 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

#include //include header file stdio.h


void main() //tell the compiler the start of the program
{
int numb1, num2, sum, sub, mul, div, mod; //declaration of variables
scanf (“%d %d”, &num1, &num2); //inputs the operands

sum = num1+num2; //addition of numbers and storing in sum.


printf(“\n Thu sum is = %d”, sum); //display the output

sub = num1-num2; //subtraction of numbers and storing in sub.


printf(“\n Thu difference is = %d”, sub); //display the output

}
.

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.

Floating point arithmetic

When an arithmetic operation is preformed on two real numbers or fraction numbers


such an operation is called floating point arithmetic. The floating point results can be truncated
according to the properties requirement. The remainder operator is not applicable for floating

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

Mixed mode arithmetic


When one of the operands is real and other is integer, the expression is called a mixed-
mode arithmetic expression. If either operand is of real type then only the real operation is
performed and the result is always a real number.

For ex: 15/10.0 = 1.5

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 less than

<= is less than or equal to

> is greater than

>= is greater than or equal to

== is equal to

!= is not equal to

A simple relational expression contains only one relational operator and takes the following
form.

exp1 relational operator exp2

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 AND

|| Logical OR

! Logical NOT

Logical AND (&&)

This operator is used to evaluate 2 conditions or expressions with relational operators


simultaneously. If both the expressions to the left and to the right of the logical operator is true
then the whole compound expression is true.
Example

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

Here the value of a + b is evaluated and substituted to the variable x.


In addition, C has a set of shorthand assignment operators of the form.

var oper = exp;


Here var is a variable, exp is an expression and oper is a C binary arithmetic operator. The
operator oper = is known as shorthand assignment operator

Example
x + = 1 is same as x = x + 1

The commonly used shorthand assignment operators are as follows


Shorthand assignment operators

Statement with simple Statement with


shorthand operator
assignment operator

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

Example for using shorthand assignment operator


.#define N 100 //creates a variable N with constant value 100
#define A 2 //creates a variable A with constant value 2

main() //start of the program


{
int a; //variable a declaration
a = A; //assigns value 2 to a

while (a < N) //while value of a is less than N


{ //evaluate or do the following
printf(“%d \n”,a); //print the current value of a
a *= a; //shorthand form of a = a * a
} //end of the loop
} //end of the program
.

Output
2
4
16

5. Increment and Decrement Operators

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.

Consider the following


m = 5;
y = ++m; (prefix)

In this case the value of y and m would be 6


Suppose if we rewrite the above statement as
m = 5;
y = m++; (post fix)
Then the value of y will be 5 and that of m will be 6. A prefix operator first adds 1 to the
operand and then the result is assigned to the variable on the left. On the other hand, a postfix
operator first assigns the value to the variable on the left and then increments the operand.

6. Conditional or Ternary Operator


The conditional operator consists of 2 symbols the question mark (?) and the colon (:)
The syntax for a ternary operator is as follows
exp1 ? exp2 : exp3
The ternary operator works as follows
exp1 is evaluated first. If the expression is true then exp2 is evaluated & its value becomes the
value of the expression. If exp1 is false, exp3 is evaluated and its value becomes the value of the
expression. Note that only one of the expressions is evaluated.

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.

./* Example : to find the maximum value using conditional operator)


#include
void main() //start of the program
{
int i,j,larger; //declaration of variables
printf (“Input 2 integers : ”); //ask the user to input 2 numbers
scanf(“%d %d”,&i, &j); //take the number from standard input and store it

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 AND

| Bitwise OR

^ Bitwise Exclusive

<< Shift left

>> Shift right

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

The Comma Operator


The comma operator can be used to separate the statement elements such as variables,
constants or expressions. And this operator is used to link the related expressions together, such
expressions can be evaluated from left to right most expressions is the value of combined
expression.

For example the statement

value = (x = 10, y = 5, x + y);

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:

for (n=1, m=10, n <=m; n++,m++)

In while loops

While (c=getchar(), c != ‘10’)

Exchanging values

t = x, x = y, y = t;

The size of Operator


The operator size of gives the size of the data type or variable in terms of bytes occupied
in the memory. The operand may be a variable, a constant or a data type qualifier.

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 :

main() //start of program


{
int a, b, c, d; //declaration of variables
a = 15; b = 10; c = ++a-b; //assign values to variables
printf (“a = %d, b = %d, c = %d\n”, a,b,c); //print the values
d=b++ + a;
printf (“a = %d, b = %d, d = %d\n, a,b,d);
printf (“a / b = %d\n, a / b);
printf (“a %% b = %d\n, a % b);
printf (“a *= b = %d\n, a *= b);
printf (“%d\n, (c > d) ? 1 : 0 );
printf (“%d\n, (c < d) ? 1 : 0 );
}

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

printf(“a %% b = %d\n”, a%b);

This program also illustrates that the expression

c>d?1:0
Assumes the value 0 when c is less than d and 1 when c is greater than d.

ARITHMETIC EXPRESSIONS

An expression is a combination of variables constants and operators written according to


the syntax of C language. In C every expression evaluates to a value i.e., every expression
results in some value of a certain type that can be assigned to a variable. Some examples of C
expressions are shown in the table given below.

Algebraic Expression C Expression


axb–c a*b–c

(m + n) (x + y) (m + n) * (x + y)

(ab / c) a*b/c

3x2 +2x + 1 3*x*x+2*x+1

(x / y) + c x/y+c

EVALUATION OF EXPRESSIONS

Expressions are evaluated using an assignment statement of the form

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;

The following program illustrates the effect of presence of parenthesis in expressions.

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

RULES FOR EVALUATION OF EXPRESSION

.First parenthesized sub expression left to right are evaluated.


.If parentheses are nested, the evaluation begins with the innermost sub expression.
. The precedence rule is applied in determining the order of application of operators in
evaluating sub expressions.
. The associability rule is applied when two or more operators of the same precedence level
appear in the sub expression.
. Arithmetic expressions are evaluated from left to right using the rules of precedence.
. When Parentheses are used, the expressions within parenthesis assume highest priority.

PRECEDENCE IN ARITHMETIC OPERATORS

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

TYPE CONVERSIONS IN EXPRESSIONS

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.

The following rules apply during evaluating expressions

All short and char are automatically converted to int then

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.

5. If one operand is long int and other is unsigned int then

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

Ratio = female_students / male_students

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.

Ratio = (float) female_students / male_students

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

OPERATOR PRECEDENCE AND ASSOCIATIVITY

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.

perator Description Associativity Rank


() Function Call
Left to Right 1
[] Array element reference
+ Unary plus
- Unary minus
++ Increment
-- Decrement
! Logical negation
Right to Left 2
~ One’s compliment
* Pointer reference
& Address
Sizeof Size of an object
(type) Type cast
* multiplication Left to Right 3
MASC Programming in C
31
/ Division
% Modulos
+ Addition
Left to Right 4
- Substraction
<< Left shift
Left to Right 5
>> Right shift
< Less than
<= Less than or equals
Left to Right 6
> Greater than
>= Greater than or equals
== Equality
Left to Right 7
!= inequality
& Bitwise AND Left to Right 8
^ Bitwise XOR Left to Right 9
| Bitwise OR Left to Right 10
&& Logical AND Left to Right 11
|| Logical OR Left to Right 12
?: Conditional Expression Right to Left 13
= Assignement Operator Right to Left 14
, Comma operator Left to Right 15

MASC Programming in C
32

UNIT-II

MANAGING INPUT AND OUTPUT OPERATIONS:

Introduction

One of the essential operations performed in a C language programs is to provide input


values to the program and output the data produced by the program to a standard output device.
We can assign values to variable through assignment statements such as x = 5 a = 0; and so on.
Another method is to use the Input then scanf which can be used to read data from a key board.
For outputting results we have used extensively the function printf which sends results out to a
terminal. There exists several functions in ‘C’ language that can carry out input output
operations. These functions are collectively known as standard Input/Output Library. Each
program that uses standard input / out put function must contain the statement.

# include < stdio.h >

at the beginning.

SINGLE CHARACTER INPUT OUTPUT:

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.

Program shows the use of getchar function in an interactive environment.

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

This is used to display a single character variable to standard output device.

Syntax:
Putc(Character variable);

Ex: char x;
Putc(x);

3. String input and output:

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.

The standard form of the gets function is

gets (str)

Here "str" is a string variable.

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)

Where str is a string variable.

Example program (Involving both gets and puts)

# include < stdio.h >


Void main ( )
{
char s [80];
printf (“Type a string less than 80 characters:”);
gets (s);
printf (“The string types is:”);
puts(s);
MASC Programming in C
35
}

FORMATTED INPUT OUTPUT STATEMENTS

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 scanf function has the general form.

Scanf (“control string”, arg1, arg2, arg3 ………….argn);

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

%c read a single character


%d read a decimal number
%e read a floating point value
%f read a floating point value
%g read floating point value
%h read short integer
%i read decimal, hexadecimal, octal integer
%o read octal integer
%s read string
%u read unsigned decimal integer
%x read hexadecimal integer

Rules for writing scanf() function

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

Reading integer numbers

The integers can be read through scanf statements with the field specification along with the
control string.

Syntax: scanf(“%wd”, &var(s));

Where % indicates the conversion specification


W is an integer number that is used to specify the field width of the
number to read.
d is the control string specification

Ex: scanf(%d %d”, &x, &y);

Reading real numbers


Like integers the field width for the real numbers cannot be specified, because the scanf()
function reads the real numbers using its format specification %f
Ex: scanf(“%f%f”,&a,&b);
22.65 23.98e-2
It will automatically read with the decimal point notation as well as exponential notation.
Reading character strings
The single character or string can be read through the scanf() statement with the field
specification along with the control string.
a) Reading a character
The specification for reading character is %wc
Syntax: scanf(“%wc”,var(s));
Where w specifies the system will wait up to the w th character to read
Ex: scanf(“%5c”,name);
b) Reading strings
The specification for reading string is %ws
Syntax: scanf(“%ws”,var(s));

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 :

Printf (“conversion string”, variable list);

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!

Conversion Strings and Specifiers:

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

Rules for writing printf() function

Place appropriate headings in the output


MASC Programming in C
38
The variable must be separated by commas and need not be preceded with & sign

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.

Provide blank space in between the numbers for better readability

Print special messages wherever requires in output.

Writing integer numbers


The integer data values can also be displayed using the field width specification in printf()
statement.
Syntax: printf(“%wd”, &var(s));
Where w is used to specify the minimum field width for the output
d is the control string specification

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

Writing real numbers


The writing o displaying of real numbers may be displayed in decimal point notation using the
field width specification.
Syntax: printf(“% w.p.f”, var(s));
Where w is the minimum number of position that are to be used for displaying
the output.
P specified the number of digits to be displayed after the decimal point.
Note: the default precision is 6 decimal places.
We can also output the real numbers in exponential form using the following
Syntax: printf(“%w.p.e”, var(s));
Where e is used to specify the exponential form.
Example:
The value of a = 28.4465
Printf(“%7.4f”, a) 2 8 . 4 4 6 5

MASC Programming in C
39
Printf(“%7.2f”,a) 2 8 . 4 4

Printf(“%10.2e”,a) 2 . 8 4 e + 0 1

Writing character strings


The single character or string can be write through the printf() statement with the field
specification along with the control string.
a) Writing a character
A single character can be displayed in a desired position using the following format %wc
Syntax: printf(“%swc”,var(s));
Where w is used to specify a desired position
S= 1 character displayed right justified
S=- character displaed left justified
S=1 is default value for s
b) Writing strings
The writing or displaying of string may be displayed in decimal point notation using the
following field width specification
%w.ps
Syntax: printf(“%w.psc”, var(s));
Where p specifies that only the first p characters of string are to be displayed.
Ex:
Name= harish kumar. A
Printf(“%15s”, name);

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

The C language programs presented until now follows a sequential form of


execution of statements. Many times it is required to alter the flow of the sequence of
instructions. C language provides statements that can alter the flow of a sequence of
instructions. These statements are called control statements. These statements help to jump from
one part of the program to another. The control transfer may be conditional or unconditional.

C language provide 4 general categories of control structures

1. Sequential structure – in which instructions are executed in sequence. ex: i=i+1;


j=j+1;

2. Selection structure – here the sequence of the instructions ae determined by using


the result of the condition.
Ex: if (a>b)
i=i+1;
Else
j=j+1;

3. Iteration structure- in which statements are repeatedly executed.


Ex: for (i=1; i<5; 1++)
{ i==+1; }
4. Encapsulation structure – in which the other compound structures are included

Ex: we can include an if statement in a for loop.

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.

The if statement may be implemented in different forms depending on the complexity of


the conditions to be tested.

1. Simple if statement
2. if...else statement
3. Nested if...else statement
4. else if ladder.

SIMPLE IF STATEMENT

The general form of a simple if statement is

if (test expression)
{
statement-block;
}
statement-x;

The statement-block may be a single statement or a group of statements. If the test


expression is true, the statement-block will be executed; otherwise the statement-block will be
skipped and the execution will jump to statement-x. remember, when the condition is true both
the statement-block and the statement-x are executed in sequence.

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

NESTING OF IF…ELSE STATEMENTS

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;

If the condition-1 is false statement-3 will be executed; otherwise it continues to


perform the second test. If the condition-2 is true, the statement-1 will be evaluated; otherwise
the statement-2 will be evaluated and then the control is transferred to the 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

This grading can be done using the else if ladder follows:

if (marks > 79)


grade = "Honours";
else
if (marks >59)
grade = "First Division";
else
if (marks > 49)
grade = "Second Division";
else
if (marks > 39)
grade = "Third division";
else
grade = "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

The general form of the conditional operator is as follows:


conditional expression ? expression1 : expression2
The conditional expression is evaluated first. If the result is nonzero, expression1 is
evaluated and is returned as the value of the conditional expression. Otherwise, expression2 is
evaluated and its value is returned.
MASC Programming in C
46
For example
if ( c == 'y' )
f = 1;
else
f = 0;
can be written as
f = ( c == 'y' ) ? 1 : 0;
Using of the conditional operator makes the code more concise and perhaps, more
efficient. However, the readability is poor. It is better to use if statements when more than a
single nesting of conditional operator is required.

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.

DECISION MAKING LOOPING (BRANCHING)

In looping, a sequence of statements are executed until some condition is satisfied


which is placed for termination of the loop. A program loop consists of two segments, one is
the body of the loop and the other known as the control statement. The control is tested
always for execution of the body of the loop.

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.

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

1. Setting and initialization of a counter.


2. Execution of the statements in the loop.
3. Test for a specified condition for execution of the loop.
4. Incrementing the counter.

The C language provides for three loop constructs for performing loop operations. They are:

1. The while statement.


2. The do statement.
3. The for statement.

MASC Programming in C
48
WHILE STATEMENT

This is one of the simplest looping structures. The basic format of the while statement
is

while (test condition)


{
body of the loop
}

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.

The general form of the for loop is:

for (initialization; test-condition ; increment)


{
body of the loop
}

The execution of the for statement is as follows:

1. Initialization of the control variables is done first, using assignment statements 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:

for( i = 0; i<10; i = i+1)


{
printf("%d",i);
}

The for loop will be executed 10 times. Each time a value equal to the current value of i will be
printed out.

Additional Features of for Loop

1. More than one variable can be initialized at a time in the for statement. For example:

for (p=1,n=0; n<18; ++n)

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

for (a=2,b=30; n <= m; n=n+1,m=m-1)


{
p = b/a;
printf("%d ",p);
}

4. It is also permissible to use expressions in the assignment statements of initialization and


increment sections.

For example

for (w = (a+b); w>0; w=w/2) is valid.

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 for loop

Nesting of loops i.e., one for statement within another for statement, is allowed in c.

For ex:

for( i = 0; i<10; i = ++i)


{
--------
---------
for( j = 0; j<10; j =++j)
{ inner loop outer loop
---------
}

--------
}

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

Existing a loop with break statement

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

while (-----) for (-------)


{ {-------
if (error) for(-------)
goto stop; {
--- -------
if (condition) if (error)
goto abc; goto error;
------ jump Exit Exit -------
------ within from from }
abc; loop loop two -----
---------- loops }
} errors;
stop; ---------
------- ---------
--------

MASC Programming in C
53
Jumping within and Existing from the Loops with goto Statement

Skipping a Part of a Loop:


 The Continue statement causes the loop to be continued with the next iteration after
skipping any statements in between.
 The continue statement tells the compiler, SKIP THE FOLLOWING STATEMENTS
AND CONTINUE WITH THE NEXT ITERATION”.
The format of the continue statement is
continue;

while (test-condition) do
{ {
------- -------
if (-------) if ( -----)
continue; continue;
--------- - --------
--------- --------
} }
while (test-condition);

for (initialization; test-condition; increment)


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

Jumping Out of the Program:

We can jump out of a program by using the library function exit( ).


---------
if (test-condition) exit(0);
---------
 The exit() function takes an integer value as its argument.
 Zero is used to indicate normal termination and a nonzero value to indicate termination
due to some error abnormal condition.
 The use of exit() function requires the inclusion of the header file <stdlib.h>

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.

ONE DIMENSIONAL ARRAY

A list of items can be given one variable name using only one subscript and such a
variable is called a single-subscripted variable or one-dimensional array.

In c single subscripted variable xi can be expressed as x[1],x[2],x[3],….x[n] . The subscript


can begin with number 0.

Declaration of arrays:
Like any other variable arrays must be declared before they are used.

The general form of declaration is:

type variable-name[size or subscript of the array];

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 .

for ex: int a[5];

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

for(i=0;i < 100;++i);


sum = sum + grades [i];

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:

An array can be initialized at either of the following stages:

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

type array_name[size]={list of values};

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.

The initialization of arrays in c suffers two draw backs


1. There is no convenient way to initialize only selected elements.
2. There is no shortcut method to initialize large number of elements.

Run time initialization

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

/* Program to count the no of positive and negative numbers*/


#include< stdio.h >
void main( )
{
int a[50],n,count_neg=0,count_pos=0,I;
printf(“Enter the size of the arrayn”);
scanf(“%d”,&n);
printf(“Enter the elements of the arrayn”);
for I=0;I < n;I++)
scanf(“%d”,&a[I]);
for(I=0;I < n;I++)
{
if(a[I] < 0)
count_neg++;
else
count_pos++;
}
printf(“There are %d negative numbers in the arrayn”,count_neg);
printf(“There are %d positive numbers in the arrayn”,count_pos);
}

Two-Dimensional Arrays

Two dimensional arrays are used in situation where a table of values needs to be stored
in an array.

C allows us to define such tables of items by using two-dimensional arrays.


Two- dimensional arrays are declared as follows:
type array_name [row-size][column-size];

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

[0][0] [0][1] [0][2]


Row 0 --> 310 275 365

[1][0] [1][1] [1][2]


Row 1- 310 275 365

MASC Programming in C
58
[2][0] [2][1] [2][2]
Row 2- 310 275 365

Initializing Two-dimensional Arrays

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

MULTI DIMENSIONAL ARRAY:

An array of three or more dimension are called multi-dimensional array.


The general form of a multi dimensional array is
Data type array-name[s1][s2]...[sn];
where si is the size of the ith dimension.
Some examples are
float sales[4][5][12];
int table[2][4][5][8];

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

Program to find the largest and smallest number in arrays

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

scanf ("%d", &arr[i]);

for (i=0;i<10;i++)
{
flag=1;

for (j=2;j<=(arr[i]/2); j++)


{
if (arr[i]%j==0)
{
flag=0;
break;

}
}
}

for (i=0;i<10;i++)
{
if (flag=1)

printf ("%d", arr[i]);

MASC Programming in C
62
}
}

Multiplication of Two Matrix

#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]):
}

CHARACTER ARRAYS AND STRINGS:

INTRODUCTION:

A string is a sequence of characters. Any sequence or set of characters defined within


double quotation symbols is a constant string. In C it is required to do some meaningful
operations on strings they are:

 Declaring and initializing string variables


 Reading strings from terminal
MASC Programming in C
63
 Writing strings to terminal
 Combining or concatenating strings
 Comparing string & checking whether they are equal
 Copying one string to another.

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

ASCII 77 121 32 97 103 10 32 105 115


code

character 2 ( t w o ) \0

ASCII 32 50 32 40 116 119 41 0 0


code

The last character is the null character having ASCII value zero.

DECLARING AND INITIALIZING STRING VARIABLES:

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 *

/*String.c string variable*/


#include < stdio.h >
main()
{
char month[15];
printf (“Enter the string”);
gets (month);
printf (“The string entered is %s”, month);
}
In this example string is stored in the character variable month the string is displayed in the
statement.

printf(“The string entered is %s”, month”);

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

Character string terminated by a null character ‘\0’.

READING STRINGS FROM THE TERMINAL:

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.

Reading a Line of Text:

In many applications it is required to process text by reading an entire line of text from the
terminal.

 Using getchar Functions

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

 Using gets Functions

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)

WRITING STRINGS TO SCREEN

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.

 Using putchar functions

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

 Using puts function


Another more convenient way of printing string values is to use the function puts
declared in the header<stdio.h>. It is invoked as under
Puts(str);
Where str is a string variable containing a string value. This print the value of the string
variable str and then moves the curser to the beginning of the next line on the screen.

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.

String operations (string.h)


C language recognizes that string is a different class of array by letting us input and
output the array as a unit and are terminated by null character. C library supports a large number
of string handling functions that can be used to array out many o f the string manipulations such
as:

 Length (number of characters in the string).


 Concatenation (adding two are more strings)
 Comparing two strings.
 Substring (Extract substring from a given string)
 Copy(copies one string over another)

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

strcmpi(“THE”,”the”); will return 0.

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

In the above example Robert is assigned to the string called name.

Other string functions

strlwr () function:
This function converts all characters in a string from uppercase to lowercase.

syntax strlwr(string);

For example:

strlwr(“EXFORSYS”) converts to Exforsys

strrev() function: This function reverses the characters in a string.


Syntax strrev(string);

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

For example strupr(“exforsys”) will convert the string to EXFORSYS.

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

/* Example program to use string functions*/


#include < stdio.h >
#include < string.h >
void main()
{
char s1[20],s2[20],s3[20];
int x,l1,l2,l3;
printf(“Enter the strings”);
scanf(“%s%s”,s1,s2);
x=strcmp(s1,s2);
if(x!=0)
{printf(“\nStrings are not equal\n”);
strcat(s1,s2);
}
else
printf(“\nStrings are equal”);
strcpy(s3,s1);
l1=strlen(s1);
l2=strlen(s2);
l3=strlen(s3);
printf(“\ns1=%s\t length=%d characters\n”,s1,l1);
printf(“\ns2=%s\t length=%d characters\n”,s2,l2);
printf(“\ns3=%s\t length=%d characters\n”,s3,l3);
}

MASC Programming in C
72

UNIT-IV

USER DEFINED FUNCTIONS

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.

WHAT IS FUNCTION IN C LANGUAGE?

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

So function in a C program has some properties discussed below.

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

NEED FOR USER-DEFINED 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

The use of functions in C serves many advantages:

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

Output of this program is:

This demonstrates user-defined functions


Result of displayname function call

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

ELEMENTS OF USER DEFINED FUNCTIONS

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

It is an independent program module that is specially written to implement the


requirements of the function. A function definition , also known as function implementation
shall include the following elements.

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

We could have also combined the last two statements as follows:

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.

Example of a simple function to add two integers

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

1. Functions with no arguments and no return value.

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

See all 9 photos

Logic of the functions with no arguments and no return value.

Output

2. Functions with arguments and no return value.

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

Logic of the function with arguments and no return value.

Output

MASC Programming in C
82

3.Functions with arguments and return value.

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.

4. Functions with no arguments but returns 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. }

Functions with no arguments and return values.

MASC Programming in C
84

5. Functions that return multiple values.

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

When a called functions in turn calls another function a process of “ chaining “


occurs. Recursion is a special case of this process , where a function calls itself .
Eg:
Main()
{
printf(“ this is the example for recursion”);
main();
MASC Programming in C
86
}

PASSING ARRAY & STRING TO FUNCTION

To pass an array to called function it is sufficient to maintain the name of the


array without any subscript and the size of the array as arguments for example
Sum(x,n);
Will pass all elements contained in the array x of the size n.

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, VISIBILITY AND LIFETIME OF VARIABLES

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:

Register datatype variablename;

Eg:
Register int k;

MASC Programming in C
89

UNIT -IV

STRUCTURES AND UNIONS


INTRODUCTION

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

The general format of a structure definition as follows

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.

DECLARING STRUCTURE VARIABLES

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

For example the statement,

struct lib_books book1,book2,book3;

declares book1,book2,book3 as variables of type struct lib_books each declaration has


four elements of the structure lib_books. The complete structure declaration might look like this

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.

ACCESSING STRUCTURE MEMBERS

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;

/* Example program for using a structure*/


#include <stdio.h>
void main()
{
int id_no;
char name[20];
char address[20];
char combination[3];
int age;
}newstudent;
printf(“Enter the student information”);
printf(“Now Enter the student id_no”);
scanf(“%d”,&newstudent.id_no);
printf(“Enter the name of the student”);
scanf(“%s”,&newstudent.name);
printf(“Enter the address of the student”);
scanf(“%s”,&newstudent.address);
printf(“Enter the cmbination of the student”);
scanf(“%d”,&newstudent.combination);
printf(“Enter the age of the student”);
scanf(“%d”,&newstudent.age);
printf(“Student informationn”);
MASC Programming in C
93
printf(“student id_number=%dn”,newstudent.id_no);
printf(“student name=%sn”,newstudent.name);
printf(“student Address=%sn”,newstudent.address);
printf(“students combination=%sn”,newstudent.combination);
printf(“Age of student=%dn”,newstudent.age);
}

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

Operations on individual members

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

Program to store 3 records in one structure


#include<stdio.h>
struct book
{
char name[20];
int price;
int pages;
}
struct book b[3];
void main()
{
int I;
for(I=1;I < =3;I++)
{
printf(“Enter the bookname price and pages:\”);
scanf(“%s%d%d”,&b[i].name,&b[i].price,&b[i].pages);
}
for(I=1;I < =3;I++)
printf(“%s%d%d”,&b[i].name,&b[i].price,&b[i].pages);
getch();
}

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

Maths 200 180


English 100 135
Tamil 80 100

ARRAYS WITHIN STRUCTURES

C permits the use of arrays as structure members

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.

STRUCTURE WITHIN A STRUCTURE:


A structure may be defined as a member of another structure. In such structures the
declaration of the embedded structure must appear before the declarations of other structures.
struct date
{
int day;
int month;
int year;
};
struct student
{
int id_no;
char name[20];
char address[20];
char combination[3];
int age;
structure date def;
structure date doa;
}oldstudent, newstudent;

the structure student contains another structure date as its one of its members.

STRUCTURES AND FUNCTIONS:

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

 Pass a copy of the entire structure to the called function

 Pass the structure as an argument using pointer.

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.

Program to passing a copy of entire structure to a function

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

 Pointers are more efficient in handling arrays and data tables.


 Pointers can be used to return multiple values from a function via function arguments.
 Pointers permit references to functions and thereby facilitating passing of function as
arguments to other functions.
 The use of pointer arrays to character strings results in saving of data storage space in
memory
 Pointers allow c to support dynamic memory management.
 Pointers provided an efficient tool for manipulating dynamic data structures such as
structures, linked lists, queues, stacks and trees.
 They increase the execution speed and thus reduce the program execution time.

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

First variable second variables

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.

Declaring pointer variables

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

INITIALIZATION OF POINTER VARIABLES

The process of assigning the address of a variable to a pointer variable is known as


initialization. Once the pointer variable has been declared we can use the assignment operator to
initialize the variable.
Example:
int quality;
int *p /* declaration */
p=&quality; /* Initialization */
We can also combine the initialization with the declaration
Example:
Int *p=&quality;
We could also define a pointer variable with an initial value of NULL or 0(zero)
Example:
MASC Programming in C
102
int *p=NULL;
int *p=0;
Pointers are flexible. We can make the same pointer to point to different data variables in
different statements. Example
int x,y,z,*p; x y z
-----
P=&x;
-------
P=&y;
----------
P=&z;
--------- p

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

Accessing variable though its pointers

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;

Variable Value Address


X 15 2001
P 2001 2005

Program to accessing through variable pointer

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

Address2 Address1 Value


P2 p1 Variable

Ptr -> Ptr -> memory

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.

POINTER EXPRESSIONS & POINTER ARITHMETIC

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

Element x[0] x[1] x[2] x[3] x[4]


value 1 2 3 4 5
address 1000 1002 1004 1006 1008

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

POINTERS AND CHARACTER STRINGS

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.

Ex: char *str=”good”;

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

The array notation can be accessed by two methods

 Standard array notation

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

Pointers give better control over array processing

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.

FUNCTIONS RETURNING POINTERS

A function can return a single value by its name or return multiple values through pointer
parameters to the calling function.

int *larger(int *, int *); /* prototype */


main()
{
int a=10;
int b=20;
int *p;
p=larger(&a,&b); /* function call */
printf(“%d”, *p);
}
int *larger(int *x, int *y)
{
if(*x>*y)
return(x); /* address of a */
Else
return(y) /* address of b*/
}

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

The above function call is equivalent to mul(x,y)

POINTERS AND STRUCTURES

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.

for(ptr=item; ptr< item+2;ptr++)


printf(“%s%d%f\n”,ptr- >name,ptr- >manufac,ptr- >net);

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

File operation functions in C

Function Name Operation

fopen() Creates a new file for use


Opens a new existing file for use
fclose() Closes a file which has been opened for use

getc() Reads a character from a file

putc() Writes a character to a file

fprintf() Writes a set of data values to a file

fscanf() Reads a set of data values from a file

getw() Reads a integer from a file

putw() Writes an integer to the file

MASC Programming in C
111
fseek() Sets the position to a desired point in the file

ftell() Gives the current position in the file

rewind() Sets the position to the beginning of the file

DEFINING AND OPENING A FILE

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.

The general format of the function used for opening a file is

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.

r open the file for read only.


w open the file for writing only.
a open the file for appending data to it.
Consider the following statements:

FILE *p1, *p2;


p1=fopen(“data”,”r”);
p2=fopen(“results”,”w”);

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.

#include< stdio.h >


main()
{
file *f1;
printf(“Data input output”);
f1=fopen(“Input”,”w”); /*Open the file Input*/

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

The getw and putw functions

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

/*Example program for using getw and putw functions*/


#include< stdio.h >
main()
{
FILE *f1,*f2,*f3;
int number I;
printf(“Contents of the data filenn”);
f1=fopen(“DATA”,”W”);
for(I=1;I< 30;I++)
{
scanf(“%d”,&number);
if(number==-1)
break;
putw(number,f1);
}
fclose(f1);
f1=fopen(“DATA”,”r”);
f2=fopen(“ODD”,”w”);
f3=fopen(“EVEN”,”w”);
while((number=getw(f1))!=EOF)/* Read from data file*/
{
if(number%2==0)
putw(number,f3);/*Write to even file*/
else
putw(number,f2);/*write to odd file*/
MASC Programming in C
114
}
fclose(f1);
fclose(f2);
fclose(f3);
f2=fopen(“ODD”,”r”);
f3=fopen(“EVEN”,”r”);
printf(“nnContents of the odd filenn”);
while(number=getw(f2))!=EOF)
printf(“%d%d”,number);
printf(“nnContents of the even file”);
while(number=getw(f3))!=EOF)
printf(“%d”,number);
fclose(f2);
fclose(f3);
}

Formatted Functions (fprintf() and fscanf())

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.

The general form of fprintf is


fprintf(fp,”control string”, list);

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.

/*Program to handle mixed data types*/


#include< stdio.h >
main()
MASC Programming in C
115
{
FILE *fp;
int num,qty,I;
float price,value;
char item[10],filename[10];
printf(“Input filename”);
scanf(“%s”,filename);
fp=fopen(filename,”w”);
printf(“Input inventory datann”0;
printf(“Item namem number price quantityn”);
for I=1;I< =3;I++)
{
fscanf(stdin,”%s%d%f%d”,item,&number,&price,&quality);
fprintf(fp,”%s%d%f%d”,itemnumber,price,quality);
}
fclose (fp);
fprintf(stdout,”nn”);
fp=fopen(filename,”r”);
printf(“Item name number price quantity value”);
for(I=1;I< =3;I++)
{
fscanf(fp,”%s%d%f%d”,item,&number,&prince,&quality);
value=price*quantity”);
fprintf(“stdout,”%s%d%f%d%dn”,item,number,price,quantity,value);
}
fclose(fp);
}

ERROR HANDLING DURING I/O OPERATIONS.

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.

RANDOM ACCESS FILES

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

After performing an input or output operation on a file, the pointer is shifted to


the next position in the file. the current position is the position at which data be read
from in an input operation or written to in an output operation.
fseek function is used to move the file position to a desired location the general
format of fseek function is
fseek(file-ptr, offset, from-where);

COMMAND LINE ARGUMENTS


It is a parameter supplied to a program when the program is invoked. This parameter
may represent a filename the program should process.
For ex
To copy the contents of a file named X_FILE to another one named Y_FILE then the
command line is
C-> PROGRAM X_FIEL Y_FILE
Where PROGRAM is the filename where the executable code of the program is stored.
This eliminates the need for the program to request user to enter the filenames during execution.
In C program main () function is denotes the beginning of the program. In fact main() can
take two arguments called argc and argv and the information contained in the command line is
passed on to the program through those arguments, when main is called up by the system.
For instance, the command line is as shown below,
argv[0]->PROGRAM
argv[1]->X_FILE
argv[2]->Y_FILE

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

COMPILER CONTROL DIRECTIVES:


While developing large program, you may face one or more of the following situations
1. You have included a file containing some macro definitions. It is not known whether a
particular macro.
2. Suppose a customer has two different types of computers and you are required to write a
program that will run on both the systems. You want to use the same program, although
certain lines of code must be different for each system.
3. You are developing a program (say for sales analysis) for selling in the open market.
4. Suppose you are in the process of testing your program, which is rather is large one. You
would like to have print calls inserted in certain place to display intermediate result and
messages in order to trace the flow of execution.
The C preprocessor offers a feature known as conditional compilation, which
can be used to switch on or off a particular line or group of lines in a program.
Situation 1:
This situation refers to the conditional definition of a macro.
#include “DEFINE.H”
#ifndef TEST
#define TEST1
#endif
…………
DEFINE.H is the header file that is supposed to contain the definition
of TEST macro. The directive,
#ifndef TEST
#ifndef and the corresponding #endif directive are left ‘active’
in the program. When the macro TEST is never to be defined, the following
code can be used.
#ifdef TEST
#undef TEST
#endif
----------
This ensures that even if TEST is defined in the header file, its
definition is removed.

MASC Programming in C

You might also like