0% found this document useful (0 votes)
6 views152 pages

PPS-course Notes

The document outlines the course 'Programming for Problem Solving' (Course Code: 20CS C01), detailing its outcomes, units, and content focused on C programming. It covers fundamental concepts such as computer components, programming languages, algorithms, data structures, and file operations, along with practical applications and examples. Additionally, it includes recommended textbooks and online resources for further learning.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views152 pages

PPS-course Notes

The document outlines the course 'Programming for Problem Solving' (Course Code: 20CS C01), detailing its outcomes, units, and content focused on C programming. It covers fundamental concepts such as computer components, programming languages, algorithms, data structures, and file operations, along with practical applications and examples. Additionally, it includes recommended textbooks and online resources for further learning.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 152

Course Code: 20CS C01

Course Title: PROGRAMMING FOR PROBLEM SOLVING

Course Outcomes: On Successful completion of the course, students will be able to


1. Identify and understand the computing environments for scientific and mathematicalproblems.
2. Formulate solutions to problems with alternate approaches and represent them using algorithms /
Flowcharts.
3. Choose data types and control structures to solve mathematical and scientificproblem.
4. Decompose a problem into modules and use functions to implement themodules.
5. Apply arrays, pointers, structures, and unions to solve mathematical and
scientificproblems.6.Develop applicationsusing file I/O.

UNIT –I
Introduction to computers and Problem Solving: Components of a computer, Operating system,
compilers, Program Development Environments, steps to solve problems, Algorithm, Flowchart /
Pseudocode with examples.Introduction to programming: Programming languages and generations,
categorization of high-level languages.Introduction to C: Introduction, structure of C program,
keywords, identifiers, Variables, constants, I/O statements, operators, precedence, and associativity.

UNIT –II
Introduction to decision control statements: Selective, looping, and nested statements.Functions:
Introduction, uses of functions, Function definition, declaration, passing parameters to functions,
recursion, scope of variables and storage classes, Case study using functions and control statements.

UNIT –III
Arrays: Introduction, declaration of arrays, accessing and storage of array elements, 1-dimensional
array, Searching (linear and binary search algorithms) and sorting (Selection and Bubble)
algorithms, 2-D arrays, matrix operations.Strings: Introduction, strings representation, string
operations withexamples. Case study using arrays.

UNIT –IV
Pointers: Understanding computer’s memory, introduction to pointers, declaration pointer variables,
pointer arithmetic, pointers and strings, array of pointers, dynamic memory allocation, advantages,
and drawbacks of pointers.Structures: Structure definition, initialization and accessing the members
of a structure, nested structures, structures and functions, self-referential structures, unions, and
enumerated data types.

UNIT-V
Files: Introduction to files, file operations, reading data from files, writing data to files, error
handing during file operations.Preprocessor Directives: Types of preprocessor directives, examples.

1
Text Books:
1.M.T. Somashekar “Problem Solving with C”, 2nd Edition, Prentice Hall India Learning Private
Limited 2018

2.AK Sharma, “Computer Fundamentals and Programming”, 2nd Edition,


UniversityPress,20183.Pradeep Deyand Manas Ghosh, “Programming in C”, Oxford Press,2nd
Edition,2017
Suggested Reading:

1.Byron Gottfried, Schaum’s Outline of Programming with C”, Mc Graw-Hill.

2.Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, Prentice Hall ofIndia.

3.E. Balaguruswamy, Programming in ANSI C, Tata McGraw-Hill.

4.Reema Tharaja “Introduction to C Programming”, Second Edition, OXFORDPress,2015.

Online Resources:
1.https://www.tutorialspoint.com/cprogramming/index.htm.
2.https://onlinecourses.nptel.ac.in/noc18-cs10/preview

Syllabus:https://www.cbit.ac.in/wp-content/uploads/2019/04/CBIT-CSE-R20-I-and-II-Semesters-
Syllabus-2020-21.pdf

2
UNIT I
COMPONENTS OF A COMPUTER

There are 5 main computer components that are given below:

o Input Devices
o CPU
o Output Devices
o Primary Memory
o Secondary Memory

The operations of computer components are given below:

1) Inputting: It is the process of entering raw data, instructions and information into the
computer. It is performed with the help of input devices.

2) Storing: The computer has primary memory and secondary storage to store data and
instructions. It stores the data before sending it to CPU for processing and also stores the
processed data before displaying it as output.

3) Processing: It is the process of converting the raw data into useful information. This process
is performed by the CPU of the computer. It takes the raw data from storage, processes it and
then sends back the processed data to storage.

4) Outputting: It is the process of presenting the processed data through output devices like
monitor, printer and speakers.

5) Controlling: This operation is performed by the control unit that is part of CPU. The control
unit ensures that all basic operations are executed in a right manner and sequence.

Operatingsystem:
3
In the Computer System (comprises of Hardware and software), Hardware can only understand
machine code (in the form of 0 and 1) which doesn't make any sense to a naive user.

We need a system which can act as an intermediary and manage all the processes and resources
present in the system.

An Operating System can be defined as an interface between user and hardware. It is


responsible for the execution of all the processes, Resource Allocation, CPU management, File
Management and many other tasks.

The purpose of an operating system is to provide an environment in which a user can execute
programs in convenient and efficient manner.

Compilers:

o A compiler is a translator that converts the high-level language into the machine
language.
o High-level language is written by a developer and machine language can be understood
by the processor.
o Compiler is used to show errors to the programmer.
o The main purpose of compiler is to change the code written in one language without
changing the meaning of the program.
o When you execute a program which is written in HLL programming language then it
executes into two parts.
o In the first part, the source program compiled and translated into the object program (low
level language).
o In the second part, object program translated into the target program through the
assembler.

4
Compilation Process in C:

The compilation is a process of converting the source code into object code. It is done with the
help of the compiler. The compiler checks the source code for the syntactical or structural errors,
and if the source code is error-free, then it generates the object code.

The c compilation process converts the source code taken as input into the object code or
machine code. The compilation process can be divided into four steps, i.e., Pre-processing,
Compiling, Assembling, and Linking.

The preprocessor takes the source code as an input, and it removes all the comments from the
source code. The preprocessor takes the preprocessor directive and interprets it. For example,
if <stdio.h>, the directive is available in the program, then the preprocessor interprets the
directive and replace this directive with the content of the 'stdio.h' file.

The following are the phases through which our program passes before being transformed into an
executable form:

o Preprocessor
o Compiler
o Assembler
o Linker

5
Preprocessor

The source code is the code which is written in a text editor and the source code file is given an
extension ".c". This source code is first passed to the preprocessor, and then the preprocessor
expands this code. After expanding the code, the expanded code is passed to the compiler.

Compiler

The code which is expanded by the preprocessor is passed to the compiler. The compiler
converts this code into assembly code. Or we can say that the C compiler converts the pre-
processed code into assembly code.

Assembler

The assembly code is converted into object code by using an assembler. The name of the object
file generated by the assembler is the same as the source file. The extension of the object file in
DOS is '.obj,' and in UNIX, the extension is 'o'. If the name of the source file is 'hello.c', then the
name of the object file would be 'hello.obj'.

Linker

Mainly, all the programs written in C use library functions. These library functions are pre-
compiled, and the object code of these library files is stored with '.lib' (or '.a') extension. The
main working of the linker is to combine the object code of library files with the object code of
our program. Sometimes the situation arises when our program refers to the functions defined in
other files; then linker plays a very important role in this. It links the object code of these files to
our program. Therefore, we conclude that the job of the linker is to link the object code of our
6
program with the object code of the library files and other files. The output of the linker is the
executable file. The name of the executable file is the same as the source file but differs only in
their extensions. In DOS, the extension of the executable file is '.exe', and in UNIX, the
executable file can be named as 'a.out'. For example, if we are using printf() function in a
program, then the linker adds its associated code in an output file.

ProgramDevelopmentEnvironments:

The development environment helps the developers to develop the application or product using
a set of processes and programming tools.
An development environment provides developers an interface and convenient view of the
development process which includes writing code, testing the same and packaging the build so
that it can be deployed.
Ex:
Microsoft Visual Studio
Turbo C/C++
Dev C/C++
Flowchart:
Flowchart is a diagrammatic representation of sequence of logical steps of a program.
Flowcharts use simple geometric shapes to depict processes and arrows to show relationships
and process/data flow.
Flowchart Symbols
Here is a chart for some of the common symbols used in drawing flowcharts.

Symbol Symbol Name Purpose

Used at the beginning and end of the algorithm to


Start/Stop
show start and end of the program.

Indicates processes like mathematical operations.


Process

Input/ Output Used for denoting program inputs and outputs.

7
Stands for decision statements in a program,
where answer is usually Yes or No.
Decision

Shows relationships between different shapes.


Arrow

Connects two or more parts of a flowchart, which


On-page Connector are on the same page.

Connects two parts of a flowchart which are


Off-page Connector spread over different pages.

Examples:
Here is a flowchart to calculate the average of two numbers.

Here is a flowchart to calculate the even or odd number.


8
Programming Language

As we know, to communicate with a person, we need a specific language, similarly to


communicate with computers, programmers also need a language is called Programming
language.

Before learning the programming language, let's understand what is language?

What is Language?

Language is a mode of communication that is used to share ideas, opinions with each other.
For example, if we want to teach someone, we need a language that is understandable by both
communicators.

What is a Programming Language?

A programming language is a computer language that is used by programmers (developers)


to communicate with computers. It is a set of instructions written in any specific language ( C,
C++, Java, Python) to perform a specific task.

A programming language is mainly used to develop desktop applications, websites, and


mobile applications.

Types of programming language

1. Low-level programming language

Low-level language is machine-dependent (0s and 1s) programming language. The processor
runs low- level programs directly without the need of a compiler or interpreter, so the programs
written in low-level language can be run very fast.

9
Low-level language is further divided into two parts -

i. Machine Language

Machine language is a type of low-level programming language. It is also called as machine


code or object code. Machine language is easier to read because it is normally displayed in
binary or hexadecimal form (base 16) form. It does not require a translator to convert the
programs because computers directly understand the machine language programs.

The advantage of machine language is that it helps the programmer to execute the programs
faster than the high-level programming language.

ii. Assembly Language

Assembly language (ASM) is also a type of low-level programming language that is designed for
specific processors. It represents the set of instructions in a symbolic and human-
understandable form. It uses an assembler to convert the assembly language to machine
language.

The advantage of assembly language is that it requires less memory and less execution time to
execute a program.

2. High-level programming language

High-level programming language (HLL) is designed for developing user-friendly software


programs and websites. This programming language requires a compiler or interpreter to
translate the program into machine language (execute the program).

The main advantage of a high-level language is that it is easy to read, write, and maintain.

High-level programming language includes Python, Java, JavaScript, PHP, C#, C++,
Objective C, Cobol, Perl, Pascal, LISP, FORTRAN, and Swift programming language.

A high-level language is further divided into three parts -

i. Procedural Oriented programming language

Procedural Oriented Programming (POP) language is derived from structured programming and
based upon the procedure call concept. It divides a program into small procedures
called routines or functions.

Procedural Oriented programming language is used by a software programmer to create a


program that can be accomplished by using a programming editor like IDE, Adobe
Dreamweaver, or Microsoft Visual Studio.

The advantage of POP language is that it helps programmers to easily track the program flow
and code can be reused in different parts of the program.

The advantage of POP language is that it helps programmers to easily track the program flow

10
and code can be reused in different parts of the program.

Example: C, FORTRAN, Basic, Pascal, etc.

ii. Object-Oriented Programming language

Object-Oriented Programming (OOP) language is based upon the objects. In


this programming language, programs are divided into small parts called objects. It is used
to implement real-world entities like inheritance, polymorphism, abstraction, etc in the program
to makes the program resusable, efficient, and easy-to-use.

The main advantage of object-oriented programming is that OOP is faster and easier to execute,
maintain, modify, as well as debug.

Note: Object-Oriented Programming language follows a bottom-up approach.

Example: C++, Java, Python, C#, etc.

iii. Natural language

Natural language is a part of human languages such as English, Russian, German, and
Japanese. It is used by machines to understand, manipulate, and interpret human's language. It is
used by developers to perform tasks such as translation, automatic summarization, Named
Entity Recognition (NER), relationship extraction, and topic segmentation.

The main advantage of natural language is that it helps users to ask questions in any subject and
directly respond within seconds.

3. Middle-level programming language

Middle-level programming language lies between the low-level programming language and
high-level programming language. It is also known as the intermediate programming language
and pseudo-language.

A middle-level programming language's advantages are that it supports the features of high-level
programming, it is a user-friendly language, and closely related to machine language and human
language.

Example: C, C++ language

Introduction to C:

The C Language is developed by Dennis Ritchie for creating system applications that directly
interact with the hardware devices such as drivers, kernels, etc.

C programming is considered as the base for other programming languages, that is why it is
known as mother language.

It can be defined by the following ways:

11
1. Mother language
2. System programming language
3. Procedure-oriented programming language
4. Structured programming language
5. Mid-level programming language

structure of C program:

Documentation Section :
This section consists of a set of comment lines useful for documentation. Though comments are
not necessary in a program, they help users to understand the program better.

Link(Preprocessor) and Definition Section:


This section contains header files which begin with a # symbol and are extended with .h. They
are also known as preprocessor directives used to include header files in a C program. Examples
of preprocessor statements are
#include<stdio.h>
#include<math.h>
Symbolic Constants are included using # define. For example to define the value of PI, the
statement is:
#define PI 3.14159

Global Declaration Section:


Global declaration section is used to define variables that would be used in more than one
function. Such variables are called global variables and they must be declared before the main( )
function.

The main( ) Function:


All C programs must contain main( ) function. Further there must be only one main( ) function.
main( ) denotes the starting of a C program.

Braces :
All C programs incorporate a set of curly braces { }. Execution of the program begins at the
opening brace { of the main( ) function and ends at its closing brace }.

12
Declaration Part:
This part is used to declare all the variables, arrays functions etc. used in the C program.
Initialization along with declaration can also be done here.

Executable Part :
This part of the program consists of a set of executable statements such as Input/ Output
statements, arithmetic statements, control statements etc. It can also include comment statements
which are ignored by the compiler (non-executable). The declaration part and the executable part
must be within opening and closing braces.

Every statement in the declaration part and executable part ends with a semicolon.

Subroutine Section:
This section is optional and consists of all the user-defined functions called in the main( )
function.
Example:
/*Program to find the area of a square*/
#include <stdio.h>
main()
{
float side, area ;
side=5;
area=side*side;
printf(“\nArea of a square=%f’,area);
}
Output:
Area of a square = 25.0

C KEYWORDS:
There are some reserved words in C, called keywords. All the keywords have standard pre-
defined meanings and can be used only for the purpose intended. All keywords must be written
in lowercase. They cannot be used as user-defined identifiers. The standard keywords are listed
below
auto break case char const continue default do double else
enum extern float for goto if int longregister return
short signed sizeof static struct switch typedef union unsigned void
volatile while

IDENTIFIERS:
• Identifiers refer to the names of program elements such as variables, functions and arrays.
• Identifiers are sequence of characters chosen from the set A–Z, a–z, 0–9, and _
(underscore).
• C is a case sensitive language so that ALFA and Alfa are different.
• The underscore symbol _ is generally in the middle of an identifier (embedded).
• Identifiers may be of reasonable length of 8–10 characters though certain computers
allow up to 32 characters.
• Identifier names must start with an alphabet or underscore followed by letters, digit or a
combination of both.
• C has a list of keywords that cannot be used anywhere other than that predefined in the

13
language i.e., you can’t have a variable named int. Also one must follow the practice of
choosing names for variables which indicate the roles of those variables in the program.

VARIABLES:
A variable is an identifier used to store a single data item. This data could be a numerical
quantity or a character constant. During execution of the program, data must be assigned to the
variable. Therefore a variable can take different values at different times during the execution of
the program. The data stored in the variable can be accessed any time, by referring to the
variable name.

The rules for naming a variable are the same as those for an identifier.
They are :
1. Variable names generally begin with a letter followed by letters, digits underscore or a
combination of all.
2. No special character except the underscore symbol ( _ ) is allowed. Underscore is generally
embedded in a variable name to make it more readable.
3. Maximum length of a variable name should not exceed 32 characters. Normally the length
must not exceed 8 characters since many compilers treat the first 8 characters as significant.
4. C variables are case sensitive, so that Counter, counter and COUNTER are 3 different
variables.
5. C keywords cannot be used as variable names.
6. White spaces are not allowed in a variable name.
7. Appropriate variable names must be chosen to indicate their role in the program.

CONSTANTS:
Any fixed value that does not change during the execution of a program is known as a constant.
C consists of several types of constants.

Types of C constants:
C constants can be divided into two categories :
• Primary Constants
• Secondary Constants

These constants can further be divided as follows :

14
Integer Constants :
Integers and real constants are numbers and are generally referred to as numeric constants.
An integer constant consists of a sequence of digits and is an integer-valued number. There are 3
types of integer constants depending on the number system.
They are:
• Decimal (base 10)
• Octal (base 8)
• Hexadecimal (base 16)

Real Constants:
Quantities which are represented by numbers with fractional part are called real or floating point
constants.
(a) A real constant must have at least 1 digit.
(b) It must have a decimal point.
(c) It can be either positive or negative.
(d) No commas or blanks are allowed within a real constant.

Character Constants:
(a) A character constant is a single character within single quotes.
(b) The maximum length of a character constant is 1.
(c) Arithmetic operations are possible on character constant since they too represent integer
values.
(d) C also recognizes all the backlash character constants (Escape sequences) available.

Note that the character constant ‘2’ is not the same as the number 2. Every character has an
equivalent integer value known as the ASCII code. Some character constant & their equivalent
ASCII values are as below :
‘A’ = 65
‘B’ = 66
‘a’ = 97
‘0’ = 48
‘1’ = 49

String Constants:
A string constant consists of zero or more number of characters enclosed within double quotes.
The characters within quotes could be digits, characters, special characters and blank spaces.
Ex: "Red", "Rs.20.25", " "

Note that ‘A’ is not equal to “A” since a string constant containing a single character does not
have a corresponding integer value. In fact it contains two characters, the specified character
followed by a null character represents by \0.

Coding constants:
There are 3 types of code constants used in programs:
• Literal constants
• Defined constants
• Memory constants

15
Literal constants: are used to specify data, which cannot be changed.
For example: x = y + 1 ;
In this statement 1 is a literal constant.

Defined Constants: are constants that can be defined using a preprocessor command #define.
This constant is placed at the beginning of a program since it is a preprocessor command.
For example :
# define MAX 30
The defined constants make the program easily modifiable and enhance the understandability of
the program.

Memory Constants: use a c type qualifier called const, to indicate that the data specified is a
constant and that it cannot be changed.
Its general format is :
const Datatype identifier = value ;
For example :
const float pi = 3.14159 ;
defines a memory constant pi of float type with a value of 3.14159.

I/O statements:
In C programming you can use scanf() and printf() predefined function to read and print data.
i) printf
This function is used for displaying the output on the screen i.e the data is moved from the
computer memory to the output device.

Syntax:
printf(“format string”, arg1, arg2, …..);

In the above syntax, 'format string' will contain the information that is formatted. They are the
general characters which will be displayed as they are .
arg1, arg2 are the output data items.

Example: Demonstrating the printf function


printf(“Enter a value:”);

printf will generally examine from left to right of the string.


The characters are displayed on the screen in the manner they are encountered until it comes
across % or \.
Once it comes across the conversion specifiers it will take the first argument and print it in the
format given.
ii) scanf
scanf is used when we enter data by using an input device.

Syntax:
scanf (“format string”, &arg1, &arg2, …..);

16
The number of items which are successful are returned.

Format string consists of the conversion specifier. Arguments can be variables or array name and
represent the address of the variable. Each variable must be preceded by an ampersand (&).
Array names should never begin with an ampersand.

Example: Demonstrating scanf


intavg;
float per;
char grade;
scanf(“%d %f %c”,&avg, &per, &grade):

scanf works totally opposite to printf. The input is read, interpret using the conversion specifier
and stores it in the given variable.
The conversion specifier for scanf is the same as printf.
scanf reads the characters from the input as long as the characters match or it will terminate.
The order of the characters that are entered are not important.
It requires an enter key in order to accept an input.

OPERATORS IN C :
C provides several operators for elementary arithmetic operations like addition, subtraction,
multiplication, division, residue-modulo (the operation that gives the remainder after division of
one integer by another) and logical manipulations.
An operator is a symbol used for certain type of manipulations, logical or mathematical. The
data on which the operators act are called operands. An expression is a valid combination of
operators and operands that results in a value.
For example in the expression : 12*5
* is the multiplication operator,
12 and 5 are the operands.

Operators may be classified into 4 categories namely


(i) unary
(ii) Binary
(iii) Ternary
(iv) Special
Unary Operators:
Operators that operate on a single operand are known as unary operators. The unary operators
always precede the operand. The different unary operators available in C are :
(i) Unary plus (+)
17
(ii) Unary minus (–)
(iii) Increment (++)
(iv) Decrement (– –)
(v) Logical NOT (!)
(vi) Bitwise complement (~)
(vii)Address (&)
The unary minus operator is used for negation. It change sign of the quantity on its right i.e., it
multiplies its only operand by –1. Similarly unary plus multiplies its operand by +1.

Binary Operators:
Binary operators operate on two operands. They are classified into five categories as follows:
(i) Arithmetic
(ii) Relational
(iii) Logical
(iv) Assignment
(v) Bitwise

Ternary Operators:
Ternary operators act on three data elements. The conditional operator (?:) is a ternary operator

Special Operators:
Special operators include operators such as comma (,) and sizeof.

ARITHMETIC OPERATORS:
C supports five arithmetic operators.

Operator Purpose
+ Addition
– Subtraction or (unary)
* Multiplication
/ Division
% Remainder after integer division

There is no exponentiation operator available in C. However, the library function pow( ) is


provided to compute exponentiation.

Dividing one integer by another integer is called as integer division, which truncates, the
fractional part. The % operator gives the remainder of such a division.
For example, consider a = 10, b = 3.
a % b gives 10% 3 giving the result 1
and a/b gives 10/3 giving the result 3

% operator can have only integer operands.

Mixed-mode Arithmetic operations consists of a real and an integer operand. If one of the

18
operand is real, the result is also real.
For example :
15/2.0 = 7.5
However 15/2 = 7

RELATIONAL OPERATORS:
The relational operators are used to form relational expressions, representing conditions that are
either true or false. The result of the expression is an integer. Further, false is represented by zero
value and true in represented by non-zero value. For example expressions
50<200
x>y
are called relational expressions whose value can be either true or false i.e., 50<200 is true.
when x = 10 and y = 5, x > y is true. There are 6 relational operators in C.
They are:
Operator Meaning
> greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal to
!= Not equal to

Consider 3 integer variables, i = 1, j = 2 and k = 7


Expression Logical value Integral value
(i) 10.5<=12 true 1
(ii) i==20 false 0
(iii) 5>20 false 0
(iv) (i+j)>=k false 0
(v) (j+k+1)>(i+5) true 1
(vi) k!=7 false 0

In the 4th and 5th example given above the expressions contain arithmetic expression. Thus in
the relational expression (i+j)>=k, the arithmetic expression i+j will be evaluated and then the
result is compared with k. These arithmetic operators have higher priority over relational
operators. The relational operators are used to compare two quantities in decision statements.

LOGICAL OPERATORS:
Logical operators are used to combine two or more logical expressions. There are 3 logical
operators in C. They are logical AND, logical OR and logical NOT

Operator Meaning
! logical NOT
&& logical AND
|| logical OR

• The result of a logical AND is true only if both operands are true. The result is false if
either operand is false.
• The result of a logical OR is false only if both operands are false. The result is true if
either operand is true.
19
• C also consists of the unary operator ! (not) that negates the value of a logical expression
i.e., it causes true expression to become false and vice-versa. This operator is known as
logical NOT operator. Further like relational operators, a logical expression results in
zero or non-zero value depending on whether it is false or true.

Consider i = 8, x = 5.1, c = ‘a’ where i is an integer variable, x is a floating point variable and c
is a char variable.
Expression Logical value Integer value
(i>6)&&(c==’a’) true 1 (or non-zero)
i<=6||(c==’b’) false 0
i>=6&&(c==97) true 1
!(i<=4) true 1

ASSIGNMENTOPERATORS
The assignment operator ‘=’ is used to assign the value of a variable, constant or
expression to a variable. The syntax is :

variable=variable/constant/expression;

For example :
x=10; /*x is assigned a value 10 */

b=x; /*The value of x is assigned to b i.e.,10*/

sum=a+b; /*Thesumofa&bwhichis20isassignedtosum*/

C also provides abbreviated or shorthand assignment operators. They are of the


form:
Variable operator = Expression;

For example the statement


n = n + 5;
can be written using shorthand assignment operator as :
n + = 5;

Where += is the abbreviated or compound operator. In the above case + = means add
5ton.Thedifferentshorthandassignmentoperatorsare:

Normal Shorthand Operator Meaning


assignment assignment
n=n+1 n += 1 += sum & assign
n = n – 50 n –= 50 –= subtract & assign
n = n*10 n *= 10 *= multiply & assign
n=n/6 n /= 6 /= divide & assign
20
n=n%5 n %= 5 %= find modulo and assign

The priority of the above operators + =, –=, *=, /= and % = is the same as theassignment
operator.
Difference between = = and = operator
1. == is an equality or relational operator, used for comparison = is an
assignmentoperator which assigns the resultant value on its right hand side to the
variableon its left hand side.
2. == operator does not change the value of the variable on the left hand side.However
= operator does change the value of the variable on the left hand side of the
assignmentstatement.
INCREMENT/DECREMENTOPERATOR
Theincrement and decrement operators are specifically used in C or C++.
They are not generally available in other languages.
Increment operator ++ is used to increment the value of the variable by 1.Decrement
operator – – is used to decrement the value of the variable by 1.
They are also called as unary operators Fig. 2.14. Since they operate on only one
dataelement.

Operator Meanings Usage


++ Increment a++ or ++ a means a = a + 1
–– Decrement a – – or – – a means a = a – 1

Consider the following statements :


int x,y;
:
x =10;
y = ++x;
x is increment by 1 so that x and y will have a value 11. Similarly in

int a, b;
:
a = 5;
b = --a;
will result in the value of a and b to be 4.

Post-increment operator ++ is written to the right of its operand as in n ++; which is the
21
same as n = n + 1;
Post-decrement operator – – is also written to the right of its operand as in n—
, and is equivalent to n = n – 1;
Pre-increment and pre-decrement operators ++ and – – are always placed to theleft of the
operand as follows :
++n; /* same as n =n+1*/
––n; /* same as n =n–1*/

The behavior of post and pre–increment or decrement operators are the same when used
with a single operand. However, they behave differently when the operand is embedded in an
expression.
Difference between postfix & prefixoperators
(i) The pre-increment or decrement operator first increments or decrements the value
of its operand by 1 and then assigns the resulting value to the variable onthe left
hand side. For example,consider
int a, b; a =
15;
b = ++a;
In this example, the value of a is incremented by 1 and then this value 16 is assigned
tob.
(ii) The post increment or decrement operator first assigns the value to the variable on
the left hand side and then increments or decrements the operand by 1. Consider the
following program segment:
intm,n; n =
2;
m = n– –;

The value of n is first assigned to m and then it is decremented i.e., n becomes 1, but
value of m is 2.
In subscripted variables.
a[j++]=5;
is equivalent to a[j]=5;
j++;
Similarly, a[++i]=5;
is equivalent to i = i+1;
a[i] = 5;
Consider the statement
x = n++/2;
where n = 5. After execution, n is 6 but x gets the value 5/2 which is 2.

22
TERNARY OPERATOR (CONDITIONALOPERATOR)
C consists of a very special operator known as ternary or conditional operator and
isrepresented by ? : The syntax is
expression1 ?expression2 : expression3;

and general usage is as


variable = expression1 ? expression2 :expression3;

Since it contains 3 expressions it is called ternary. The above statement is evaluated as


follows :
(i) Expression1 is evaluatedfirst.
(ii) If it is true or non-zero, expression2 is evaluated and its value assigned to the
variable.
(iii) If expression1 is false or zero, expression3 is evaluated and its value assigned to
thevariable.
(iv) Eitherexpression2orexpression3willbeevaluated,butneverboth.

Consider the following statements :


n = 5;
m = 10;
big = (n > m) ? n :m;
Here n> m is evaluated first giving the result ‘false’. Since the expression is false the
value of m is assigned to big. Thus big = 10. The same can be written in the form of if else
statement as follows :
if(n > m) big = n; else
big = m;
Some more examples :
(10 == 8) ? 2:4 //resultis4since10isnotequalto8
(10>8) ? 2:4 //result is 2 since 10 is greater than 8
(10==8+3) ? 2:4 //result is 4 since 10 is not equal to11

SPECIALOPERATORS
C consists of some special operators. The operators, , &,*,.and , are called special
operators in C.
Operator Description
, Comma operator
sizeof size in bytes

23
& address of operand
* accessing value at that address
. dot operator
 arrow operator

The CommaOperator
(i) The comma operator is used to separate a list of expressions given as a single
expression.
(ii) Thelistswithcommasarealwaysevaluatedfromlefttoright.
(iii) The value of the right most expression becomes the final value of the combined
expression.
(iv) The syntax is of the form:
variable =exp1,exp2, .................. expn;

For example, the statement:


result = (a = 5, b = 10, a + b);
 firstassigns5toai.e.,a=5
 nextassigns10tobi.e.,b=10
 andfinallyassignsthevalueofa+bi.e.,10+5=15toresult.
(v) The comma operator needs parentheses, since it has the lowest precedence
compared to all otheroperator.
(vi) The comma operator is used in for( ) loops to separate more than one expression. It

for (exp1a, exb1b; exp2; exp3a, exp3b)statement;


is possible to write:
(vii) It can also be used in while loops to separate more than one expression. For
example:
while(textchar=getchar( ),textchar ! = ‘\n’)
putchar(textchar);
In this example, the end condition for input is checked first and then it waits for
input of a character. The program terminates as soon as the enter key is pressed.
The sizeofoperator
(i) Thesizeofoperatorreturnsthesizeinbytesoftheoperandontheright.
(ii) The syntaxis

sizeof(n)

where n can be a variable, a constant or a data type.


(iii) Itisaunaryoperatorwhichassociatesfromrighttoleft.

24
(iv) The size of operator is used to determine the size of an array or a structure. It is
alsousedfordynamicmemoryallocationofvariables.

Example 2.30
/* Program to show usage of sizeof operator
*/ #define STRING “Usage of sizeof
Operator” #include <stdio.h>
main()
{
char a = ‘p’;
clrscr();
printf(“\n The size ofcharis : %d \n”,sizeof(char));
printf(“\n Therefore the size of char ais : %d \n”,sizeof(a));
printf(“\n However the size of‘p’is : %d \n”,sizeof(‘p’));
printf(“\nSTRING : \”%s\”
\n”,STRING); printf(“\n The number of bytes in STRINGis : %d
\n”,sizeof STRING); printf(“\n The size ofshortis : %d\n”,sizeof(short));
printf(“\n The size ofintis : %d\n”,sizeof(int));
printf(“\n The size oflongis : %d\n”,sizeof(long));
printf(“\n The size offloatis : %d\n”,sizeof(float));
printf(“\n The size ofdoubleis : %d
\n”,sizeof(double)); getch();
}
Output
The size ofcharis 1
Therefore the size of charais 1
However the size of‘p’is 2
STRING : “Usage of sizeof
Operator” The number of bytes inSTRINGis 25
The size ofshortis 2
The size ofintis 2
The size oflongis 4
The size offloatis 4

25
The size ofdoubleis 8

BITWISEOPERATORS:
C supports a powerful set of operators known as bitwise operators. The bitwise
operatorsare used for controlling and interacting with hardware and also for
manipulating data at the bit level.
The Bitwise operators are as shown below table.

Operator Description
& bitwise AND
| bitwise OR
^ bitwise exclusive OR
<< shift left
>> shift right
~ one’s complement

(i) Bitwise operators cannot be applied to float or double. They can be applied to
integersonly.
(ii) All except ~ operator are used in binary operations. Tilde (~) is a unaryoperator.
(iii) Bitwise operators perform bitwise logical AND, bitwise logical OR,
bitwiseexclusiveOR,bitwiseshiftleftandshiftright.
(iv) Bitwise operators work on their operands bit by bit starting from the least
significant bit. The truth table for logical bitwise operations is as shown in below
table.Trueistakentobe1andfalseaszero.

Operand1 Operand2 x & x|y x^y


x y y
1 1 1 1 0
1 0 0 1 1
0 1 0 1 1
26
0 0 0 0 0

Bitwise ANDOperator:
TheBitwise AND operator is represented by the symbol & (ampersand). The
result of AND operation is 1 if both operand bits are 1, otherwise, the result is zero.
Further,theANDoperationisdoneonthebinaryrepresentationoftheoperands.

4 & 5 results in 4
i.e., binary value of4is 0100
binary value of5is 0101
AfterANDoperation 0100 i.e.,4

Bitwise & operator is used to check whether a particular bit is 0 or 1. Consider the
number 21. Its bit pattern is represented by
0001 0101
To check whether the fourth bit is 0 or 1, AND operation must be done withanother
operand whose value must be 24 i.e., 16, which can be represented as00010000.
Therefore, 00010101
0001 0000 & mask
0001 0000

result shows that 4thbit is 1 since the resultant value is 16.


Bitwise OROperator
The bitwise OR Operator is represented by the symbol | (vertical bar). It is also known
as inclusive OR. The result of a bitwise OR operation is 1 if either or bothcorresponding bits
has a value 1. Otherwise it is zero.

Consider x = 4, y = 9
xis 00000100 4
yis 00001001 9
x|yis 00001101 i.e.,13
The bitwise OR is used to set a particular bit on (set to 1).

Bitwise Exclusive OROperator


This operator is represented by the symbol ^ and is known as Exclusive ORoperator.
The result of a bitwise XOR operation is 1 if one of the corresponding bits is 1, otherwise it
is0.
Consider the values x = 4, y = 9.
xis 00000100 4
yis 00001001 9

27
x^yis 00001101 i.e.,13
Bitiwse ComplementOperator
The complement operator is represented by ~(tilde) and is also known as one’s
complement operator. It inverts all the bits. Thus all the zeros become 1 and all the ones
become 0.

Consider x = 4
x is 00000100
~x is 11111011
Bitwise ShiftOperator
The shift operators are used to push the bit patterns to the right or left by thenumber of bits given
by theirright operand
The Right shift operator is of the form :
expression>>n

where n is the number of bit positions to be shifted. However the rightmost n bitsare
lost. Further the left most n bits which are vacant will be filled with zero. For
examplex>>4shiftsallbitsby4placestotheright.
The Left shift operator is of the form
expression<<n
where n is the number of bit positions to be shifted. The left most n bits are lost andthe
rightmost n bits are vacated and filled with zeros.
Shift operators are used for multiplication and division by 2. For example, the statement
x = y << 2;
shifts two bit to the left in y. Further the value of x is equal to y multiplied by 22.
Similarly, the statement
x = y >> 2;

shifts the bits in y to the right by 2. Also the value of x is equal to y divided by 22.

PRECEDENCE OF ARITHMETICOPERATORS:

Any arithmetic expressionis evaluated according to the rule of precedence of operators.


For example in the expression.
4*5/2

Evaluation takes place from left to right i.e.,


First 4 is multiplied by 5 and the result 20 is divided by 2.
The order in which the expression is evaluated depends on the hierarchy ofoperators

28
Precedence level Operators Associativity
1 () Left to right
2 unary Right to left
3 *,/,% Left to right
4 +, – Left to right

 In an arithmetic expression, the expression enclosed in parentheses is


evaluatedaccording to theprecedence.
 In the case of nested parentheses, the inner most parentheses is evaluated first and
the evaluation continuesoutwards.
 When two operators with the same precedence are encountered, the evaluation is
done from left to right as inthe above example. This is known an associativity.
 Parenthesescanbeusedtochangetheorderofevaluation

PRECEDENCE AND ASSOCIATIVITY OFOPERATORS


The precedence of operators comes into effect whenever there are more than one
operators involved in the expression to be evaluated.
 Therearemanylevelsofprecedence,eachcontainingoneormoreoperator.
 Theoperatorwiththehighestprecedencelevelisevaluatedfirst.
 Operators in the same level are evaluated either from left to right or right to
leftdepending on their associativity. Associativity determines the operations to be
performed from right and from left, when several operators of the same priority
level exist in the sameexpression.
 The order of precedence and associativity of operators are two very important
aspectsofevaluation.Forexample,considerthestatement
(a < 10&& a + b > 15)

where a = 20, b = 1.
The order of evaluation will be as follows.
(i) Since + operator has the highest priority in the expression, addition is computed first:
a < 10 && 21 > 15

(ii) Both the relational operators have higher priority compared to the logical operator &&.
Here the associativity of relational operators has to be considered which is leftto right.
Thus:
20 <10 && 21 > 15
False && True

(iii) Theresultoflogical&&isfalseor0.

29
A complete operator precedence summary is listed in Fig. 2.20, from highest to lowest.

Operator Operator category Associativity Rank


() Function call/Innermost parenthesis L to R 1
[] Array element
 . member selection
+ unary plus R to L 2
– unary minus
++ increment
–– decrement
! logicalNot
~ One's
* complement
& Pointer reference
sizeof Addressof
(type)
size of a variable
cast operator
*, /, % Multiplication, division and remainder L to R 3
+, – Addition and subtraction L to R 4
<< , >> Left shift and Right shift L to R 5
<,<=, >,>= Relational operators L to R 6
==, != Equality operators L to R 7
& Bitwise AND L to R 8
^ Bitwise XOR (Exclusive OR) L to R 9
Bitwise OR (Inclusive OR) L to R 10
&& Logical AND L to R 11
|| Logical OR L to R 12
?: Conditional operator R to L 13
=, Assignment R to L 14
*=, /=, operators
%=, += and
–= Abbreviated
&=, ^=, assignment
!=, <<=, >>= operators
, Comma operator L to R 15

30
UNIT II

Selective control statements:


1. if
2. if else
3. nested if else
4. else if ladder
5. switch
Iterative control statements :
1. for loop,
2. while loop,
3. do while loop

Simple if statement
1. Simple if statement is used to make a decision “yes or no”, based on the available choice. It
has the following form:

Syntax:
if ( condition )
{
stmt block;
}
stmt-x;

In this syntax,

• if is the keyword.
• <condition>is a relational expression or logical expression or any expression that returns
either true or false. It is important to note that the condition should be enclosed within
parentheses and no terminator (;) at the end.
• The stmt block can be a simple statement or a compound statement or a null statement.
• stmt-x is any valid C statement.

31
2. flow chart for simple if.
Whenever simple if statement is encountered, first the condition is tested. It returns either
true or false. If the condition is false, the control transfers directly to stmt-x without considering
the stmt block. If the condition is true, the control enters into the stmt block. Once, the end of
stmt block is reached, the control transfers to stmt-x

3. Example Program for if statement:


#include<stdio.h>main()
{
int number;
printf("enter a number\n"); scanf("%d",&number);
if(number%2==0)
printf("Even number\n");

Output:
enter a number
12
Even number
if - else statement

if…else statement is used to make a decision based on two choices. It has the following
form:

1. Syntax:
if(condition)
{
true stmt block;
}
else
{
false stmt block;
}
Stmt-x;

In this syntax,
• if and else are the keywords.
32
• <condition>is a relational expression or logical expression or any expression that returns
either true or false. It is important to note that the condition should be enclosed within
parentheses .
• The true stmt block and falsestmtblock are simple statements or compound statements or null
statements.
• stmt-x is any valid C statement.

2. Flow chart:

Whenever if...else statement is encountered, first the condition is tested.


It returns either true or false.
If the condition is true, the control enters into the true stmt block.
Once, the end of true stmt block is reached, the control transfers to stmt-x without
considering else-body.

If the condition is false, the control enters into the false stmt block by skipping true stmt
block.
Once, the end of false stmt block is reached, the control transfers to stmt-x.

3. Program for if else statement:


/* odd or even */

#include <stdio.h>
main()
{
int x;
printf("Enter a number\n");
scanf("%d",&x);
if(x%2==0)
printf("EVEN\n");
else
printf("ODD\n");
}

Output: enter a number


33
11
ODD

More examples on if else

/* largest of two numbers */


#include <stdio.h>
main()
{
Int x,y,big;

if(x>y)
big=x;
else
big=y;
printf(“BIG=%d\n”,big);
}

/* absolute value */
#include <stdio.h>
main()
{
int x;
printf("Enter a integer\n");
scanf("%d",&x);
if(x<0)
printf("absolute value is %d\n",-x);
else
printf("absolute value is %d\n",x);
}

/* quadrant position */
#include <stdio.h>
main()
{
Int x,y;
printf("Enter the coordinate\n");
scanf("%d%d",&x,&y);
if(x>0 && y>0)
printf("FIRST QUADRANT\n");

if(x<0 && y>0)


printf("SECOND QUADRANT\n");

if(x<0 && y<0)


printf("THIRD QUADRANT\n");

if(x>0 && y<0)


printf("FOURTH QUADRANT\n");
34
}

/* alphabet or not */
#include <stdio.h>
main()
{
charch;
printf("Enter a character\n");
scanf("%c",&ch);
if(ch>= 'a' &&ch<='z')
printf("alphabet\n");
else
printf("not a alphabet\n");
}

/* vowel or not */
#include <stdio.h>
main()
{
char ch;
printf("Enter a alphabet\n");
scanf("%c",&ch);
if(ch== 'a' || ch=='e'||ch=='i'||ch=='o'||ch=='u')
printf("vowel\n");
else
printf("not a vowel\n");
}

Nested if—else statement

Nested if…else statement is one of the conditional control-flow statements. If the body of if
statement contains at least one if statement, then that if statement is called as ―Nested if…else
statement‖. The nested if…else statement can be used in such a situation where at least two
conditions should be satisfied in order to execute particular set of instructions. It can also be used
to make a decision among multiple choices. The nested if…else statement has the following
form:
Syntax: if(condition1)
{
if(condition 2)
{
stmt1;
}
else
{
stmt2;

}
}
35
else
{
stmt 3;
}

stmt-x;

In this syntax,

• if and else are keywords.


• <condition1>,<condition2> … <condition>are relational expressions or logical
expressions or any other expressions that return true or false. It is important to note that
the condition should be enclosed within parentheses ( and ).
• if-body and else-body are simple statements or compound statements or empty
statements.
• stmt-x is a valid C statement.
The flow of control using Nested if...else statement is determined as follows

Whenever nested if…else statement is encountered, first <condition1> is tested. It returns either true
or false.

If condition1 (or outer condition) is false, then the control transfers to else-body (if exists) by
skipping if-body.

If condition1 (or outer condition) is true, then condition2 (or inner condition) is tested. If the
condition2 is true, if-body gets executed. Otherwise, the else-body that is inside of if statement
gets executed.

Program for nested if… else statement:

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

int a ,b,c;

printf("enter three values\n"); scanf("%d%d%d",&a,&b,&c); if(a>b)


{
if(a>c)
pintf("%d\n",a);
else
printf("%d\n",b);
}

else
{
if(c>b)
printf("%d\n",c);
else
printf("%d\n",b);
}

Output: enter three values 3 5 12


12

if-else if STATEMENT OR else if ladder


Introduction
If we want to make one decisions out of many options, then we can use the if-else if statement.
Syntax
The general format for the if-else if statement is:

if (condition 1)
simple or compound statement // s1
else if (condition 2)
simple or compound statement // s2
else if ( condition 3)
simple or compound statement // s3
.....
else if ( conditon n )
simple or compound statement // sn

If condition 1 is true then s1 is executed.


If condition 1 is false and condition 2 is true then s2 is executed.
The else clause is always associated with the nearest unresolved if statement.
37
Whenever else if ladder is encountered, condition1 is tested first. If it is true, the statement 1 gets
executed. After then the control transfers to stmt-x.

If condition1 is false, then condition2 is tested. If condition2 is false, the other conditions are tested.
If all are false, the default stmt at the end gets executed. After then the control transfers to stmt-x.

If any one of all conditions is true, then the body associated with it gets executed. After that the
control transfers to stmt-x.

Points to Remember
1. We can use if-else if when you want to check several conditions but still execute one
statement.
2. When writing an if-else if statement, be careful to associate else statement to the appropriate
if
statement.
3. We must have parentheses around the condition.

Example program:
/* to find grade when percentage of marks are given */
#include<stdio.h>
void main()
{

int m1,m2,m3,avg,tot;
printf("enter three subject marks");
scanf("%d%d%d",&m1,&m2,&m);
tot=m1+m2+m3;

38
avg=tot/3;
if(avg>=75)
{
printf("distinction");

else if(avg>=60 &&avg<75)


{
printf("first class");
}
else if(avg>=50 &&avg<60)
{
printf("second class");
}
else if (avg<50)
{
printf("fail");
}
}

Output: enter three subject marks


85 80 81
Distinction

THE switch STATEMENT


Introduction
We can use a switch statement when we want to check multiple conditions. It can also be done using
an if statement but it will be too lengthy and difficult to debug.
Syntax
The general format for a switch statement is
switch(integer expression)
{
case 1:
statement;
break;
case 2:
statement;
break;
---------
default:
statement;
}

Example of a case constant expression and column:


switch (i/10)
{
case 0: printf ("Number less than 10"); // A
break;
39
case 1: printf ("Number less than 20"); // B
break;
case 2: printf ("Number less than 30"); // C
break;
default: printf ("Number greater than or equal to 40"); // D
break;
}

Explanation
1. The switch expression should be an integer expression and, when evaluated, it must have an
integer value.
2. The case constant expression must represent a particular integer value and no two case
expressions should have the same value.
3. The value of the switch expression is compared with the case constant expression in the order
specified, that is, from the top down.
4. The execution begins from the case where the switch expression is matched and it flows
downward.
5. In the absence of a break statement, all statements that are followed by matched cases are
executed.
6. If there is no matched case then the default is executed. You can have either zero or one default
statement.
7. In the case of a nested switch statement, the break statements break the inner switch statement.

Flow chart:

Whenever, switch statement is encountered, first the value of <exp> gets matched with case values.
If suitable match is found, the statements block related to that matched case gets executed. The
break statement at the end transfers the control to the Next-statement.

If suitable match is not found, the default statements block gets executed and then the control gets
transferred to Next-statement.
40
Point to Remember
1. case constructs need not be serial.
2. characters can be used.
3. combination of integers and characters is possible.
4. default is optional.
5. Brace in case block is optional

//switch 1
// to display name of the day
#include <stdio.h>
void main()
{
int day;
printf("Enter day number\n");
scanf("%d",&day);
switch(day)
{
case 1:
printf("monday\n");
break;
case 2:
printf("tuesday\n");
break;
case 3:
printf("wednesday\n");
break;
case 4:
printf("thursday\n");
break;
case 5:
printf("friday\n");
break;
case 6:
printf("saturday\n");
break;
case 7:
printf("sunday\n");
break;
default:
printf("Wrong entry\n");
}
}
//switch 2
// to display the gender
#include <stdio.h>
void main()
41
{
charch;
printf("Enter your gender\n");
scanf("%c",&ch);
switch(ch)
{
case 'm':
case 'M':
printf("so you are a male\n");
break;

case 'f':
case 'F':
printf("so you are a female\n ")
break;

default:
printf("Wrong entry\n");
}
}

while LOOP
Introduction
The while loop is used when we want to repeat the execution of a certain statement or a set of
statements (compound statement).
Syntax
The general format for a while loop is
while (condition)
simple or compound statement (body of the loop)
For example,
i = 0;
while (i<5)
{
printf(" the value of i is %d\n", i);
i = i + 1;
}
Explanation
1. Before entering into the loop, the while condition is evaluated. If it is true then only the loop
body is executed.
2. Before making an iteration, the while condition is checked. If it is true then the loop body is
executed.
3. It is the responsibility of the programmer to ensure that the condition is false after certain
iterations; otherwise, the loop will make infinite iterations and it will not terminate.
4. The programmer should be aware of the final value of the looping variable. For example, in
this case, the final value of the looping variable is 5.
5. While writing the loop body, you have to be careful to decide whether the loop variable is
updated at the start of the body or at the end of the body.
42
#include<stdio.h>
#include<conio.h> int main()
{
int i,n;
printf("enter the range\n");
scanf("%d",&n);
i=1;

while(i<=n)

{
printf("%d ",i); i=i+1;
}
}

Output: enter the range 10


1 2 3 4 5 6 7 8 9 10

do-while LOOP
Introduction
The do-while loop is used when we want to execute the loop body at least once. The do-while loop
executes the loop body and then traces the condition.

Syntax
The general format for a do-while loop is
do
simple or compound statement
while (condition);

For example,
43
i = 0;
do
{
printf(" the value of i is %d\n", i);
i = i + 1;
}
while (i<5);

Explanation
1. The loop body is executed at least once.
2. The condition is checked after executing the loop body once.
3. If the condition is false then the loop is terminated.
4. In this example, the last value of i is printed as 5.

#include<stdio.h>

#include<conio.h> int main()


{
int i,n;
printf("enter the range\n"); scanf("%d",&n);
i=1;
do
{
printf("%d\n",i);
i=i+1;
}
while(i<=n);
}

Output: enter the range 5


1
2
44
3
4
5

for LOOP
Introduction
The for loop is used only when the number of iterations is predetermined, for example, 10 iterations
or 100 iterations.
Syntax
The general format for the for loop is
for (initializing; continuation condition; update)
simple or compound statement
For example,
for (i = 1; i<=5; i++)
{
printf("%d”, i");
}
Explanation
1. The for loop has four components; three are given in parentheses and one in the loop body.
2. All three components between the parentheses are optional.
3. The initialization part is executed first and only once.
4. The condition is evaluated before the loop body is executed. If the condition is false then the
loop body is not executed.
5. The update part is executed only after the loop body is executed and is generally used for
updating the loop variables.
6. The absence of a condition is taken as true.
7. It is the responsibility of the programmer to make sure the condition is false after certain
iterations.

Program to print n natural numbers using for loop


#include<stdio.h>

#include<conio.h>
void main()
{
int i,n;
printf("enter the value"); scanf("%d ",&n);
45
for(i=1;i<=n;i++)
{
printf("%d\n",i);
}
}

Output: enter the value 5


12345

THE for LOOP WITH A COMMA OPERATOR


Introduction
We may want to control the loop variables in the same for loop. We can use one for loop with a
comma operator in such situations.
Syntax
for (i = 0, j = 10; i< 3 && j > 8; i++, j-)
printf (" the value of i and j %d %d\n",i, j);
Explanation
1. First iis initialized to 0, and j is initialized to 10.
2. The conditions i<3 and j>8 are evaluated and the result is printed only if both conditions are
true.
3. After executing the loop body, iis incremented by 1 and j is decremented by 1.
4. The comma operator also returns a value. It returns the value of the rightmost operand.
The value of (i = 0, j = 10) is 10.

1. Program to find the factorial of a number


#include <stdio.h>
main()
{
longint fact=1;
inti,n;
printf(“Enter a positive number to find factorial\n”);
scanf(“%d”,&n);
for(i=1; i<n; i++)
fact *=i;
printf(“The factorial of %d is %ld”,n,fact);
}
2. Fibonacci series
main()
{
int i, f1, f2, f3, n;
f1 = f2 = 1;

printf( "\nHow many Fibonacci numbers required ? ");


scanf("%d", &n);
printf("\nThe first %3d Fibonacci numbers are\n", n);
46
printf("%5d\n", f1);
printf("%5d\n", f2);
for( i = 3; i<= n; i++)
{
f3 = f1 + f2;
printf("%5d\n", f3);
f1 = f2;
f2 = f3;
}
}
//3. Sine series
/* sin(x) = x - x3/3! + x5/5! + .. .. .. */
#include <stdio.h>
main()
{
int i, n;
float x,denom, term, sum,deg;
printf("Enter value of x in deg and number of
terms: \n");
scanf("%f%d", &deg, &n);
x=deg*3.14/180;
sum = term = x;
for ( i = 2; i<= n; i++)
{
denom = (2 * i - 2)*( 2 * i - 1);
term *= -(x*x)/ denom;
sum += term;
}
printf("\ndeg = %.1f, Sum = %.2f", deg, sum);
} /* end of main */

/* cos(x) = 1– x2/2! + x4/4! + .. .. */

// cosine series
main()
{
int i, n;
float x,denom, term, sum,deg;
printf("Enter value of x in deg and number of terms: \n");
scanf("%f%d", &deg, &n);
x=deg*3.14/180;
sum = term = 1;
for ( i = 1; i<= n; i++)
{
denom = (2 * i )*( 2 * i - 1);
term *= -(x*x)/ denom;
sum += term;
}
printf("\ndeg = %.1f, Sum = %.2f", deg, sum);
} /* end of main */
47
// to find the sum of digits of a number
#include <stdio.h>
main()
{
intn,sum=0,digit;;
printf("Enter a number\n");
scanf("%d",&n);
while(n!=0)
{
digit=n%10;
sum=sum+digit;
n=n/10;
}
printf("%d",sum)
}

// to convert decimal number to binary number


#include <stdio.h>
main()
{
intn,sum=0,digit,i=0;
printf("Enter a number\n");
scanf("%d",&n);
while(n!=0)
{
digit=n%2;
sum=sum+digit*pow(10,i);
n=n/2;
i++;
}
printf("%d",sum);
}

1. Jumping/ unconditional statements- break,continue,goto


2. Use these with combination of other statements.
3. Understand nested loops.

48
break statement

The break statement is used within the looping control statements, switch statement and nested
loops. When it is used with the for, while or do-while statements, the control comes out of the
corresponding loop and continues with the next statement.

When it is used in the nested loop or switch statement, the control comes out of that loop / switch
statement within which it is used. But, it does not come out of the complete nesting.

Syntax for the ―break statement is:

break;

In this syntax, break is the keyword.

The following representation shows the transfer of control when break statement is used:

Any loop

{
statement_1;
statement_2;
:

break;

next_statement;

Program for break statement:


#include<stdio.h>

#include<conio.h>
int main()
{
int i;
49
for(i=1; i<=10; i++)
{
if(i==6)
break;
printf("%d",i);
}
}

Output: 12345

2. continue statement

A continue statement is used within loops to end the execution of the current iteration and proceed
to the next iteration. It provides a way of skipping the remaining statements in that iteration after the
continue statement. It is important to note that a continue statement should be used only in loop
constructs and not in selective control statements.
Syntax for continue statement is:

continue;

where continue is the keyword.

The following representation shows the transfer of control when continue statement is used:
Any loop

statement_1; statement_2;
:

continue;

next_statement;

Program for continue statement:


#include<stdio.h>

#include<conio.h> int main()


{

int i, sum=0, n;
for(i=1; i<=10; i++)
{

printf("enter any no:");


50
scanf("%d",&n);
if(n<0)
continue;
else
sum=sum+n;
printf("%d\n",sum);
}

Output: enter any no:8


18

3. goto statement

The goto statement transfers the control to the specified location unconditionally. There are certain
situations where goto statement makes the program simpler. For example, if a deeply nested loop is
to be exited earlier, goto may be used for breaking more than one loop at a time. In this case, a break
statement will not serve the purpose because it only exits a single loop.

Syntax for goto statement is:

label:

statement_1; statement_2;
:

goto label;

In this syntax, goto is the keyword and label is any valid identifier and should be ended with a colon
(:).

The identifier following goto is a statement label and need not be declared. The name of the
statement or label can also be used as a variable name in the same program if it is declared
appropriately. The compiler identifies the name as a label if it appears in a goto statement and as a
variable if it appears in an expression.

If the block of statements that has label appears before the goto statement, then the control has to
move to backward and that goto is called as backward goto. If the block of

statements that has label appears after the goto statement, then the control has to move to forward
and that goto is called as forward goto.
51
Program for goto statement:
#include<stdio.h>

#include<conio.h> void main()


{

printf("www."); goto x;
y:

printf("expert"); goto z;
x:

printf("c programming"); goto y;


z:

printf(".com");

Output: www.c programming expert.com

PROGRAM 1
1
1 2
1 2 3
#include <stdio.h>
void main()
{
int line ,n;
for(line=1;line<=3;line++)
{
for(n=1;n<=line; n++)
printf("%3d",n);
printf("\n");
}
}
PROGRAM2
1
1 2
1 2 3
#include <stdio.h>
void main()
{
int line ,n,gap;
for(line=1;line<=3;line++)
{
for(gap=1;gap<=20-line;gap++)
printf(" ");
52
for (n=1;n<=line;n++)
printf("%4d",n);
printf("\n");
}
}
PROGRAM 3
/* 1
12
123
1234
12345

*/
#include <stdio.h>
void main()
{
int line ,n,gap;

for(line=1;line<=5;line++)
{
for(gap=1;gap<=5-line;gap++)
printf(" ");
for(n=1;n<=line;n++)
printf("%2d",n);
printf("\n");
}
}
PROGRAM 4
1
121
12312
1234123
123451234

#include <stdio.h>
void main()
{
int line ,n,gap;

for(line=1;line<=5;line++)
{
for(gap=1;gap<=20-line;gap++)
printf(" ");

for(n=1;n<=line;n++)
printf("%2d",n);

for(n=1;n<line;n++)
printf("%2d",n);
printf("\n");
53
}
}
//program 5 :Pascal triangle
#include <stdio.h>
void main()
{
int binom,n,q,g,x;
binom=1;
q=0;
printf("enter no of rows\n");
scanf("%d",&n);
while(q<n)
{
for(g=40-3*q;g>0;g--)
printf(" ");
for(x=0;x<=q;x++)
{
if((x==0)||(q==0))
binom=1;
else
binom = (binom*(q-x+1))/x;
printf("%6d",binom);
}
printf("\n");
q++;
}
}

Programming exercises:

Develop programs to display the given patterns (L3)(CO3)

*****
* *
* *
* *
*****

*****
*****
*****
*****
*****

54
*
**
**
* *
*****

10101
01010
10101
01010
10101

555555555
544444445
543333345
543222345
543212345
543222345
543333345
544444445
555555555

Lecture-13

// to display the given number in words


#include <stdio.h>
void main()
{
intnum,digit,temp,rev=0;
printf("Enter a number\n");
scanf("%d",&num);
temp=num;
while(num!=0)
{
digit=num%10;
rev = rev*10 + digit;
num=num/10;
}
while(rev!=0)
{

55
digit=rev%10;
switch(digit)
{
case 1:
printf("ONE ");
break;
case 2:
printf("TWO ");
break;
case 3:
printf("THREE ");
break;
case 4:
printf("FOUR ");
break;
case 5:
printf("FIVE ");
break;
case 6:
printf("SIX ");
break;
case 7:
printf("SEVEN ");
break;
case 8:
printf("EIGHT ");
break;
case 9:
printf("NINE ");
break;
case 0:
printf("ZERO ");
}
rev=rev/10;
}

while(temp%10==0)
{
printf("ZERO ");
temp=temp/10;
}
}

FUNCTIONS

56
Definition:
A function is a set of instructions under a name that carries out a specific task, assigned to it.

CLASSIFICATION of functions:
1. User defined functions (UDF)
2. Library functions
USER DEFINED FUNCTIONS

Without arguments with arguments

Without return with return Without return with return

Example:
void sum( ) function without arguments and without return value
int sum( ) function without arguments but with return value
void sum(int ,int) function with arguments but without return value
int sum(int,int) function with arguments and with return value

1. It avoids the need for redundant programming of the same instructions.


2. Logical clarity of the programming will be clear.
3. Easy to debug.
4. A library with user defined functions can be created.

Function prototype:
If we use any variable in the program, we declare that variable in the declaration section of the

program. Similarly, any function that is to be called should be declared before its call in the

calling function. This declaration of a function is called function prototype.

Function declaration should be done either in the declaration section of calling function

or before it. The function prototype should agree with definition of that function.

Prototype contains the data type returned by the function followed by the name of that

function and a pair of parentheses enclosing the data type of each parameter separately.

Optionally the name of each parameter may be given.

Ex: int fact(int); or int fact(int n);

If there are no parameters, void should be shown in parentheses. Similarly, if there is no

return value, return value type should be indicated as void.

57
Function definition

Writing code for the function is called function definition.

Function definition contains function header + body of function.

Syntax of function header :return type name of the function ( arguments)

FUNCTION CALL
Function call means, accessing a function. A function can be called by specifying its
name, followed by a list of arguments enclosed in the parentheses, and separated by comma
Example: f=fact(n);
If a function call does not require any arguments, an empty pair of parentheses must
follow the function name.
A function call may appear itself or it may be one of the operand within a expression.
Example: printf(“%d”,fact(n));
Arguments in function call, and formal parameters in function declaration must be same
in number, type and order.

Difference between actual and formal parameters


Variables used in function calling are called actual parameters or arguments.
Variables used in function definition are called formal parameters or dummy parameters or
place holders.

There are two parameter passing mechanisms


1. call by value. Or passing by value
2. call by reference or passing by address or call by address.
Call by value:
Passing arguments by value means , the contents of the arguments in the calling
function are not changed , even if they are changed in the called function.
This is because the content of the variable is copied to the formal parameter of the function
definition, thus preventing the contents of the argument in the calling function.
Call by reference:
Call by reference means sending the address of variables as arguments to the function.
When addresses are sent, the changes occurred in the called function can also effect in the calling
function.
58
/* example to illustrate call by value and call by reference*/
#include <stdio.h>
void main()
{
void makezero(int,int*); /*function prototype*/
int x=50,y=100;
makezero(x,&y); /* function call by value and referene */
printf(“x=%d y=%d”, x,y);
}
/* function makezero */
void makezero(int a,int *b)
{
a=0;
*b=0;
}

OUTPUT
x=50 y=0
Example programs on functions
Factorial of number by using function
#include <stdio.h>
main()
{
long int fact(int);
int n;
long int f;
printf("Enter a number\n");
scanf("%d",&n);
f = fact(n);
printf("The factorial of %d is %ld",n,f);
} /*end of main */

/* function fact*/
long int fact(int x)
{
int i;
long int f1=1;
for(i=1;i<=x;i++)
f1 = f1*i;
return(f1);
59
}
Fibonacci series by function
main()
{
int n;
void fib(int);
printf( "\nHow many Fibonacci numbers
required ? ");
scanf("%d", &n);
printf("\nThe first %3d fibonaccinumbers are\n", n);
fib(n);
}

void fib(int n)
{
int i, f1, f2, f3;
f1 = f2 = 1;
printf("%5d\n", f1);
printf("%5d\n", f2);
for( i = 3; i<= n; i++)
{
f3 = f1 + f2;
printf("%5d\n", f3);
f1 = f2;
f2 = f3;
}
}
GCD of two numbers by function
void main()
{
int m,n,g;
int gcd(int,int);

printf("Enter two numbers\n");


scanf("%d%d",&m,&n);
g = gcd(m,n);
printf("GCD of %d and %d is %d", m,n,g);

} /* End of main() */
int gcd(int m,int n)
{
int r,g1;
do

60
{
r=m%n;
if(r!=0)
{
m=n;
n=r;
}
}while(r!=0);
g1=n;
return(g1);
} /* End of function gcd */
LCM of two numbers by function
main()
{
int m,n;
int lcm(int,int);

printf("Enter two numbers\n");


scanf("%d%d",&m,&n);
printf("LCM of %d and %d is %d", m,n,lcm(m,n));

} /* End of main() */

int lcm(int m,int n)


{
int i;
for(i=1;i<= m*n;i++)
{
if(i%m==0 &&i%n==0)
break;
}
return i;
} /* End of function lcm*/
Sum of digits by function
main()
{
int digitsum(int);
int num;
printf("Enter a number\n");
scanf("%d",&num);
printf("Sum of digits = %d\n",digitsum(num));
}
/* function digitsum() */
int digitsum(int num)
{
61
int digit,sum=0;
while(num !=0)
{
digit = num%10;
sum = sum+ digit;
num = num/10;
}
return sum;
}
To check whether the number is palindrome or not by using function

#include <stdio.h>
void main()
{
int palin(int);
int num,ans;
printf("Enter a number\n");
scanf("%d",&num);
ans=palin(num);
if(ans==1)
printf("%d is palindrome\n",num);
else
printf("%d is not palindrome\n",num);
}

/* function palin */
int palin(int num)
{
int rev=0,temp,digit;
temp=num;
while(num!=0)
{
digit= num%10;
rev = rev*10 + digit;
num = num/10;
}
if(rev==temp)
return 1;
else
return 0;
}

RECURSIVE FUNCTIONS
A function which calls itself until a certain condition is reached is called recursive function
/* to find factorial of a number recursively */
#include <stdio.h>
main()
{
62
int rfactorial(int);
int n,f;
printf("Enter a number\n");
scanf("%d",&n);
f=rfactorial(n);
printf("Factorial of %d is %d",n,f);

/* factorial */
int rfactorial(int n)
{
if(n==0)
return 1;
else return(n*rfactorial(n-1));
}
/* to find nth fib number recursively */
#include <stdio.h>
main()
{
int rfib(int);
int n,f;
printf("Enter a number\n");
scanf("%d",&n);
f=rfib(n);
printf("n thfibonacci number is %d",f);
}

/* rfib */
int rfib(int n)
{
if(n==1||n==2)
return 1;
else return(rfib(n-1)+rfib(n-2));
}
/* to find GCD of two numbers recursively */
#include <stdio.h>
main()
{
int rgcd(int,int);
int m,n,g;

printf("Enter two numbers\n");


scanf("%d%d",&m,&n);
g=rgcd(m,n);
printf("gcd is %d",g);

}
/* function rgcd */
int rgcd(int m,int n)
63
{
if(m%n==0)
return n;
else
return(rgcd(n,m%n));
}

/* to find nCr recursively */


#include <stdio.h>
#include <conio.h>
void main()
{
int rncr(int,int);
int n,r,s;
printf("Enter two numbers\n");
scanf("%d%d",&n,&r);
s=rncr(n,r);
printf("ncr =%d\n",s);
}
int rncr(int n,int r)
{
if(r==0 || n==r)
return 1;
else
return(rncr(n-1,r)+rncr(n-1,r-1));
}
/* to find sum of digits recursively */
#include <stdio.h>
#include <conio.h>
void main()
{
int rsum(int n);
int n,s;
printf("Enter a number\n");
scanf("%d",&n);
s=rsum(n);
printf("sum of digits =%d\n",s);
}

int rsum(int n)
{
if(n==0)
return n;
else return(n%10+rsum(n/10));
}

/* to find m power n recursively */

#include <stdio.h>
void main()
64
{
int rpower(int,int);
int m,n;
printf("Enter two number\n");
scanf("%d%d",&m,&n);
printf("%d power %d is %d\n",m,n,rpower(m,n));

}
int rpower(int m,int n)
{
if(n==0)
return 1;
else
return(m*rpower(m,n-1));
}

/* to find the sum of two numbers recursively */


#include <stdio.h>
#include <conio.h>
void main()
{
int rsum(int,int);
int m,n,s;

printf("Enter two numbers\n");


scanf("%d%d",&m,&n);
s=rsum(m,n);
printf("sum =%d\n",s);
}

int rsum(int m,int n)


{
if(n==0)
return m;
else
return(rsum(m+1,n-1));
}

STORAGE CLASSES
Normally the life of a variable is limited to a function as long as the function is alive. How to
make it alive in a file or throughout the program or limiting only to a block inside a function or
to make common to a desired couple of functions etc., The answer lies in “STORAGE
CLASSES” or “VARIABLE TYPES”.
65
There are four types of storage classes.
1. Automatic variables.
2. External variables.
3. Static variables.
4. Register variables.

AUTOMATIC VARIABLES:
Automatic variables are declared inside a function, in which they are to be utilized. They
are created when the function is called and destroyed automatically when the function is exited.
By default all variables are automatic variables. These are also called local or internal variables.
EXTERNAL VARIABLES
Variables that are both alive and active throughout the entire program are called external
variables. These variables are available to all functions in that program. Whatever changes that
occur in a function, will effect the value of that variable.
STATIC VARIABLES
When a variable is declared as a static variable it is assigned the value zero. Static
variables are initialized only once. They will not be initialized for second time during the
program. When static is applied to a global variable, the global variable becomes inaccessible
outside the file.
REGISTER VARIABLES

This is local to a function or a block. If a compiler finds a physical register in the CPU free for
the time being, and also big enough to hold the value, then it may stick that variable in that
register. Otherwise, the compiler treats that variable as ordinary. It is machine dependent. But
compiler will not give error messages even if no register available in reserve. If we know that a
particular variable will be used often inside function-say the variable inside a loop-then we can
declare that variable with class register. So that the interaction will be very fast.

//Write a program to demonstrate life cycle of auto


variable in nested blocks.
void main()
{

66
auto int x=1;
{
auto int x=2;
{
auto int x=3;
printf(“%d\n”, x);
}
printf(“%d\n”,x);
}
printf(“%d\n”,x);
}
Output
3
2
1
// program to illustrate automatic and external variables
#include <stdio.h>
int x=1;
int fun1()
{
x=x+10;
return x;
}

int fun2()
{
int x;
x=20;
return x;
}
int fun3()
{
x=1000;
return x;
}
void main()
{
int x=100;
printf("% d\n",fun1());
printf("%d\n",fun2());
printf("% d\n",fun3());
x=0;
printf("%d\n",x);
printf("% d\n",fun1());
printf("%d\n",fun2());
printf("% d\n",fun3());
}
OUTPUT
11
20
67
1000
0
1010
20
1000

// program to illustrate static variable


#include <stdio.h>
void main()
{
int fun();
int i;
for(i=1;i<5;i++)
printf("%d\n",fun());
}

int fun()
{
static int x=0;
x+=1;
return(x);
}
OUTPUT
1
2
3
4
// program to illustrate register variable
#include <stdio.h>
void main()
{
register inti;
int i;
for(i=1;i<1000;i++)
printf("% d",i);
}
automatic variable static variable

1. It is declared by auto int a = 10; 1. It is declared by static int a = 10;

2. It must be declared inside the function 2. It can be declared inside or outside the
function
3. If it is not initialized, garbage value is 3. If it is not initialized, zero is stored
stored 4. It is initialized once and only one but not
4. It is initialized every time function is every
called that is repeated initialization time when function is called
5. It is lost when function terminates 5. It is lost when program terminates but not
when function terminates

68
Local variable Global variable
1. It is declaration inside the function 1.It is declaration outside the function
2.It is declared by 2. It is declared by int a=10
auto int a=10 or
int a = 10 (auto is default scope)
3. If it is not initialized. garbage value is 3. If it is not initialized zero is stored
stored Eg: int a; Eg: int a;
a is garbage value a=0
4. It is created when the function starts 4. It is created before program execution
execution and lost when the function starts and lost when program terminates
terminates
5. It is visible in only one function. 5. It is visible through out the program.

6. It can be accessed in only one function that 6. It can be accessed in more than one
is the function.

function where it is declared


7. Data sharing is possible that is
7. Data sharing is not possible that is multiple functions can access the
data of local variable can be accessed same global variable.
by only one function
8. Parameters passing is not required
for global variable since global
8. Parameters passing is required for variable is visible throughout the
local variable that is local variable of program
one variable
9. If value of global variable is modified
9. If value of local variable is modified in one function changes are visible in
in one function changes are rest of the program
not visible in another functions

Iterative Recursive

69
1. Function calls some other functions 1. Function calls some itself

2. while loop, do while loop or for loop is 2. if statement is necessary in recursive function
necessary in iterative function
3. Fast in execution since one function 3. Slow in execution since several function calls
call is enough to get the result are involved to get the result, as number of
function increases execution will slow down.
4. Function call leads to value 4. Function call leads to another function call
Eg: fact(4) = 24 Eg: fact(4) = 4 x fact(3)

5. Werequire mathematical steps or 5. We require a formula to write a recursive


procedure to write an iterative function. function.
6. Stacks are not used during execution
6. Stacks are used during execution of recursive
functions

UNIT III

ARRAYS

Introduction to Arrays
Till now you might have declared variables to hold data and to perform operations on it. Just like
given below-
int a=10;
char ch=’a’;
These variables can hold only one data item at a time. Let us take some example where collection of
data items need to be stored….
• 60 students marks secured in a subject
• Salaries of 100 employees
we are supposed to declare multiple variables to hold the above data for each example.
language provides a derived data types called arrays.
efinition
An array is collection of homogeneous elements stored in continuous memory locations and shares a
common name.
here are several forms of an array used in C: one-dimensional or single-dimensional and
multidimensional array.
eclaration of one-dimensional or single-dimensional
Like any other variables, arrays must be declared before they are used. The general form of array
declaration is
Syntax: datatype array_name[sizeofarray];

 The data type specifies the type of data/element that will be stored in the array, such as int,
float, or char.
 The size indicates the maximum number of data/elements that can be stored in the array.
 The size of array should be a int constant or constant expression.
Let us take the same example to declare suitable one dimensional array variable to hold the data.

70
• 60 students marks secured in a subject
unsigned short int PPS[60];
• Salaries of 100 employees
float salaries_of_employees[100];

t Inernal representation /Memory Allocation


a[5];

 Elements are stored in consecutive memory allocations. Each block is of size two because
variable ‘ a’ is of data type ‘int’. If array variable is of ‘float ‘ data type then each block
occupies four bytes.
 So total memory occupied by an array whose size is given as ‘n’ is-
sizeof(datatype of the variable)*n
 First element in the array is stored at a[0], second at a[1] and so on fifth element is stored at
a[4]. If size of an array is ‘n’ then elements in the array stored from 0 to n-1 index/subscript.
Storing/ retrieving data into/from the array is done by using index/subscript.

cProcessing one-dimensional array elements


Array access involves store/initialize and retrieve the data items.

• Array is initialized with elements can be done at static time (while writing the code) or
dynamic time( at the time of executing the program).
Static Initialization
Example 1:
int a[5]; //array declaration
//array initialization
a[0]=10;
a[1]=20;
a[2]=30;
a[3]=40;
a[4]=50;

Example 2:
int a[5]={10,20,30,40,50}; // array declaration and initialization

71
Dynamic Initialization
Example 3:
int a[5],i;
printf(“Enter 5 integer elements:”);
for(i=0;i<=4;i++)
scanf(“%d”,&a[i]);
At the time of execution user can give 5 data items which will be stored in the array.

Retrieving elements from an array using subscript

int a[5]={10,20,30,40,50};
printf(“%d\t%d\t%d\t%d\t%d”,a[0], a[1], a[2], a[3], a[4]);

Retrieving elements from an array using loop/iterative variable as subscript

int a[5]={10,20,30,40,50},i;
for(i=0;i<=4;i++)
printf(“%d”,a[i]);

In both the cases elements stored in the indexes from ‘0’ to ‘4’ will be displayed.
As loop variable value changes the subscript of an array changes and corresponding
element will be displayed.

Let us write a program to store and retrieve element into/from an array.


# include<stdio.h>
int main( )
{
inti , a[5];
72
printf(“Enter 5 integer elements: ”); /* reading values into Array */
for (i=0; i<5; i++)
scanf(“ %d ”, &a[i]);
/* printing of a[i] values */
printf(“The array elements are:”);
for(i=0; i< 5; i++)
printf(“%d ”, a[i]);

}
Output:

Variable length arrays


Previous version of C(C89) compilers, an array’s size must be an constant, so that compiler can
calculate the size/memory allocation at the compilation time itself. But from C99 onwards, C
compilers allows the programmers to declare an array variable with variable length ie size of an
array can be given at execution time/ run time.

/* Program to read and display using variable length arrays*/


int main()
{
intn,i;
printf("\n Enter the size of the array");
scanf("%d",&n);
int a[n]; // variable length array (VLA). The ‘n’ variable declaration should be before VLA
printf("\n Enter %d numbers:",n);
for(i=0;i<=n-1;i++)
scanf("%d",&a[i]);
printf("\n\n Given %d numbers are:",n);
for(i=0;i<n;i++)
printf("%d ",a[i]);
return 0;
}
Output:

Operations on array elements


Some operations are listed below
• c=a[0]+a[1] // adding elements at index ‘0’ and ‘1’ and store it in ‘c’ variable
• a[i]=a[i]+20 // adding a constant to the array element at index ‘i’ and store in same
location
• a[i]> x // compare value at ‘x’ with value at ‘a[i]’

73
• a[i]=a[i]+1 // add ‘1’ to value at ‘a[i]’
• a[i]++ // add ‘1’ to value at ‘a[i]’
• a[i]+=1 // add ‘1’ to value at ‘a[i]’
• a[k]=a[i]; // ‘i’th indexed element stored at index ‘k’

/* Write a program to print the array elements in reverse order */

# include<stdio.h>
int main( )
{
inti , a[5];
printf(“Enter 5 integer elements: ”); /* reading values into Array */
for (i=0; i<5; i++)
scanf(“ %d ”, &a[i]);
/* printing of a[i] values */
printf(“The array elements in reverse order are:”);
for(i=4; i>=0 ; i--)
printf(“%d ”, a[i]);

}
Output:

Searching operation on array elements

Find whether a given element/key exists or not in the array of elements is called search.
This operation can be done by using two methods- simplest method is a sequential search or linear
search and binary search.

The basic idea of linear search is start comparing the key with each element in the array from index
‘0’ to index ‘n’-1 if ‘n’ is the size of the array.
if key is found display the position/index at which element exist and exit the search
otherwise search will be continued till the end of the array and display the key is not found.

/* Program to implement linear search */


#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[10],n,i,key, FOUND=0;
printf(“\n How many numbers”);
scanf(“%d”,&n);
if(n>10)
74
{
printf(“\n Too many Numbers”);
exit(0);
}
printf(“\n Enter the array elements \n”);
for(i=0 ; i<n; i++)
scanf(“%d”, &a[i]);
printf(“\n Enter the key to be searched \n”);
scanf(“%d”,&key);
for(i=0 ; i<n; i++)
if(a[i] == key)
{
printf(“\n Found at %d”,i);
FOUND=1; break;
}
if(FOUND = = 0)
printf(“\n NOT FOUND...”);
return 0;
}
Output when more than the size of the array

Output when search is successful Logic for successful search

Output when search is unsuccessful Logic for unsuccessful search

In binary search method , halves the size of the list and searches only in half of the array by
finding the mid element index using first(low) and last(high) index of the array.
The procedure is as follows-
• Find mid element by using low and high

75
• If key is less than mid element then search will be done in left of the array by updating high
• Else If key is greater than mid element then search will be done in right of the array by
updating low
• Otherwise mid element itself is the search element.
his will be continued until low is less than high. Unsuccessful search make low greater than high. To
perform binary search the elements should be increasing order in the array.
/* Program to implement linear search */

#include<stdio.h>
int main()
{
int n;
printf("\n Enter the size of the array:");
scanf("%d",&n);

int a[n],i,key,FOUND=0;

printf("\n Enter elements in increasing order");


for(i=0;i<n;i++)
scanf("%d",&a[i]);

printf("\n Enter element for searching:");


scanf("%d",&key);

int low=0,high=n-1,mid;
while(low<=high)
{
mid=(low+high)/2;
if(key>a[mid])
low=mid+1;
else if(key<a[mid])
high=mid-1;
else
{
printf("\n Found at %d",i);
FOUND=1; break;
}
}
if(FOUND == 0)
printf("\n NOT FOUND...");

return 0;
}
Output Binary search logic Interpretation for
successful search

76
Bubble Sorting
Sorting operation will keep the element in an order.
Basic principle of bubble sort is consecutive/adjacent elements are compared and exchanges their
values if they are not in the order. This process bubbles the smallest element in the array to ‘0’ index
and largest to ‘n-1’ index where ‘n’ is the size of the array.
The following depicts the different stages of the bubble sort.

Array elements are 44 22 -1 3 10

pass1 Comparison on
44 22 -1 3 10 44 , 22 (swap)
22 44 -1 3 10 44, -1 (swap)
22 -1 44 3 10 44 , 3 (swap)
22 -1 3 44 10 44, 10 (swap)
22 -1 3 10 44 Pass1 completed and largest element (44) placed in the correct
position. It is not going to be considered in the next iteration.
Pass2 Comparison on
-1 22 3 10 44 22, -1 (swap)
-1 3 22 10 44 22, 3 (swap)
-1 3 10 22 44 22, 10 (swap)
-1 3 10 22 44 Pass 2 completed . 22 is placed in the correct position. It is not
going to be considered in the next iteration.
Pass3 Comparison on
-1 3 10 22 44 -1, 3 (no swap)
-1 3 10 22 44 3,10 (no swap)
-1 3 10 22 44 Pass 3 completed . 10 is placed in the correct position .It is not
going to be considered in the next iteration.
Pass4 Comparison on
-1 3 10 22 44 -1, 3 (no swap)
-1 3 10 22 44 Pass 4 completed . 3 is placed in the correct position .It is not
going to be considered in the next iteration.
Always single element in the array will be in sorted order itself. So algorithm stops its passes.

/* Program to implement bubble sort*/


#include<stdio.h>
int main()
{
int n;
printf("\n Enter the size of the array:");
scanf("%d",&n);

77
int a[n],i,j,temp;
printf("\n Enter %d numbers for sorting",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\n Before Sorting ....\n");

for(i=0;i<n;i++)
printf("%5d",x[i]);

//sorting logic
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1]; /* swap */
a[j+1]=temp;
}

}
printf("\n After Sorting ....\n");
for(i=0;i<n;i++)
printf("%5d",x[i]);
return 0;
}

Selection Sorting
 Selection sort finds the minimum element from the array and place it in the beginning.

Array elements are 44 22 -1 3 10


44 22 -1 3 10 Pass 1:
Find minimum element from index 0 to 4
and place at index 0 ie min=-1
Swap( 44,-1)
-1 22 44 3 10 Pass 2:
Find next minimum element from index 1 to 4
and place at index 1 ie min=3
Swap( 22,3)
-1 3 44 22 10 Pass 3:
Find next minimum element from index 2 to 4
and place at index 2 ie min=10
Swap( 44,10)
-1 3 10 22 44 Pass 4:
Find next minimum element from index 3 to 4
and place at index 3ie min=22
78
Swap( 22,22)
-1 3 10 22 44 Single element will be in sorted order

/* Program to implement Selection Sort*/

#include <stdio.h>
main()
{
int a[20],n,i, j, po,se,temp;
printf("How many elements\n");
scanf("%d",&n);

/* loop to read values into array */


printf("Enter %d numbers below:\n", n);
for ( i = 0; i< n; i++ )
scanf("%d", &a[i]);

/* loops of selection sort */


for(i=0;i<n-1;i++)
{
se=po=i;
for(j=i+1;j<n;j++)
{
if(a[j] <a[se])
se=j;
}
temp=a[po];
a[po]=a[se];
a[se]=temp;
}

/* loop to display sorted array */


printf("The sorted Array is: \n");
for ( i = 0; i< n; i++ )
printf("%d\n", a[i]);

TWO DIMENSIONAL ARRAYS

• Arrays with more than one dimension are called multidimensional arrays.
• Array of one dimensional array is called two dimensional array.

An array of two dimensions can be declared as follows:


79
Syntax:
data_typearray_name[size1][size2];
 size1, size2 are constant , array subscript in both dimensions start from 0 to size1-1 and 0 to
size2-1. Size1 tells the information about number of rows and size2 tells about number of
columns .
 In other words, size1 gives how many one-dimensional arrays exists and size2 gives how
many elements in a one one-dimensional array.
 Number of elements stored in the array will be size1 *size 2 .

Example:
int a[10][10];
float b[20][20];
• Two dimensions are useful to store data in a table form. Ie take the previous example 60
student marks in a subject.
• In order to store 60 students’ marks obtained in 6 subjects then six one dimensional arrays
need to be declared for each subjects.
• It will be difficult to remember the variable name of each subject if multiple subjects exist.

Static initialization
initialization of an array: this can be done in two ways
1. int a[2][2] = { {3,6} , {2,9} }; // each 1D array enclosed in {} and separated with ,
2. int a[2][2] = { 3,6,2,9}; // based on 2nd dimension it will identify the number of
// elements in each row.
dynamic initialization
• To represent 2 dimensions we need two variable one for each dimension.

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

ternal representation /Memory Allocation


• If array is declared as int a[3][3]
the computer the array a[3][3] will looks as below

row1 row 2 row 3


ser perception

a[3][3]={1,2,3,4,5,6,7,8,9};
hen the array will be …
80
row1 row 2 row 3

 To accesses the 2nd element at 3rd row we need to use the indexes as a[1][2]. So element in ith
row jth column will be accesses as a[i-1][j-1].
 All the elements are stored in continuous locations. Two dimensional array is also called as
array of arrays.
 First dimension in the 2D array tells about how many one dimensional arrays are required,
second dimension tells about how many elements in each one dimensional array .

Program to add two M x N matrices.


#include <stdio.h>
main()
{
int a[10][10],b[10][10],c[10][10],i,j,m,n;

printf("Enter the number of rows and


columns for A and B\n");
scanf("%d%d",&m,&n);
/* loop to read values of matrix A*/
printf("Enter the elements for matrix A\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);

/* loop to read values matrix B*/


printf("Enter the elements for matrix B\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&b[i][j]);

/* loop to add two matrices*/


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

/* loop to print resultant matrix */


printf("The sum of A and B is\n");
for(i=0;i<m;i++)
{
81
for(j=0;j<n;j++)
printf("%3d",c[i][j]);
printf("\n");
}
}

Enter the number of rows and columns for A and B


2
2
Enter the elements for matrix A
1234
Enter the elements for matrix B
4321
The sum of A and B is
5 5
5 5

Program to multiply two M x N and P x Q matrices


#include <stdio.h>
main()
{
int a[10][10],b[10][10],c[10][10],i,j,m,n,p,q,k;
printf("Enter the number of rows and columns for A \n");
scanf("%d%d",&m,&n);
printf("Enter the number of rows and columns for B \n");
scanf("%d%d",&p,&q);

/* loop to read values of matrix A*/


printf("Enter the elements for matrix A\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);

/* loop to read values of matrix B*/


printf("Enter the elements for matrix B\n");
for(i=0;i<p;i++)
for(j=0;j<q;j++)
scanf("%d",&b[i][j]);
/* loop to multiply two matrices*/
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j] = 0;
for(k=0;k<n;k++)
c[i][j] = c[i][j] + a[i][k]*b[k][j];
}
}

82
/* loop to display resultant matrix */
printf("The multiplication of A and B is\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
printf("%3d",c[i][j]);
printf("\n");
}
}

Enter the number of rows and columns for A


23
Enter the number of rows and columns for B
32
Enter the elements for matrix A
222
222
Enter the elements for matrix B
33
33
33
The multiplication of A and B is
18 18
18 18

Program to find Transpose of a matrix


#include <stdio.h>
main()
{
int a[5][5],b[5][5],i,j,r,c;
printf("Enter the size of matrix\n");
scanf("%d%d",&r,&c);

/* loop to read values of matrix A*/

printf(“Enter the matrix values\n”);


for(i=0;i<r;i++)
for(j=0;j<c;j++)
scanf("%d",&a[i][j]);

/* loop to find transpose of matrix A*/


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

/* loop to display the resultant matrix*/


printf("Transpose of a :\n");
for(i=0;i<c;i++)
{

83
for(j=0;j<r;j++)
printf("%3d",b[i][j]);
printf("\n");
}
}
Enter the size of matrix
23
Enter the matrix values
123
456
Transpose of a :
1 4
2 5
3 6

1 D ARRAYS AND FUNCTIONS

1. We can pass entire array to a function.


2. In the calling function we need to give only name of the array, subscript or square brackets are
not necessary.
3. When we pass array name to a function, base address of that array is passed, since array name
refers base address of that array. Therefore call by reference mechanism takes place.
4. It is optional to give size of the array in the function definition.

/* linear search by function */


#include <stdio.h>
main()
{
void lsearch(int [],int,int);
int a[10],n,i,key;
printf("enter how many elements\n");
scanf("%d",&n);
printf("Enter the values\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("enter the key\n");
scanf("%d",&key);
lsearch(a,n,key);
}
/*Function lsearch */

void lsearch(int a[10],intn,int key)


{
inti,found=0;
for(i=0;i<n;i++)
{
if(a[i]==key)
{
printf("search is successful\n");

84
printf("location = %d\n",i+1);
found =1;
}
}
if(found==0)
printf(" element not found\n");
}
OUTPUT:
Enter how many numbers
8↵
Enter the number
34 5 89 54 7 15 77 23 ↵
Enter the key
77↵
Search is successful
Location =7

/* binary search by function */


#include <stdio.h>
main()
{
void input(int [ ],int);
void bsearch(int [],int,int);
int a[25],n,key;
printf("How many numbers ? ");
scanf("%d",&n);
printf("\nEnter %d numbers :\n", n);
input(a,n);
printf("Enter the key\n");
scanf("%d",&key);
bsearch(a,n,key);

} /* end of main */
/*Function input */
void input( int a[],int n)
{
inti;
for ( i = 0; i< n; i++ )
scanf("%d", &a[i]);
} /* end of function input */

/* Function Bsearch */
void bsearch (int a[],intn,int key)
{
intlow,high,mid,flag=0;
low=0;
high=n-1;
while(low<=high)
85
{
mid=(low+high)/2;
if(key < a[mid])
high=mid-1;
else if(key > a[mid])
low = mid+1;
else if(key == a[mid])
{
printf("search is successful\n");
printf("location = %d\n",mid+1);
flag=1;
break;
}
}
if(flag==0)
printf("search is unsuccessful\n");
} /* end of function bubblesort */
OUTPUT:
Enter how many numbers
10 ↵
Enter the number
3 5 8 54 7 15 76 23 79 11 ↵
Enter the key
79↵
Search is successful
Location =9

/*bubble sort by functions */


#include<stdio.h>
main()
{
void input(int [],int);
void output(int [],int);
void bubblesort(int [],int);

int a[25],n;
printf("How many numbers to sort ? ");
scanf("%d",&n);
printf("\nEnter %d numbers below:\n", n);
input(a,n);
bubblesort(a,n);
printf("\nThe sorted Array is: \n");
output(a,n);
} /* end of main */

/*Function input */
void input( int a[],int n)
86
{
inti;
for ( i = 0; i< n; i++ )
scanf("%d", &a[i]);
} /* end of function input */

/* Function Bubblesort */
void bubblesort (int a[],int n)
{
int pass, j, temp;
for ( pass = 1; pass < n; pass++ )
{
for ( j =0 ; j < n-1; j++ )
{
if( a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
} /* end of function bubblesort */

/* Function output */
void output (int a[],int n)
{
inti;
for ( i = 0; i< n; i++ )
printf("%5d\n", a[i]);
} /* end of function output */

Selection sort by function

#include <stdio.h>
main()
{
void ssort(int [],int);
void display(int [] ,int);
void readarray(int [],int);
int a[20],n;
printf("How many elements\n");
scanf("%d",&n);
printf("Enter the elements\n");
readarray(a,n);
ssort(a,n);
display(a,n);
}

87
void readarray(int a[],int n)
{
inti;
for(i=0;i<n;i++)
scanf("%d",&a[i]);
}

void ssort(int a[], int n)


{
inti,j,po,se,temp;
for(i=0;i<n-1;i++)
{
se=po=i;
for(j=i+1;j<n;j++)
{
if(a[j] <a[se])
se=j;
}
temp=a[po];
a[po]=a[se];
a[se]=temp;
}
}
void display(int a[],int n)
{
inti;
printf("The sorted array is\n");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
}
How many numbers to sort ?
7
Enter 7 numbers below:
55 4 -3 0 22 1 5
The sorted Array is:
-3
0
1
4
5
22
55

2 D ARRAYS AND FUNCTIONS

1. We can pass entire two dimensional array to function like one dimensional array.
2. When we pass two dimensional array to a function, in the function definition formal
argument, the size of the column is must and size of the row is optional.
88
/*Program to add two matrices by using functions*/

#include <stdio.h>
main()
{
void readmat(int [ ][10],int,int);
void matadd(int [ ][10],int [ ][10],int [ ][10],int,int);
void display(int [ ][10],int,int);

int A[10][10], B[10][10], C[10][10],m,n;

printf("\nEnter size of the matrix A and B: ");


scanf("%d%d", &m,&n);

printf("\nEnter elements of matrix A \n");


readmat (A, m,n);

printf("\nEnter elements of matrix B \n");


readmat (B,m,n);

matadd(A, B, C,m,n);

printf("Matrix A is :\n");
display(A, m,n);

printf("Matrix B is :\n");
display(B, m,n);

printf("\nMATRIX C (= A + B) is:\n");
display(C, m,n);

} /* end of main */

/* Function to read the elements of a matrix row-wise */


void readmat(int X[10][10],introws,int cols)
{
inti, j;
for(i = 0; i< rows; i++)
for( j = 0; j < cols; j++)
scanf("%d", &X[i][j]);
} /* end of function read_matrix */

/*Function to add two mxn matrices */


void matadd (int A[10][10], int B[10][10], int C[10][10], int m, int n)
{
inti, j;
for(i = 0; i< m; i++)
{
89
for( j = 0; j < n; j++)
{
C[i ][ j] = A[i ][j ] +B[ i][j ] ;
}
}
} /* end of function matmul */

/*Function to print the elements of a matrix */


void display(int X[10][10],int rows ,int cols)
{
inti, j;
for(i = 0; i< rows; i++)
{
for( j = 0; j < cols; j++)
printf("%5d", X[i][j]);
printf("\n");
}
} /* end of function display */

/*Program to multiply two matrices by using functions*/

#include <stdio.h>
main()
{
void readmat(int [][10],int,int);
void matmul(int [][10],int [][10],int [][10],int,int,int);
void display(int [][10],int,int);

int A[10][10], B[10][10], C[10][10],m,n,p,q;

printf("\nEnter size of the matrix A: ");


scanf("%d%d", &m,&n);
printf("\nEnter size of the matrix B: ");
scanf("%d%d", &p,&q);

if(n!=p)
printf("multiplication not possible\n");
else
{
printf("\nEnter elements of matrix A \n");
readmat (A, m,n);

printf("\nEnter elements of matrix B \n");


readmat (B,p,q);

matmul(A, B, C,m,q,n);

printf("Matrix A is :\n");
display(A, m,n);

90
printf("Matrix B is :\n");
display(B, p,q);

printf("\nMATRIX C (= A X B) is:\n");
display(C, m,q);
}
} /* end of main */

/* Function to read the elements of a matrix row-wise */


void readmat(int X[10][10],introws,int cols)
{
inti, j;
for(i = 0; i< rows; i++)
for( j = 0; j < cols; j++)
scanf("%d", &X[i][j]);
} /* end of function read_matrix */

/*Function to multiply m x n and p x q matrices */


void matmul (int A[10][10], int B[10][10], int C[10][10],
int m, int q, int n)
{
inti, j,k;
for(i = 0; i< m; i++)
{
for( j = 0; j < q; j++)
{
C[i][j] =0;
for(k=0; k<n; k++)
{
C[i][j] = C[i][j] +A[i][k] * B[k][j];
}
}
}
} /* end of function matmul */

/*Function to print the elements of a matrix */


void display(int X[10][10],int rows ,int cols)
{
inti, j;
for(i = 0; i< rows; i++)
{
for( j = 0; j < cols; j++)
printf("%5d", X[i][j]);
printf("\n");
}
} /* end of function display */

91
STRINGS: ONE-DIMENSIONAL CHARACTER ARRAYS
Definition:
Strings are defined as an array of characters. The difference between a character array and a string
is the string is terminated with a special character ‘\0’ the null character, which is a character all
of whose bits are zero, i.e., a NUL (not a NULL). (The null character has no relation except in
name to the null pointer. In the ASCII character set, the null character is named NUL.)
Although C does not have a string data type, it allows string constants. For example: ”hello
students” is a string constant.

Declaration of a String:
Strings can be declared like one-dimensional arrays. For example,
char str[30];
char text[80];

String Initialization:
Character arrays or strings allow a shorthand initialization,
for example,
char str[9] = “I like C”;
which is the same as
char str[9] = {‘I’,‘ ’,‘l’,‘i’,‘k’,‘e’,‘ ’,‘C’,‘\0’};
Whenever a string, enclosed in double quotes, is written,C automatically creates an array of
characters containing that string, terminated by the \0 character. C language allows the
alternative notation
char msg[] = “Hello”;
that is always used in practice. It should be noted that the size of the aggregate ‘msg’ is six bytes,
five for the letters and one for the terminating NUL. There is one special case where the null
character is
not automatically appended to the array. This is when the array size is explicitly specified and
the number of initializers completely fills the array size. For example, char c[4] = “abcd”; Here,
the array c holds only the four specified characters, a, b, c, and d. No null character terminates
the array.

String Representation:

String Input and Output:

Printing Strings:
The conversion type ‘s’ may be used for output of strings using printf(). Width and precision
specifications may be used with the %s conversion specifier. The width specifies the minimum

92
output field width; if the string is shorter, then space padding is generated. The precision
specifies the maximum number of characters to display. If the string is too long, it is truncated. A
negative width implies left
justification of short strings rather than the default right justification. For example,
printf(“%7.3s”,name);
This specifies that only the first three characters have to be printed in a total field width of seven
characters and right justified in the allocated width by default. We can include a minus sign to
make it left justified (%-7.3). The following points should be noted:
• When the fi eld width is less than the length of the string, the entire string is printed.
• The integer value on the right side of the decimal point specifies the number of characters
to be printed.
• When the number of characters to be printed is specified as zero, nothing is printed.
• The minus sign in the specification causes the string to be printed as left justified.

Example program:
#include <stdio.h>
int main()
{
char s[]=“Hello, World”;
printf(“>>%s<<\n”,s);
printf(“>>%20s<<\n”,s);
printf(“>>%-20s<<\n”,s);
printf(“>>%.4s<<\n”,s);
printf(“>>%-20.4s<<\n”,s);
printf(“>>%20.4s<<\n”,s);
return 0;
}
Output:

The gets() and puts() are declared in the header file stdio.h. Both the functions are involved in
the input/output operations of the strings.

Using %s control string with scanf()


Strings may be read by using the %s conversion with the function scanf() but there are some
irksome restrictions. The first is that scanf() only recognizes a sequence of characters delimited
by white space characters as an external string. The second is that it is the programmer’s
responsibility to ensure that there is enough space to receive and store the incoming string along
with the terminating null which is automatically generated and stored by scanf() as part of the %s
conversion. The associated parameter in the value list must be the address of the first location in
an area of memory set aside to store the incoming string.
Of course, a field width may be specified and this is the maximum number of characters that are
read in, but remember that any extra characters are left unconsumed in the input buffer. A simple
93
use of scanf() with %s conversions is illustrated in the following program.
int main()
{
char str[50];
printf(“Enter a string”);
scanf(“%s”,str);
printf(“The string was :%s\n”,str);
return 0;
}
Output of sample runs:
(a) Enter a string manas
The string was :manas
(b) Enter a string manasghosh
The string was :manas
(c) Enter a string manas and ghosh
The string was : “manas”

C gets() function

The gets() function enables the user to enter some characters followed by the enter key. All the
characters entered by the user get stored in a character array. The null character is added to the
array to make it a string. The gets() allows the user to enter the space-separated strings. It returns
the string entered by the user.

char[] gets(char[]);

The gets() function is risky to use since it doesn't perform any array bound checking and keep
reading the characters until the new line (enter) is encountered. It suffers from buffer overflow

Example:
#include<stdio.h>
void main ()
{
char s[30];
printf("Enter the string? ");
gets(s);
printf("You entered %s",s);
}

C puts() function

The puts() function is very much similar to printf() function. The puts() function is used to print
the string on the console which is previously read by using gets() or scanf() function. The puts()
function returns an integer value representing the number of characters being printed on the
console. Since, it prints an additional newline character with the string, which moves the cursor
to the new line on the console, the integer value returned by puts() will always be equal to the
number of characters present in the string plus 1

int puts(char[]);
94
Example:
#include<stdio.h>
#include <string.h>
int main(){
char name[50];
printf("Enter your name: ");
gets(name); //reads string from user
printf("Your name is: ");
puts(name); //displays string
return 0;
}

Character Manipulation in the String:


Character functions in <ctype.h> where c is the character argument.

Example:
This program checks whether character is alphanumeric or not.

/* C example program of isalnum().*/


#include<stdio.h>

95
#include<ctype.h>

int main()
{
char ch;

printf("Enter a character: ");


scanf("%c",&ch);

if(isalnum(ch))
printf("%c is an alphanumeric character.\n",ch);
else
printf("%c is not an alphanumericcharacter.\n",ch);

return 0;
}

String Manipulation:
The string header, string.h, provides many functions useful for manipulating strings or character
arrays. Some of these are mentioned below:

Example programs:
The given code shows the use of the strcpy()function.
#include <string.h>

96
int main()
{
char s1[] =“Hello, world!”;
char s2[20];
strcpy(s2, s1);
puts (s2);
return 0;
}
The following program illustrates the comparison of two strings.
#include <stdio.h>
#include <string.h>
int main()
{
char x[50],y[]=“a programming example”;
strcpy(x,“A Programming Example”);
if(strcmp(x,“A Programming Example”) == 0)
printf(“Equal \n”);
else
printf(“Unequal \n”);
if( strcmp(y,x) == 0)
printf(“Equal \n”);
else
printf(“Unequal \n”);
return 0;
}

The following program illustrates the strings concatenation.

int main()
{
char s[30] =“Hello,”;
charstr[] =“world!”;
printf(“%s\n”, s);
strcat(s, str);
printf(“%s\n”, s);
return 0;
}

ARRAYS OF STRINGS: TWO-DIMENSIONAL CHARACTER ARRAY

Declaration:
A two-dimensional array of strings can be declared as follows:

<data_type><string_array_name>[<row_size>][<columns_size>];
Consider the following example on declaration of a two-dimensional array of strings.
char s[5][30];

Initialization:
Two-dimensional string arrays can be initialized as shown

97
char s[5][10] ={“Cow”,”Goat”,”Ram”,”Dog”,”Cat”};
which is equivalent to

Here every row is a string. That is, s[i] is a string.

Note that the following declarations are invalid.


char s[5][] ={“Cow”,“Goat”,“Ram”,”Dog”,“Cat”};
char s[][] ={“Cow”,“Goat”,“Ram”,“Dog”,“Cat”};

Examples:
The following program demonstrates how an individual string of an array of strings can be used
to take input from the user. As mentioned before, each row (i.e., s[i], if ‘s’ is the array of strings)
of an array of strings is a string.
#include <stdio.h>
int main()
{
inti;
char s[10][30], t[30];
for(i=0;i<10;i++)
scanf(“%s”,s[i]);
for(i=0;i<10;i++)
printf(“\n%s”,s[i]);
return 0;
}

The following program sorts an array of strings using bubble sort. Note here that strcmp() is used
to compare the string. strcpy() is used for interchanging the strings.
#include <stdio.h>
#include <string.h>
int main()
{
char s[10][30], t[30];
inti,j,n;
printf(“\n how many strings:”);
scanf(“%d”,&n);
printf(“\n enter the strings:\n”);
for(i=0;i<n;i++)
scanf(“%s”,s[i]);
printf(“\n **starting comparing and sorting**”);
for(i=0;i<n-1;i++)
for(j=i+1; j<n; ++j)
if(strcmp(s[i],s[j])>0)
98
{
strcpy(t,s[i]);
strcpy(s[i],s[j]);
strcpy(s[j],t);
}
printf(“\n **sorted array**\n”);
for(i=0;i<n;i++)
printf(“\n%s”,s[i]);
return 0;
}

UNIT IV

Pointer :
A pointer is a variable that stores the address of another variable. Unlike other variables that hold
values of a certain type, pointer holds the address of a variable. For example, an integer variable holds (or you
can say stores) an integer value, however an integer pointer holds the address of a integer variable.

Definitions:
Call by address: facilitating the changes made to a variable in the called function to become permanently
available in the function from where the function is called.

Call-by-value :A particular way of implementing a function call, in which the arguments are passed by their
value (i.e., their copies).

Dangling pointer: A pointer pointing to a previously meaningful location that is no longer meaningful;
usually a result of a pointer pointing to an object that is de allocated without resetting the value of the pointer.

Dynamic memory allocation :The process of requesting and obtaining additional memory segments
during the execution of a program.

Function pointer: A function has a physical location in memory that can be assigned to a pointer. Then it
is called function pointer. This address is the entry point of the function and it is the address used when the
function is called.

Garbage collection: If only implicit dynamic allocation is allowed then deallocation must also be done
by implicit means, which is often called garbage collection.

NULL : A special C constant, defined as macro in stdio.h as or 0, or (void*)), that can be used as the null
value for pointers.

Null pointer: A null pointer is a special pointer value that points nowhere. I is initialized with value 0 or
NULL.

Pointer : A value or a variable with two attributes:


99
• an address and
a data type of what should be found at that address.

Static memory allocation: Memory layout for static data prepared by the compiler.

Void pointer :A void pointer is a special type of pointer that can point to any data type.

Understanding Memory Addresses:

Memory Layout:

1. Text/Code segment: code and read-only, sharable by several instances of processes


2. Data Segment: Storage for initialized global variables
3. BSS: storage for uninitialized global variables
4. Stack Segment
• Provides storage for local variables declared in functions
100
• Stores housekeeping information involved when function calls are made
• Needed for recursive calls
5. Heap: Reserved for dynamically(run-time) allocating memory for variables
6. Shared libraries: Contains the executable libraries being used by the program
Operators used with Pointer:
1. Address Operator (&) :

• Attributes of variables
• Name
• Location (address)
• Type and value
• Scope, lifetime
• Operations

• The location of a variable is decided by the compiler and the operating system at run-time.

• The initial value of a variable without assigning a value, the result is a garbage value.

• The ampersand (&) operator is used to get the address of a variable


scanf(“%d”, &n);
Example:
• the declaration int i=3;
tells the C compiler to
• reserve space in memory to hold the integer value
• associate the name i with this memory location
• store the value 3 at this location

2. Indirection Operator and Dereferencing :

• The primary use of a pointer is to access and, if appropriate, change the value of the variable that the
pointer is pointing to.

• The other pointer operator available in C is ‘*’, called the ‘value at address’ operator. It returns the
value stored at a particular address. It is also called indirection operator/ dereference operator.
Pointer Variable :

Definition :
A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory
location. Like any variable or constant, you must declare a pointer before using it to store any variable
101
address.
The general form of a pointer variable declaration is
Syntax : type *var-name;

• A pointer provides a way of accessing a variablewithout referring to the variable directly.


• A pointer is a variable that holds the memory addressof another variable.
• A pointer has two parts,
• The address that it holds and
• The value pointed by that address

Pointers can be used to:


• Call by address, thereby facilitating the changes made to a variable in the called function to become
permanently available in the function from where the function is called.
• Return more than one value from a function indirectly.
• Pass arrays and strings more conveniently from one function to another.
• Manipulate arrays more easily by moving pointers to them (or to parts of them) instead of moving the arrays
themselves.
• Create complex data structures, such as linked lists and binary trees, where one data structure must contain
references to other data structures.
• Communicate information about memory, as in the function malloc()
which returns the location of free memory by using a pointer.
• Compile faster, more efficient code than other derived data types such as arrays.

Declaring a Pointer – Pointer Declaration :


• Like other variables, in a program, a pointer has to be declared.
• A pointer will have a
• value, scope, lifetime, and name.
• Pointers will occupy a certain number of memory locations.
• The pointer operator available in C is ‘*’ , called ‘value at address’ operator.
• The syntax for declaring a pointer variable is
datatype * pointer_variable
• The data type of pointer and the variable must match, an int pointer can hold the address of int variable,
similarly a pointer declared with float data type can hold the address of a float variable.
Declaration What it means
int p p is an integer
int *p p is a pointer to an integer
char p p is a character
char *p p is a pointer to a character
long p p is a long integer

102
long *p p is pointer to a long integer
unsigned char p P is an unsigned character
unsigned char *p P is pointer to an unsigned character
Some Pointer Variable Declarations
Example:

/* Program to illustrate Pointer Variable Declaration*/


#include<stdio.h>
int main( )
{
int *p;
float *q;
double *r;
printf(“\n the size of integer pointer is %d”, sizeof(p));
printf(“\n the size of fl oat pointer is %d”, sizeof(q));
printf(“\n the size of double pointer is %d”,sizeof(r));
printf(“\n the size of character pointer is %d”, sizeof(char*));
return 0;
}
Output :
In Turbo C:
the size of integer pointer is 2
the size of fl oat pointer is 2
the size of double pointer is 2
the size of character pointer is 2
In GCC:
the size of integer pointer is 4
the size of fl oat pointer is 4
the size of double pointer is 4
the size of character pointer is 4

Initializing Pointers :

A Pointer is similar to any other variable excepts that it holds only memory address and therefore it needs
to be initialized with a valid address before it can be used.

• Unlike a simple variable that stores a value, a pointer must be initialized with a specified address prior
to its use.

103
•A pointer should be initialized with another variable’s memory address, with 0, or with the keyword
NULL prior to its use; otherwise the result may be a compiler error or a run-time error.
Example :
#include <stdio.h>
int main()
{
int *p; /* a pointer to an integer */
printf(“%d\n”,*p);
return 0;
}

Assigning Pointers :

• A pointer is bound to a specific data type (except pointer to void) . A pointer to an int cannot hold the
address of a character variable in which case a compiler error would result.
• The following pointer initializations are invalid.
int a=6, *ip;
float *p;
char ch=’A’;
p=&a;
ip=&ch:
om the Below Figure :
• r points to the same address that p points to, which is the address of i.
• We can assign pointers to one another, and the address is copied from the right-hand side to the
left- hand side during the assignment.

Printing pointer value :

• To print the memory address stored in pointers and non-pointer variables using the %p conversion specifier
and to learn the use of the %p conversion specifier.
104
• Addresses must always be printed using %u or %p or %x. If %p is used, the address is printed in
hexadecimal form. If %u is used, address is printed in decimal form.

Example 1 :
/* Program to illustrate Pointer Initialization*/
#include <stdio.h>
int main(void)
{
int a=20, *p;
*p=&a;
printf(“\n*p = %p”, *p);
return 0;
}
Example 2 :
/* Program to illustrate printing Pointer Value*/
#include <stdio.h>
int main(void)
{
int a=20, *p;
p=&a;
printf(“\n*p = %p”, *p);
return 0;
}
Output:
p = 0022FF2C

Is it possible to assign a constant to a pointer variable?

• No
• In C, pointers are not allowed to store any arbitrary memory address, but they can only store addresses
of variables of a given type.
• Consider the following code:
int *pi;
pi= (int*)1000;
*pi = 5;
• Location 1000 might contain the program. Since it is a read only, the OS will throw up a segmentation
fault.

Example:
/* Program to illustrate printing Pointer Value*/
#include <stdio.h>
int main()
105
{
int num = 15;
int *iPtr = &num;
printf(“ The value of a num is %d”, num);
num = 100;
printf(“ The value of a num after num=10 is %d”, num);
*iPtr = 25;
printf(“ The value of a num after *iPtr = 15 is %d”, num);
}

Output:
The value of num is 15
The value of num after num = 100 is 100
The value of num after *iPtr = 25 is 25

Void Pointer :
•A void pointer is a special type of pointer.
•It can point to any data type, from an integer value or a float to a string of characters.
•Its sole limitation is that the pointed data cannot be referenced directly (the asterisk * operator cannot
be used on them) since its length is always undetermined. Use type casting or assignment
Example:
/* Program to illustrate Void Pointer */

int main()
{
int a=10,
double b=3.1415;
void *vp;
vp=&a;
printf(“\n a=%d”, *((int*)vp));
vp=&b;
printf(“\n a= %d”, *((double *)vp));
return 0;
}
Output :
a= 10
b= 3.141500
Null Pointer :
• Null pointer is a special pointer that points nowhere. That is, no other valid pointer to any other variable
106
or array cell or anything else will ever be equal to a null pointer.
#include <stdio.h>
int *ip = NULL;
• It is also possible to refer to the null pointer using a constant 0,
int *ip = 0;
• NULL is a constant that is defined in the standard library and is the equivalent of zero for a pointer.
• NULL is a value that is guaranteed not to point toany location in memory.
Use of Pointers :

Call by reference : One of the typical applications of pointers is to support call by reference. However, C does
not support call by reference as do other programming languages such as PASCAL and FORTRAN.
• Typically a function call is made to communicate some arguments to the function.
• C makes use of only one mechanism to communicate arguments to a function: call by
value.
• This means that when a function is called, a copy of the values of the arguments is created
and given to the function.
• Call by reference: Simulated by the use of pointers called “call by address”.

Example:
/* Program to illustrate call by Value*/
void swap(int a, int b)
{
int temp; temp=a; a=b; b=temp;
}
int main()
{
int x=5,y=10;
void swap(int,int); printf(“%d %d\n”,x,y);
swap(x,y);
printf(“%d %d\n”,x,y);
return 0;
}

Output:
5 10
5 10 No swapping

/* Program to illustrate call by Address*/


void swap(int *a, int *b)
{
int temp; temp = *a;
107
*a = *b;
*b = temp;
}
int main()
{
int x=5,y=10;
void swap(int *,int *);
printf(“%d %d\n”,x,y);
swap(&x, &y);
printf(“%d %d\n”,x,y); return 0;
}

Output:
5 10
10 5
Returning more than one value from a function:

• Pointers allow the programmer to return more than one value

Example :

Program to print area by illustrating returning more than one value from a function*/

#include <stdio.h>

int main()

float r, area, perimeter;


float compute(fl oat, fl oat *); //function prototype
printf(“\n enter the radius of the circle:”);
scanf(“%f”,&r);
area=compute(r, &perimeter); //function call
printf(“\n AREA = %f”, area);
printf(“\n PERIMETER = %f”, perimeter); return 0;
}
float compute(float r, fl oat *p)
{
float a;
a=(fl oat)3.1415 * r * r;
*p=(fl oat)3.1415 * 2 * r;
return a;
}
108
Arrays and Pointers :

One-dimensional Arrays and Pointers :

• An array is a non-empty set of sequentially indexed elements having the same type of data.
• Each element of an array has a unique identifying index number. Changes made to one element of
an array does not affect the other elements.
• An array occupies a contiguous block of memory. The array a is laid out in memory as a contiguous
block, as shown.

The below figure demonstrates the memory allocation strategy of Arrays :

• Array name is an pointer constant. It cannot be used as lvalue.


• Array names cannot be used as variables on the left of an assignment operator.
• Both array and &array would give the base address of the array, but the only difference is under
ANSI/ISO Standard C, &array yields a pointer, of type pointer to- array of-the data type to the entire
array.

Example :
/* Program to illustrate arrays*/
#include <stdio.h>
int main()
{
int array[]={10, 20, 30, 40, 50};
printf(“%u %u”, array, &array[0]);
return 0;
}
Output:
2147478270
2147478270

A pointer variable (of the appropriate type) can also be used to initialize or point to the
first element of the array.

109
Below figure depicts the equivalence among array notation and pointer notation.

Passing Array to a Function :

• For any one-dimensional array a and integer i, the following relationships are always true.
a[i] ≡ *(a+i) ≡ *(i+a) ≡ i[a]
• An array may be passed to a function, and the elements of that array may be modified without

110
having to worry about referencing and dereferencing.

When an array is passed to a function, it degenerates to a pointer.

• All array names that are function parameters are always converted into pointers by the compiler.
• Because when passing an array to a function, the address of the zero-th element of the array is copied to
the pointer variable which is the formal parameter of the function.
• However, arrays and pointers are processed differently by the compiler, represented differently at runtime.
Differences between Array Name & Pointer :

• When memory is allocated for the array, the starting address is fixed, i.e., it cannot be changed during
program execution. Therefore, array name is an address constant.
• The & (address of) operator normally returns the address of the operand. However, arrays are the
exception.
• When applied to an array (which is an address), it has the same value as the array reference without the
operator.
• This is not true of the equivalent pointers, which have an independent address.
• The sizeof operator returns the
• Size of the allocated space for arrays in case of arrays.
• 4 or 8 bytes depending on the machine architecture.

fference Between Arrays and Pointers :

Arrays Pointers
Array allocate space automatically It is explicitly assigned to point to an allocated

111
space
It cannot be resized It can be resized using realloc( )
It cannot be reassigned It can be reassigned
sizeof(arrayname) gives the number of bytes sizeof(p) gives the number of bytes used to
occupied by the array store the pointer variable p

Pointer Arithmetic :

A pointer in c is an address, which is a numeric value. Therefore, you can perform arithmetic operations on a
pointer just as you can on a numeric value. There are four arithmetic operators that can be used on pointers:
++, --, +, and –

Pointer Arithmetic - Valid :


The only valid operations on pointers are as follows.
1) Assignment of pointers to the same type of pointers: the assignment of pointers is done
symbolically. Hence no integer constant except 0 can be assigned to a pointer.
2) Adding or subtracting a pointer and an integer.
3) Subtracting or comparing two pointers (within array limits) that point to the elements of an
array Pointer Arithmetic - Valid
4) Incrementing or decrementing the pointers (within array limits) that point to the elements of
an array.
• When a pointer to an integer is incremented by one, the address is incremented by
two (as two bytes are used for int).
• Such scaling factors necessary for the pointer arithmetic are taken care of
automatically by the compiler.
5) Assigning the value 0 to the pointer variable and comparing 0 with the pointer. The pointer
with address 0 points to nowhere at all.

Pointer Arithmetic- not Valid


1. Addition of two pointers
2. Multiplying a pointer with a number
3. Dividing a pointer with a number

112
Important Points - Pointer Arithmetic:

Pointers and Strings :


• Strings are one-dimensional arrays of type char. By convention, a string in C is terminated by the end-
of-string sentinel \0, or null character.
• A string constant is treated by the compiler as a pointer.
• For a string, the number of elements it has need not be passed to a function because it has the
terminating null character

Array of Pointers :
• An array of pointers can be declared very easily.
Example: int *p[20];
• Declares an array of 20 pointer, each of which points to an integer.
• 1st pointer is p[0], 2nd is p[1], and so on up to p[19].
• These start off as uninitialized—they point to some unknown point in memory. We could make
them point to integer variables in memory thus.

Example :

113
Pointers to Array : We can declare a pointer to a simple integer value and make it point to the array as is
done normally.
Example :
int v[5] = {1004, 2201, 3000, 432, 500};
int *p = v;
printf(“%d \n”, *p);
This piece of code displays the number, which the pointer p points to, that is the first number in the array,
namely 1004. We can use instructions such as += and -= to refer to different elements in the array.

114
Difference between an array of pointers and a pointer to an array

Array of Pointer Pointer to an Array


Declaration Declaration
Data_type * array_name[SIZE]; Data_type (* array_name)[SIZE];
Size represents the number of rows Size represents the number of columns
The space for columns may be allotted The space for rows may be dynamically
115
allotted

Two-dimensional array and Pointers :

A two-dimensional array in C is treated as a one dimensional array whose elements are one-dimensional arrays
(the rows).
• C does not do run-time range checking of array subscripts.
• In C the rightmost subscript of a two-dimensional array varies faster than the leftmost.
• Multi-dimensional array is stored in a ‘row major addressing’ format.
• The following expressions are equivalent for a two dimensional array
a[i][j]= *(a[i]+ j) = (*(a + i))[j] = *(*(a + i)+ j)
• Arrays of dimension higher than two work in a similar fashion.
• Let us describe how three-dimensional arrays work.
• If the following is declared
int a[7][9][2];
• In case of multi-dimensional arrays all sizes except the first must be specified.

Logical representation of a two-dimensional array

116
Physical representation of a two-dimensional array

Example 1 :

/* Program to illustrate matrix addition – two dimensional array*/

void getdata(int x[10][10], int m, int n)


{
for(int i=0;i<m;++i) for(int j=0;j<n;++j)
scanf("%d",&x[i][j]); return;
}
void display(int x[10][10], int m, int n)
{
for(int i=0;i<m;++i)
{
for(int j=0;j<n;++j) printf("%4d",x[i][j]);
printf("\n");
}
return;
}
void add(int x[10][10],int y[10][10],int z[10][10],int m,int n)
{
for(int i=0;i<m;++i) for(int j=0;j<n;++j)
z[i][j] = x[i][j] + y[i][j];
return;
}
int main()
{
int A[10][10],B[10][10],C[10][10],T[10][10],m,n;
printf("\nEnter the values of m and n: ");

117
scanf("%d %d",&m,&n);
printf("\nEnter the elements of A: ");
getdata(A,m,n);
printf("\nEnter the elements of B: ");
getdata(B,p,q);
printf("\nGiven matrix A is:\n");
display(A,m,n);
printf("\nGiven matrix B is:\n");
display(B,p,q);
add(A,B,C,m,n);
printf("\nGiven Resultant matrix C is:\n");
display(C,m,n);
return 0;
}

Example 2 :

/* matrix addition – Array of pointers*/

int *A[10],*B[10],*C[10],m, n, i;
printf("\nEnter the values of m and n: ");
scanf("%d %d",&m,&n); //read the values of m and n
for(i=0;i<m;++i) //allocate memory dynamically
{
A[i]=(int*)malloc(n*sizeof(int));
B[i]=(int *)malloc(n*sizeof(int));
C[i]=(int *)malloc(n*sizeof(int));
}
getdata(A,m,n);
getdata(B,m,n);
add(A,B,C,m,n);
display(C,m,n);

Example 3 :

/* matrix addition – Use of pointers*/

void getdata(int *x[10], int m, int n)


{
118
for(int i=0;i<m;++i) for(int j=0;j<n;++j)
scanf("%d",x[i]+j); //or &x[i][j] or *(x+i)+j
return;
}
void display(int *x[10], int m, int n)
{
for(int i=0;i<m;++i)
{
for(int j=0;j<n;++j)
printf("%4d",*(x[i]+j)); //or x[i][j] or *(*(x+i)+j)

printf("\n");
}
return;
}

Example 4 :

/* matrix addition – Pointer to 2-D array */

int **A,**B,**C, i, m, n;
printf("\nEnter the values of m and n: "); scanf("%d %d",&m,&n);
//read the values of m and n
for(i=0;i<m;++i)
A[i]=(int *)malloc(n*sizeof(int)); for(i=0;i<m;++i)
B[i]=(int *)malloc(n*sizeof(int)); for(i=0;i<m;++i)
C[i]=(int *)malloc(n*sizeof(int));
Example 5 :

/* matrix addition – Using Pointers - Pointer to 2-D array */

void getdata(int **x, int m, int n)


{
for(int i=0;i<m;++i) for(int j=0;j<n;++j)
scanf("%d", *(x+i)+j); //or &x[i][j] or *(x+i)+j or (x+i)[j]
return;
}
void display(int *x[10], int m, int n)
{
for(int i=0;i<m;++i)
{
for(int j=0;j<n;++j)
printf("%4d",*(*(x+i)+j)); //or x[i][j] or *(*(x+i)+j) or *(x+i)[j]

119
printf("\n");
}
return;
}

Pointers to Functions :
C also allows pointers to point to functions and it is one of the powerful feature
Declaration of a Pointer to a Function
return_type (*fptr) (argument_type1, argument_type2, ..);
xample:
int(*fp)(int, char, float); //fp is a pointer to a function that take one int, one char, one float
and returns an int

• Parenthesis are important and int *fp(); declares a function that returns an integer pointer

Initialization of Function Pointers:


r example , two functions are declared as:
int add(int, int); and int sub(int, int);
• The names of these functions, add and sum, are pointers to those functions. These can be assigned to
pointer variables.
fptr = add;
fptr = sub;

Calling a Function using a Function Pointer :


For example:
fptr=add; then the function call via function pointer will be:
result1 = fptr(4, 5); will return 9
fptr=sub;
result2 = fptr(6, 2); will return 4.

assing a Function to another Function:

function pointer can be passed as a function’s calling argument.


• How to Return a Function Pointer
float(*GetPtr1(char opCode))(float, float)
{
if(opCode == ‘+’) return &Add; if(opCode == ‘-’)
return &Sub;
}
A solution using a typedef defines a pointer to afunction that takes two float values and returns a float.

Arrays of Function Pointers:


120
Example :
/* Program – Arrays of Function Pointers */

void Add(int a, int b)


{
printf(“\n Result of Addition = %d”,a+b);
}
void Sub(int a, int b)
{
printf(“\n Result of Subtraction = %d”,a-b);
}
void Mul(int a, int b)
{
printf(“\n Result of Multiplication = %d”,a*b);
}
int main()
{
void(*p[3])(int, int);
int i;
void Add(int, int);
void Sub(int, int);
void Mul(int, int);
p[0] = Add;
p[1] = Sub;
p[2] = Mul;
for(i = 0; i <= 2; i++)
(*p[i])(10, 5);
return 0;
}

Dynamic Memory Allocation :

Static memory allocation :

• Compiler allocates the required memory space for a declared variable.


• By using the address of operator, the reserved address is obtained that maybe assigned to a pointer
variable.
• Since most declared variables have static memory, this way of assigning pointer value to a pointer
variable is known as static memory allocation.
Dynamic memory allocation :

• A dynamic memory allocation uses functions such as malloc() or calloc() realloc() to get memory
dynamically.
• If these functions are used to get memory dynamically and the values returned by these functions are
121
assigned to pointer variables, such assignments are known as dynamic memory allocation.
• Memory is assigned during run-time.
• In dynamic memory allocation, memory is allocated at runtime from heap.According to
• ANSI compiler, the malloc() and calloc() returns a void pointer on successful allocation of memory. If
sufficient memory is not available, the malloc() and calloc() returns a NULL.
• calloc() initializes all the bits in the allocated space set to zero where as malloc() does not do this.
• When dynamically allocated, arrays are no longer needed, it is recommended to free them immediately.

Dynamic Allocation of Arrays:


To allocate a one-dimensional array of length N of some particular type where N is given by the user,
simply use malloc() to allocate enough memory to hold N elements of the particular type.
Example :
/* Program – Dynamic memory Allocation */

#includestdio.h>
#include<stdlib.h>
int main()
{
int N,*a,i,s=0;
printf(“\n enter no. of elements of the array:”);
scanf(“%d”,&N);
a=(int *)malloc(N*sizeof(int));
if(a==NULL)
{
printf(“\n memory allocation unsuccessful...”);
exit(0);
}
printf(“\n enter the array elements one by one”);
for(i=0; i<N;++i)
{
scanf(“%d”,&a[i])); /* equivalent statement
scanf(“%d”,(a+i));*/
s+=a[i];
}
printf(“\n sum is %d ”,s); return 0;
}

Freeing Memory :

• Dynamically allocated memory is de-allocated with the free function. If p contains a pointer previously
returned by malloc(), a call such as free(p);
• calloc() requires two parameters, the first for the number of elements to be allocated and the second for the
size of each element, whereas malloc() requires one parameters.

122
• calloc() initializes all the bits in the allocated space set to zero whereas malloc() does not do this.
• P=calloc(m, n) is essentially equivalent to p = malloc(m * n);
• malloc(0) results are unpredictable. It may return some other pointer or it may return some other
implementation-dependent value.

Reallocating Memory Blocks :

• malloc() will not work. It is the realloc() function that is required


ip = realloc(ip, 200 * sizeof(int));

Implementing Multidimensional Arrays using Pointers:


It is usually best to allocate an array of pointers, and then initialize each pointer to a dynamically allocated
‘row’.

Memory Leak and Memory Corruption


Dangling pointer :
A pointer may be used to hold the address of dynamically allocated memory. After this memory is freed with
the free() function (in C), the pointer itself will still contain the address of the released block. This is referred to
as a dangling pointer.
Memory corruption :
Memory when altered without an explicit assignment due to the inadvertent and unexpected altering of data
held in memory or the altering of a pointer to a specific place in memory is known as memory corruption.

Advantages of Pointers :
• Pointers save memory space
• Execution time with pointer is fast because data is manipulated with address i.e directly with
memory location.
• Memory is accessed efficiently with pointers
• Dynamic memory is allocated

123
• Pointers are used with data structures.
• Pointers are useful for representing two dimensional and multi dimensional Arrays.

Drawbacks of Pointers :

• A programmer is likely to commit mistakes such as typographical mistakes and providing wrong offsets.
• Porting the code to other implementations would require changes, if data type sizes differ. This would lead
to portability issues.
• Pointers have data types but the size of a pointer variable is always 4-bytes (in a 32-bit machine) 8-bytes (in
a 64-bt machine) whatever the data type is used in declaring it.

Structures

Definition

Arrays allow defining type of variables that can hold several data items of the same kind. Similarly
structure is another user defined data type available in C that allows combining data items of different kinds.
Structures are used to represent a record. Suppose you want to keep track of your books in a library.
You might want to track the following attributes about each book−

Title Author Subject Book ID

Defining a Structure

To define a structure, you must use the struct statement. The struct statement defines a new data type,
with more than one member. The format of the struct statement is as follows –

struct structure_name{ data_type struct_member1; data_typestruct_member2;

data_typestruct_member n;
} [one or more structure variables separated by comma];

The structure_nameis optional and each struct_memberis a normal variable definition, such as int i; or
float f; or any other valid variable definition. At the end of the structure's definition, before the final semicolon,
you can specify one or more structure variables but it is optional.
Here is the way you would declare the Book structure –

struct Books
{
char title[50]; char author[50]; char subject[100]; intbook_id;
}book;

124
Accessing Structure Members

To access any member of a structure, we use the member access operator (.). The member access
operator is coded as a period between the structure variable name and the structure member that we wish to
access. You would use the keyword structto define variables of structure type.

The following example shows how to use a structure in a program

#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};

int main( )
{

Struct Books Book1; /* Declare Book1 of type Book */ structBooksBook2; /* Declare Book2 of type
Book*/
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
/* print Book1 info */
printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 author : %s\n", Book1.author);
printf( "Book 1 subject : %s\n",Book1.subject);
printf( "Book 1 book_id : %d\n", Book1.book_id);
/* print Book2 info */
printf( "Book 2 title : %s\n", Book2.title);
printf( "Book 2 author : %s\n", Book2.author);
printf( "Book 2 subject : %s\n",Book2.subject);

125
printf( "Book 2 book_id : %d\n", Book2.book_id); return 0;
}

When the above code is compiled and executed, it produces the following result
Book 1 title : C Programming
Book 1 author :Nuha Ali

Book 1 subject : C Programming Tutorial Book 1 book_id : 6495407


Book 2 title : Telecom Billing

Book 2 author : Zara Ali


Book 2 subject : Telecom Billing Tutorial Book 2 book_id : 6495700

Nested structures
Structure written inside another structure is called as nesting of two structures. Nested Structures are
allowed in C Programming Language. We can write one Structure inside another structure as member of
another structure.
Example:
structdate
{
int date; int month; int year;
};

struct Employee
{
charename[20];
intssn;
float salary;
struct date doj;
}emp1;

Accessing the nested elements

Structure members are accessed using dot operator. ‘date‘ structure is nested within Employee
Structure. Members of the ‘date‘ can be accessed using ’employee’ emp1 &doj are two structure
names (Variables)

Explanation of nested elements:

Accessing Month Field : emp1.doj.month Accessing day Field : emp1.doj.day Accessing year Field
:emp1.doj.year

126
The following example shows how to use nested structure in a program

#include <stdio.h>
struct Employee
{
charename[20];
int ssn;
float salary;
struct date
{
int date;
int month;
int year;
}doj;
}emp = {"Pritesh",1000,1000.50,{22,6,1990}};

int main(intargc, char *argv[])


{
printf("\nEmployee Name : %s",emp.ename);
printf("\nEmployeeSSN : %d",emp.ssn);
printf("\nEmployee Salary : %f",emp.salary);
printf("\nEmployeeDOJ : %d/%d/%d", \ emp.doj.date,emp.doj.month,emp.doj.year);
return0;
}

When the above code is compiled and executed, it produces the following result

Employee Name :Pritesh Employee SSN : 1000 Employee Salary : 1000.500000 EmployeeDOJ
: 22/6/1990

Arrays of Structures
We may declare the structure variable as an array by using index. Arrays of structures are passed using
the following syntax,
structstructure_name{ data_type struct_member1; data_typestruct_member2;

data_typestruct_membern;
};
structstructure_namestruct_variable[index_value];

Example: #include<stdio.h> #include<conio.h> void main()


{
struct student
{
127
intrno;
char name[20]; char course[20]; float fees;
};
struct student s[20]; clrscr();
s[0].rno=10; gets(s[0].name);
gets(s[0].course); s[0].fees=1000.50;
printf("\n %d\t %s\t%s\t%f",s[0].rno,s[0].name,s[0].course,s[0].fees);
getch();
}

Structures as Function Arguments

You can pass a structure as a function argument in the same way as you pass any other variable or
pointer. Like all other types, we can pass structures as arguments to a function. In fact, we can pass individual
members, structure variables, a pointer to structures etc to the function. Similarly, functions can return either
an individual member or structures variable or pointer to the structure.

Passing Structure Members as arguments to Function

We can pass individual members to a function just like ordinary variables.The following program demonstrates
how to pass structure members as arguments to the function.
1 #include<stdio.h>
2
3 /*
4 structure is defined above all functions so it is global.
5 */
6
7 structstudent
8{
9 charname[20];
10introll_no;
11intmarks;
12};
13
14voidprint_struct(charname[],introll_no,intmarks);
15
16intmain()
17{
18structstudentstu={"Tim",1,78};
19print_struct(stu.name,stu.roll_no,stu.marks);
20return0;
21}

128
22
23voidprint_struct(charname[],introll_no,intmarks)
24{
25printf("Name: %s\n",name);
26printf("Roll no: %d\n",roll_no);
27printf("Marks: %d\n",marks);
28printf("\n");
29}
When the above code is compiled and executed, it produces the following result
Name: Tim
Roll no: 1
Marks: 78

Flow of Execution of the above code :

• In lines 7-12, a structure student is declared with three members namely name, roll_no and marks.
• In line 14, a prototype of function print_struct() is declared which accepts three arguments namely
name of type pointer to char, roll_no of type int and marks is of type int.
• In line 18, a structure variable stu of type struct student is declared and initialized.
• In line 19, all the three members of structure variable stu are passed to the print_struct() function. The
formal arguments of print_struct() function are initialized with the values of the actual arguments.
• From lines 25-27, three printf() statement prints name, roll_no and marks of the student.
• The most important thing to note about this program is that stu.name is passed as a reference because
name of the array is a constant pointer. So the formal argument of print_struct() function i.e name
and stu.name both are pointing to the same array. As a result, any changes made by the
function print_struct() will affect the original array. We can verify this fact by making the following
amendments to our program.

Passing Structure variable as argument to a Function


In the earlier section, we have learned how to pass structure members as arguments to a function. If a structure
contains two-three members then we can easily pass them to function but what if there are 9-10 or more
members? Certainly passing 9-10 members is a tiresome and error-prone process. So in such cases instead of
passing members individually, we can pass structure variable itself.
The following program demonstrates how we can pass structure variable as an argument to the function.
1 #include<stdio.h>
2
3 /*
4 structure is defined above all functions so it is global.
5 */
6
7 structstudent
8{
9 charname[20];
129
10introll_no;
11intmarks;
12};
13
14voidprint_struct(structstudentstu);
15
16intmain()
17{
18structstudentstu={"George",10,69};
19print_struct(stu);
20return0;
21}
22
23voidprint_struct(structstudentstu)
24{
25printf("Name: %s\n",stu.name);
26printf("Roll no: %d\n",stu.roll_no);
27printf("Marks: %d\n",stu.marks);
28printf("\n");
29}
When the above code is compiled and executed, it produces the following result
Name: George
Roll no: 10
Marks: 69

Flow of Execution of the above code

• In lines 7-12, a structure student is declared with three members namely: name, roll_no and marks.
• In line 14, the prototype of function print_struct() is declared which accepts an argument of type struct
student.
• In line 18, a structure variable stu of type struct student is declared and initialized.
• In line 19, print_struct() function is called along with argument stu. Unlike arrays, the name of structure
variable is not a pointer, so when we pass a structure variable to a function, the formal argument
of print_struct() is assigned a copy of the original structure. Both structures reside in different memory
locations and hence they are completely independent of each other. Any changes made by
function print_struct() doesn't affect the original structure variable in the main() function.
• The printf() statements from lines 25-27 prints the details of the student.

Returning Structure from Function

Just as we can return fundamental types and arrays, we can also return a structure from a function. To return a
130
structure from a function we must specify the appropriate return type in the function definition and declaration.
Consider the following example:
struct player check_health(struct player p);
{
...
}

This function accepts an argument of type struct player and returns an argument of type struct player.
The following program demonstrates how we can return a structure from a function.
1 #include<stdio.h>
2
3 /*
4 structure is defined above all functions so it is global.
5 */
6
7 structplayer
8{
9 charname[20];
10floatheight;
11floatweight;
12floatfees;
13};
14
15voidprint_struct(structplayerp);
16structplayerdeduct_fees(structplayerp);
17
18intmain()
19{
20structplayerp={"Joe",5.9,59,5000};
21print_struct(p);
22p=deduct_fees(p);
23print_struct(p);
24
25return0;
26}
27
28structplayerdeduct_fees(structplayerp)
29{
30p.fees-=1000;
31returnp;
32}
33
34voidprint_struct(conststructplayerp)

131
35{
36printf("Name: %s\n",p.name);
37printf("Height: %.2f\n",p.height);
38printf("Weight: %.2f\n",p.weight);
39printf("Fees: %.2f\n",p.fees);
40
41printf("\n");
42}
When the above code is compiled and executed, it produces the following result
Name: Joe
Height: 5.90
Weight: 59.00
Fees: 5000.00

Name: Joe
Height: 5.90
Weight: 59.00
Fees: 4000.00

Flow of Execution of the above code

• In lines 7-13, a structure of type player is declared with 4 members


namely name, height, weight and fees.
• In line 15, the prototype of print_struct() is declared which accepts an argument of type struct
player and returns nothing.
• In line 16, the prototype of deduct_fees() is declared which accepts an argument of type struct
player and returns a structure of type struct player.
• In line 20, a structure variable p of type struct player is declared and initialized.
• In line 21, the print_struct() function is passed an argument of type struct player. The function prints
the details of the player and passes the control back to main() function.
• In line 22, deduct_fees() function is called with an argument of type struct player. The function
decrements the fees of the player by 1000 using the statement.
• p.fees -= 1000;
• and then returns the structure variable p to the called function i.e main(), where it is assigned back to
the variable p.
• In line 23, the print_struct() is called again with the same argument as before to check whether the
details have been modified by deduct_fees() or not.
• After printing the details of the function the control passes back to main() function and the program
terminates.

Pointers to Structures

You can define pointers to structures in the same way as you define pointer to any other variable –
132
struct Books *struct_pointer;

Now, you can store the address of a structure variable in the above defined pointer variable. To find the
address of a structure variable, place the '&'; operator before the structure's name as follows –

struct_pointer = &Book1;

To access the members of a structure using a pointer to that structure, you must use the
→ operator as follows –
struct_pointer->title;

The following program demonstrates how to access structure members using pointers.
#include <stdio.h>
#include <string.h>
struct Books{
chartitle[50];
char author[50];
char subject[100];
int book_id;
};
/* function declaration */ voidprintBook(struct Books *book ); int main( ) {
structBooksBook1; /* Declare Book1 of type Book */ structBooksBook2; /* Declare Book2 of type
Book*/

/* book 1 specification */
strcpy( Book1.title, "C Programming"); strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial"); Book1.book_id = 6495407;

/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;

/* print Book1 info by passing address of Book1 */ printBook(&Book1);


/* print Book2 info by passing address of Book2 */ printBook(&Book2);
return 0;
}
voidprintBook( struct Books *book )
{
printf( "Book title : %s\n", book->title);
printf( "Book author : %s\n", book->author);
printf( "Book subject : %s\n", book->subject);

133
printf( "Book book_id : %d\n", book->book_id);
}
When the above code is compiled and executed, it produces the following result – Book title : C Programming
Book author :Nuha Ali
Book subject : C Programming Tutorial Book book_id : 6495407
Book title : Telecom Billing Book author : Zara Ali
Book subject : Telecom Billing Tutorial Book book_id : 6495700

Self Referential Structures


Self Referential structures are those structures that have one or more pointers which
point to the same type of structure, as their member.

In other words, structures pointing to the same type of structures are self-referential in nature.
Example:
structnode {
intdata1;
chardata2;
structnode* link;
};

intmain()
{
structnode ob;
return0;
}
In the above example ‘link’ is a pointer to a structure of type ‘node’. Hence, the structure ‘node’ is a self-
referential structure with ‘link’ as the referencing pointer.
An important point to consider is that the pointer should be initialized properly before accessing, as by default it
contains garbage value.

134
The following Program to demonstrate Self referential structure.
#include <stdio.h>

structnode {
intdata1;
chardata2;
structnode* link;
};

Int main()
{
structnode ob1; // Node1

// Initialization
ob1.link = NULL;
ob1.data1 = 10;
ob1.data2 = 20;

struct node ob2; // Node2

// Initialization
ob2.link = NULL;
ob2.data1 = 30;
ob2.data2 = 40;

// Linking ob1 and ob2


ob1.link = &ob2;

// Accessing data members of ob2 using ob1


printf("%d", ob1.link->data1);
printf("\n%d", ob1.link->data2);
return0;
}
When the above code is compiled and executed, it produces the following result
30
40

Unions
A union is a special data type available in C that allows storing different data types in the same
memory location. You can define a union with many members, but only one member can contain a value at
any given time. Unions provide an efficient way of using the same memory location for multiple-purpose.

135
Defining a Union

To define a union, you must use the union statement in the same way as you did while defining a
structure. The union statement defines a new data type with more than one member for your program. The
format of the union statement is as follows–

union [union tag] { member definition; member definition;


...
member definition;
} [one or more union variables];

The union tag is optional and each member definition is a normal variable definition, such as int i; or
float f; or any other valid variable definition. At the end of the union's definition, before the final semicolon,
you can specify one or more union variables but it is optional. Here is the way you would define a union type
named Data having three members i, f, and str–

union Data { int i;


float f;
char str[20]
} data;

Now, a variable of Data type can store an integer, a floating-point number, or a string of characters. It
means a single variable, i.e., same memory location, can be used to store multiple types of data. You can use
any built-in or user defined data types inside a union based on your requirement.
The memory occupied by a union will be large enough to hold the largest member of the union. For
example, in the above example, Data type will occupy 20 bytes of memory space because this is the maximum
space which can be occupied by a character string.

The following example displays the total memory size occupied by the above union –

#include <stdio.h>
#include <string.h>
union Data {
inti; float f;
char str[20];
};

Int main( )
{
union Data data;
printf("Memorysizeoccupiedbydata:%d\n",sizeof(data));
return0;
}

136
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult– Memorysizeoccupiedbydata:20
Accessing Union Members

To access any member of a union, we use the member access operator (.). The member access
operator is coded as a period between the union variable name and the union member that we wish to access.
You would use the keyword union to define variables of union type.

The following example shows how to use unions in a program −

#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
data.i = 10;
data.f = 220.5;
strcpy(data.str, "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);
return 0;
}
When the above code is compiled and executed, it produces the following result – data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming

Here, we can see that the values of i and f members of union got corrupted because the final value
assigned to the variable has occupied the memory location and this is the reason that the value of str member
is getting printed very well.
Now let's look into the same example once again where we will use one variable at a time which is the main
purpose of having unions –

#include <stdio.h>
#include <string.h>
union Data
{

137
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
strcpy(data.str, "C Programming");
printf( "data.str : %s\n", data.str);
return 0;
}
When the above code is compiled and executed, it produces the following result – data.i : 10
data.f : 220.500000
data.str : C Programming

Here, all the members are getting printed very well because one member is being used at a time.

Enumerated data types


Enumeration is a user defined data type in C language. It is used to assign names to the integral
constants which makes a program easy to read and maintain. The keyword “enum” is used to declare an
enumeration.
Here is the syntax of enum in C language,
Enum enum_name{const1, const2, ....... };

The enum keyword is also used to define the variables of enum type. There are two ways to define the
variables of enum type as follows.

enum week{sunday, monday, tuesday, wednesday, thursday, friday, saturday};


enum week day;

The following example demonstrate the use of enum in the program

#include<stdio.h>
enum week{Mon=10, Tue, Wed, Thur, Fri=10, Sat=16, Sun};
enum day{Mond, Tues, Wedn, Thurs, Frid=18, Satu=11, Sund};
int main()
{
printf("The value of enum week: %d\t%d\t%d\t%d\t%d\t%d\t%d\n\n",Mon , Tue, Wed, Thur, Fri, Sat, Sun);

138
printf("The default value of enum day: %d\t%d\t%d\t%d\t%d\t%d\t%d",Mond , Tues, Wedn, Thurs, Frid, Satu,
Sund);
return 0;
}

When the above code is compiled and executed, it produces the following result –

The value of enum week: 10111213101617


The default value of enum day: 0123181112
In the above program, two enums are declared as week and day outside the main() function. In the main()
function, the values of enum elements are printed.

UNIT V
INTRODUCTION TO FILES:
In real world application when data is large then it is necessary to stored on the disk in
files. A file represents a sequence of bytes. file is created in secondary storage. Files are of two
types text file and binary file.
C language provides access on files with high/low level functions .FILE is a structure
defined in standard input/output library.
The file pointer is created and used as FILE *fp; where fp is a file pointer
Types of files
1. Text File :
A text stream consist of a sequence of characters. they are grouped in line. stores the
data in the text form
2. Binary File :
It stores the data in the binary form (1's and 0's). A binary stream consists of a
sequence of data. They are stored in their memory representation.

Operations on Files
C language support a number of functions to perform basic operation on file
• creating a file
• opening a file
• writing into the file
• reading from the file
• close the file
files I/O functions to manipulate data in file :
fopen() : create a file or open an existing file
fclose() : close a file
getc() : read a character
putc() : write a character
fprintf() : write a formatted values
fscanf() : read set of values
getw() : read an integer
putw() :write an integer

139
How to open a file?
fopen() function is used to open a file . This function creates a new file if the file does
not exist. .
Syntax: fopen(filename,mode)
Here, the first argument is file name and second argument is access mode.
The following are the different access modes in C,
r : read mode
w : writing mode
a : append mode
r+ : First reading then writing
w+: reading and writing and content is truncated
a+ : reading and writing and content is not truncated

Example: Demonstrate the opening of a file


#include<stdio.h>
int main()
{
FILE *fp; //creating a file pointer
fp=fopen("abc.txt","r"); // open a file
return 0;
}

How to close a file?


fclose()is used for closing the file. The fclose() function returns zero on success, or
EOF if there is an error in closing the file.
Syntax: fclose(filepointer)

Example:
#include<stdio.h>
int main()
{
FILE *fp; //creating a file pointer
fp=fopen("abc.txt","r"); // open a file
fclose(fp); // at the end close the file
return 0;
}

Summary exercise:
1. File pointer is created using FILE structure which is defined in stdio.h header file.
2. There 2 types of files: Text file, binary file
3. files can be opened in different modes to manipulate data using fopen() function.

Key topics / themes of the lecture : Reading data from files


We can read both text files as well as binary files.
Reading data from text file:
140
The following 3 functions are used for reading data from a Text File.
1. fgetc():
The fgetc() function reads a character from the input file referenced by file pointer. The
return value is the character read, or in case of any error, it returns EOF.
Syntax: int fgetc( FILE * fp );

Example: Write a program to read data from file using fgetc() method
#include <stdio.h>
int main () {
FILE *fp;
int c;
fp = fopen("myfile.txt","r");
do {
c = fgetc(fp);
if( c==EOF ) {
break ;
}
printf("%c", c);
} while(1);

fclose(fp);
return(0);
}
2. fgets():
It reads a string from a stream.

Syntax: char *fgets( char *buf, int n, FILE *fp );


The functions fgets() reads up to n-1 characters from the input stream referenced
by file pointer fp. It copies the read string into the buffer buf, appending a null character
to terminate the string.
If this function encounters a newline character '\n' or the end of the file EOF before
they have read the maximum number of characters, then it returns only the characters read
up to that point including the new line character.
Example: Write a program to read data from file using fgets() method
#include <stdio.h>
void main() {
FILE *fp;
char output[255];
fp = fopen(“myfile.txt”, “r”);
fgets(buff, 255, fp);
printf(" %s\n", output );
fclose(fp);

3. fscanf()
This function is to read strings from a file, but it stops reading after encountering the
first space character.
141
Syntax: int fscanf(FILE *fp, const char *format, [ argument, ...])

Example: Write a program to read data from file using fscanf() method
#include <stdio.h>
void main() {

FILE *fp;
char name[255];
int rollnum;
fp = fopen(“myfile.txt”, “r”);
fscanf(fp, "%s", name);
fscanf(fp, "%d", rollnum);

printf(" Name: %s\nRoll No.:%d", name, rollnum );


fclose(fp);

}
Reading data from binary file:
The following function is used for reading data from a Binary File.
1. fread()
Reads data from the given stream into the array .
Syntax: size_t fread(void *ptr, size_t sizeOfElements, size_t numberOfElements,
FILE *fp);
Here,
ptr − the pointer to a block of memory with a minimum size of sizeOfElements *
numberOfElements bytes.
sizeOfElements − the size in bytes of each element to be read.
numberOfElements − the number of elements, each one with a size of size bytes.
fp − the pointer to a FILE object that specifies an input stream.

Example: Write a program to read data from file using fread() method
#include <stdio.h>
int main () {
FILE *fp;
char output[100];
/* Open file for reading */
fp = fopen("myfile.txt", "r");

/* Read and display data */


fread(output, 1, 100, fp);
printf("%s\n", output);
fclose(fp);
return 0;
}

Key topics / themes of the lecture : Writing data to files, error handing during file
operations
142
WRITING DATA TO FILES
We can write data to both text files as well as binary files.
Writing data to a text file:
The following 3 functions are used for writing data to a Text File.
1. fputc():
The fputc() function writes the character value of the argument c to the output stream
referenced by file pointer. It returns the written character written on success otherwise
EOF if there is an error.
Syntax: int fputc(int c, FILE * fp );
Example: Write a program to write data to a file using fputc() method
#include <stdio.h>

int main () {
FILE *fp;
int ch;

fp = fopen("myfile.txt", "w");
for( ch = 65 ; ch <= 92; ch++ ) {
fputc(ch, fp);
}
fclose(fp);

return 0 ;
}

2. fputs():
It writes the string to the output stream referenced by file pointer.
Syntax: char *fgets( char *str, FILE *fp );

Example: Write a program to write data to a file using fputs() method

#include <stdio.h>

main() {
FILE *fp;

fp = fopen(“myfilet.txt", "w");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
}

3. fprintf()
It sends formatted output to a stream..
Syntax: int fprintf(FILE *fp, const char *format, [ argument, ...])

Example: Demonstrate a program to write data to a file using fprintf() method

143
#include <stdio.h>
#include <stdlib.h>
int main () {
FILE * fp;
fp = fopen ("file.txt", "w");
fprintf(fp, "%s %d", "CSE dept code is", 733);
fclose(fp);
return 0;
}
writing data to binary file:
The following function is used for writing data to a Binary File.
1. fwrite()
It writes data from the array pointed to by ptr to the given stream.
Syntax: size_t fread(void *ptr, size_t sizeOfElements, size_t numberOfElements,
FILE *fp);
Here,
ptr − the pointer to a block of memory with a minimum size of sizeOfElements *
numberOfElements bytes.
sizeOfElements − the size in bytes of each element to be read.
numberOfElements − the number of elements, each one with a size of size bytes.
fp − the pointer to a FILE object that specifies an input stream.

Example: Demonstrate a program to write data to a file using fwrite() method

#include<stdio.h>
int main () {
FILE *fp;
char str[] = "CSE department code is 733";
fp = fopen( "file.txt" , "w" );
fwrite(str , 1 , sizeof(str) , fp );
fclose(fp);
return 0;
}

RANDOM FILE ACCESS


We can take the file pointer to any part of the file for reading or writing. This can be done
using the following functions:
1. fseek():
It sets the file position of the stream to the given offset.
Syntax: int fseek(FILE *fp, long int offset, int whence)
Where, fp - the pointer to a FILE object that identifies the stream.
offset − number of bytes to offset from whence.
whence − the position from where offset is added.
• It is specified by one of the following constants:
SEEK_SET - represents Beginning of file
SEEK_CUR - represents Current position of the file pointer
SEEK_END - represents End of file
2. ftell():
It returns the current file position of the given stream.
Syntax: long int ftell(FILE *filepointer)
144
3. rewind():
It sets the file position to the beginning of the file of the given stream.
Syntax: void rewind(FILE *stream)

Example: Demonstrate a program to access data from a file using random access file operations.
#include <stdio.h>
int main () {
FILE *fp;
int len;
fp = fopen("file.txt", "r");
fseek(fp, 0, SEEK_END);
len = ftell(fp);
fclose(fp);
printf("Total size of file.txt = %d bytes\n", len);
return 0;
}

ERROR HANDING DURING FILE OPERATIONS


The following file status functions are used for handling errors during file operation:
1. feof() : it is used to check if end of the file has been reached
syntax: int feof(FILE *fp);
2. ferror(): it is used to check the error status of the file. it returns true if it finds error,
otherwise false.
syntax: int ferror(FILE *fp);
3. clearerr(): this function is used to change the status of the file from error state
syntax: void clearerr(FILE *fp);

PRE PROCESSOR DIRECTIVES

The C preprocessor is a macro processor that is used automatically by the C compiler to


transform programmer defined programs before actual compilation takes place. It is called a
macro processor because it allows the user to define macros, which are short abbreviations for
longer constructs. So, it can be also be referred to as pre compiled fragments of code. Some
possible actions are the inclusions of other files in the file being compiled, definitions of
symbolic constants and macros and
conditional compilation of program code and conditional execution of preprocessor directives.
List of Preprocessor directives which starts with #: #include, #define, #undef, #ifdef, #ifndef,
#if, #else, #elif, #endif, #error, #pragma

# include preprocessor directive:


Only defined at the top of the program definition and only white space and comments may
appear before preprocessor directive line. This directive includes a copy of the specified file or
library. And is written like so

# include <filename>
or

145
#include “file name”,

If included inside <> then the compiler looks for the file in an implementation defined
manner (or system directory paths). If included inside a quote “ ” statement then it searches for
the file in the same directory as the program being written.

So if we include a file named file1 while writing a program name code.c which is being
stored in a folder called test. Then inclusion like so -- #include “file1” will tell the compiler to
look for the file inside the test folder, It looks at neighboring folders or subfolders too but it starts
its search in the test folder.(This sub search option is compiler dependent).

A macro is a segment of code which is replaced by the value of macro. Macro is defined by
#define directive. There are two types of macros: Object-like Macros, Function-like Macros

Object-like Macros (Symbolic constants)

The object-like macro is an identifier that is replaced by value. It is widely used to


represent numeric constants. Used to create symbolic constants and macros, meaning useful for
renaming long named data types and certain constants or values which is being used throughout
the program definition.

#define identifier replacement-text

When this line appears in a file, all subsequent occurrences of identifier that do not
appear in string literals will be replaced by the replacement text automatically before program
compilation takes place.

For example: #define PI 3.14159

Replaces all subsequent occurrences of the symbolic constant PI with numeric constant
3.14159. Symbolic constants enable the programmer to create a name for a constant and use that
name throughout program execution. If this needs to be modified ,it has to be done in the #define
directive statement. After recompilation all definitions get modified accordingly.

Function-like Macros

The function-like macro looks like function call. For example:

#define MIN(a,b) ((a)<(b)?(a):(b))

Here, MIN is the macro name.xample for Function-like Macros :


#include <stdio.h>
#define MIN(a,b)
((a)<(b)?(a):(b)) void main() {
printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));
}

146
Output:
Minimum between 10 and 20 is: 10

Differences between MACRO and FUNCTION:

Macro Function
Macro is Preprocessed Function is Compiled
No Type Checking Type Checking is Done
Code Length Increases Code Length remains Same
Speed of Execution is Speed of Execution is Slower
Faster
Before Compilation macro name is replaced by During function call , Transfer of
macro value Control takes place
Useful where small code appears many time Useful where large code appears many time

Generally Macros do not extend beyond one line Function can be of any number of lines

Macro does not Check Compile Errors Function Checks Compile Errors

Preprocessor Formatting
A preprocessing directive cannot be more than one line in normal circumstances. It may be split
cosmetically with Backslash-Newline. Comments containing Newlines can also divide the
directive into multiple lines.
for example, you can split a line cosmetically with Backslash-Newline anywhere:
/*
*/ # /*
*/
defi\
ne
FO\ O
10\ 20
is equivalent into #define FOO 1020.
#undef
To undefine a macro means to cancel its definition. This is done with the #undef directive.
Syntax:
#undef token
define and undefine example
#include
<stdio.h>
#define PI
3.1415 #undef PI

147
main() {
printf("%f",PI);
}
Output:
Compile Time Error: 'PI' undeclared

#ifdef
The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the
code.
Syntax:
#ifdef MACRO
//code
#endif

#ifndef
The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the
code.
Syntax:
#ifndef MACRO

//code

#endif
#if

The #if preprocessor directive evaluates the expression or condition. If condition is true, it
executes the code.
Syntax:
#if expression
//code
#endif

#else
The #else preprocessor directive evaluates the expression or condition if condition of #if is false.
It can be used with #if, #elif, #ifdef and #ifndef directives.
Syntax:

148
Syntax with #elif

#if expression

//if code
#else
//else code
#endif

#if expression
//if code
#elif expression
//elif
code
#else
//else code
#endif

Example Code
#include <stdio.h> #include
<conio.h> #define
NUMBER 1 void main() {
#if NUMBER==0
printf("Value of Number is: %d",NUMBER);
#else
print("Value of Number is non-zero");
#endif
getch();
}

O/P:
Value of Number is non-zero

Example Code:

#include<stdio.h> -- Include external source code file


#include “file1” - Include a file which is in the same folder as the
parent file #define BUFFER_SIZE 250
int maint(){

char array[BUFFER_SIZE] =
[0]; int I = 9;

printf(“%d”,i);

149
printf(“%s”,array
); return 0;

}//end main body

Conditional Compilation:

Conditional compilation enables the coder to control the execution of preprocessor


directives and the compilation of program code. Conditional preprocessor directives evaluate
constant integer expressions. The ones that cannot be evaluated in preprocessor directives are
sizeof expressions and enumeration constants.
Every #if construct ends with #endif

Example
– #if
!defined(MY_CONSTANT)
#define MY_CONSTANT 0
#endif

150
These directives determine if MY_CONSTANT is defined or not. The expression defined
(MY_CONSTANT) evaluates to 1 if MY_CONSTANT is not defined and is defined else it
evaluates to 0.

Example: conditional compilation

#include <stdio.h>

#define MEMBER

int main()

float amount,total;

printf("enter amount\n");

scanf("%f",&amount);

#ifdef MEMBER

total= amount*0.8;

printf("Amount to be paid=%f",total);

#else

printf("Amount to be paid=%f",amount);

#endif

151
Summary exercise:

Following table will show you various directives that we have studied in this chapter:

Directives Description

#define It substitutes a preprocessor macro.

#include It inserts a particular header file from another file.

#undef A preprocessor macro is undefined.

#ifdef It returns true if the macro is defined.

#ifndef It returns true if the macro is not defined.

#if It tests if the compile time condition is true.

#else It is an alternative for #if.

#elif It has #else and #if in one statement.

#endif The conditional preprocessor is ended.

#error It prints the error message on stderr.

#pragma It issues special commands to the compiler by using a standardized method.

152

You might also like