You are on page 1of 165

E.G.

SPILLAY ENGINEERING
COLLEGE
(AUTONOMOUS)
DEPARTMENT OF CSE

1701GEX03-PROGRAMMING IN C
Reviewed by Prepared by

Dr.T.Ganesan ASP/CSE
Mr.J.Noorul Ameen Ap/CSE S.Aravindan ap/cse
Mr.R.Manivannan ap/cse
E.G.S PILLAY ENGINEERING COLLEGE
DEPARTMENT OF CSE
PROGRAMMING USING C
OBJECTIVES
Prepare students to comprehend the fundamental concepts in Computer Science and
Engineering
To demonstrate fine grained operations in number system
To gain exposure in programming language using C
To develop programming skills using the fundamentals and basics of C Language.

PROGRAMMING USING C
UNIT 1 -BASIC CONCEPTS 8
Organization and Classifications of Computer- Generations of Computers- Number System-
Problem Solving Techniques Development of Algorithm - Flowchart
UNIT 2-INTRODUCTION TO C LANGUAGE 10
Overview of C - Constants, Variables and Data Types- Compilation and Linking - Operators and
Expressions- Decision Making and Branching Looping statements
UNIT 3-ARRAYS AND STRINGS 9
Arrays-One Dimensional Array- Declaration and Initialization-Two Dimensional Array-
Declaration and Initialization- Programs using Arrays- Strings- String Handling Functions,
Programs using Strings- Managing I/O Operations
UNIT-4 FUNCTIONS & STRUCTURES 10
Functions-Function Prototypes-Declaring, Defining and Calling Functions-Call by value and
Call by Reference-Recursive Functions-Structures- Declaration and Definition -Accessing
Structure Members-Arrays of Structures-Unions- Programs using Structures and Unions
UNIT - 5- POINTERS & FILES 8
Pointers-Dynamic Memory Allocation-Arithmetic Operations using Pointers, Files File
Manipulation-I/O Operations, Preprocessor Directives, Storage Classes

TOTAL: 45 PERIODS

REFERENCES:
1. E. Balagurusamy- Programming in ANSI C-McGraw Hill Education India Private Limited;
Seventh edition (1 Jul 2017).
2. Pradip Dey, Manas Ghosh, Computer Fundamentals and Programming in C, Second
Edition, Oxford University Press, 2013.
3. Ashok N. Kamthane, Programming in C Pearson Education India; 3 edition (2015).
4. Yashavant P. Kanetkar. Let Us C, BPB Publications; 15th Revised and Updated edition (13
July 2016)

OUTCOME
To describe basic concepts of computers
To paraphrase the operations of number system
To describe about basic concepts of C-Language
To understand the code reusability with the help of user defined functions
To analyze the basics of structures, unions, file management and preprocessor in C
language
UNIT 1 -BASIC CONCEPTS

UNIT 1 -BASIC CONCEPTS 8


Organization and Classifications of Computer- Generations of Computers-
Number System- Problem Solving Techniques Development of Algorithm -
Flowchart

What is computer?

Computer is an electronic device that is designed to work with


Information. The term computer is derived from the Latin term computare,
this means to calculate or programmable machine.

Characteristics of computer

Speed

The computer process the data extremely fast. (i.e.) in millions (1,000,000)
of instructions and even more per second. A computer can perform a huge
task in few sec where a human being may take hours or even days to
complete the same task.

Accuracy

The degree of accuracy of computer is very high and every


calculation is performed with the same accuracy. The accuracy level is
determined on the basis of design of computer. The errors in computer are
due to human and inaccurate data.

Diligence

A computer is free from tiredness, lack of concentration etc. It


can work for hours without creating any error. If millions of calculations are
to be performed, a computer will perform every calculation with the same
accuracy. Due to this capability it overpowers human being in routine type of
work.

Versatility

It means the capacity to perform completely different type of


work. For example At a moment a computer can be used to draft a letter.
Next moment it can be used print a document or play a music file etc.,
Page 1
UNIT 1 -BASIC CONCEPTS
Reliability

It produces results without any error. Only human made errors can occur

So they are trustworthy machines.

Storage

Computers are capable of storing huge amount of data and it can be located
and retrieved very quickly. It uses storage devices such as hard disk to store
huge amount of data.

Hardware

The physical components that make up a computer system. Eg Mouse

Software

The programs (instructions) that tell the computer what to do.

There are two main types of software: systems software and application
software. Systems software includes the programs that are dedicated to
managing the computer itself, such as the operating system, file
management utilities, and disk. Application Software Performs specific tasks
like Word processing, Calculations Information storage and retrieval and
Accounting

Parts of computer

Page 2
UNIT 1 -BASIC CONCEPTS
Mouse

A computer mouse is a pointing device (hand control) that detects two-


dimensional motion relative to a surface. This motion is typically translated
into the motion of a pointer on a display, which allows a smooth control of
the graphical user interface.

Keyboard

A computer keyboard is one of the primary input devices used with a


computer that looks similar to those found on electric typewriters, but with
some additional keys. Keyboards allow you to input letters, numbers, and
other symbols into a computer that can serve as commands or be used to
type text.

Monitor

A computer monitor is an output device which displays the information in


pictorial form. A monitor usually comprises the display device, circuitry,
casing, and power supply.

Central processing unit

The central processing unit (CPU) is the computer component that's


responsible for interpreting and executing most of the commands from the
computer's other hardware and software.

All sorts of devices use a CPU, including desktop, laptop, and tablet
computers, smartphones...even your flat-screen television set.

Speakers

Computer speakers, or multimedia speakers, are speakers sold for use with
computers, although usually capable of other audio uses, e.g. for an MP3
player. Most such speakers have an internal amplifier and consequently
require a power source, which may be by a mains power supply often via an
AC adapter, batteries, or a USB port

Printer

A printer is a device that accepts text and graphic output from a computer
and transfers the information to paper, usually to standard size sheets of
paper. Printers vary in size, speed, sophistication, and cost

Page 3
UNIT 1 -BASIC CONCEPTS
ORGANISTATION OF COMPUTER

The memory unit that holds both data and instructions.


The arithmetic/logic gate unit that is capable of performing arithmetic
and logic operations on data.
The input unit that moves data from the outside world into the
computer.
The output unit that moves results from inside the computer to the
outside world.
The control unit that acts as the stage unit to ensure that all the other
components act in concert.

Memory

Computer memory is any physical device capable of storing information


temporarily or permanently. For example, Random Access Memory (RAM), is
a volatile memory that stores information on an integrated circuit used by
the operating system, software, and hardware.

Types of memory

Volatile
Non volatile memory
Page 4
UNIT 1 -BASIC CONCEPTS
Volatile vs. non-volatile memory

Memory can be either volatile and non-volatile memory. Volatile memory is a


memory that loses its contents when the computer or hardware device loses
power. Computer RAM is an example of a volatile memory and is why if your
computer freezes or reboots when working on a program, you lose anything
that hasn't been saved. Non-volatile memory, sometimes abbreviated as
NVRAM, is a memory that keeps its contents even if the power is
lost. EPROM is an example of a non-volatile memory.

Control unit

A control unit (CU) handles all processor control signals. It directs all input
and output flow, fetches code for instructions from microprograms and
directs other units and models by providing control and timing signals. A CU
component is considered the processor brain because it issues orders to just
about everything and ensures correct instruction execution.

Arithmetic logic unit

An arithmetic logic unit (ALU) is a major component of the central


processing unit of a computer system. It does all processes related to
arithmetic and logic operations that need to be done on instruction words. In
some microprocessor architectures, the ALU is divided into the arithmetic
unit (AU) and the logic unit (LU).

An ALU can be designed by engineers to calculate any operation. As the


operations become more complex, the ALU also becomes more expensive,
takes up more space in the CPU and dissipates more heat. That is why
engineers make the ALU powerful enough to ensure that the CPU is also
powerful and fast, but not so complex as to become prohibitive in terms of
cost and other disadvantages.

An arithmetic logic unit is also known as an integer unit (IU)

Page 5
UNIT 1 -BASIC CONCEPTS

Classification of computers

Based on the operating principles, computers can be classified into one of


the following types: -
Digital Computers
Analog Computers
Hybrid Computers

Digital Computers: - Operate essentially by counting. All quantities are


expressed as discrete or numbers. Digital computers are useful for
evaluating arithmetic expressions and manipulations of data (such as
preparation of bills, ledgers, solution of simultaneous equations etc)

Analog Computers:- An analog computer is a form of computer that uses


the continuously changeable aspects of physical phenomena such
as electrical, mechanical, or hydraulic quantities to model the problem being
solved. In contrast, digital computers represent varying quantities
symbolically, as their numerical values change.

Hybrid Computers:- are computers that exhibit features of analog


computers and digital computers. The digital component normally serves as
the controller and provides logical operations, while the analog component
normally serves as a solver of differential equations.

CLASSIFICATION BASED ON AREA OF APPLICATION

Classification based on area of applications

Modern computers depending upon their applications are classified as: -

Special Purpose Computers


General Purpose Computers

Page 6
UNIT 1 -BASIC CONCEPTS

Special Purpose Computers: - A special purpose computer is designed


only to meet the requirements of a particular task or application. The
instructions needed to perform a particular task are permanently stored into
the internal memory, so that it can perform the given task on a single
command. It therefore doesnt posses unnecessary options and is less
expensive.

General Purpose Computers: - A General Purpose computers are


designed to meet the needs of many different applications. In these
computers, the instructions needed to perform a particular task are wired
permanently into the internal memory. When one job is over, instructions for
another job can be loaded into the internal memory for processing. This, a
general purpose machine can be used to prepare pay-bills, manage
inventories, print sales report and so on.

CLASSIFICATION BASED ON SIZE AND CAPABILITY

Based on size and capability, computers are broadly classified into

Microcomputers(Personal Computer)

A microcomputer is the smallest general purpose processing system. The


older pc started 8 bit processor with speed of 3.7MB and current pc 64 bit
processor with speed of 4.66 GB.

Examples: - IBM PCs, APPLE computers

Microcomputer can be classified into 2 types :

1.Desktops

2.Portables

The difference is portables can be used while travelling whereas desktops


computers cannot be carried around.

The different portable computers are: -

Laptop
Notebooks

Page 7
UNIT 1 -BASIC CONCEPTS
Palmtop (hand held)
Wearable computers

Laptop: - this computer is similar to a desktop computers but the size is


smaller. They are expensive than desktop. The weight of laptop is around 3
to 5 kg.

Notebook: - These computers are as powerful as desktop but size of these


computers are comparatively smaller than laptop and desktop. They weigh 2
to 3 kg. They are more costly than laptop.

Palmtop (Hand held): - They are also called as personal Digital Assistant
(PDA). These computers are small in size. They can be held in hands. It is
capable of doing word processing, spreadsheets and hand writing
recognition, game playing, faxing and paging. These computers are not as
powerful as desktop computers

Wearable computer: - The size of this computer is very small so that it can
be worn on the body. It has smaller processing power. It is used in the field
of medicine. For example pace maker to correct the heart beats. Insulin
meter to find the levels of insulin in the blood.

Minicomputer: - A minicomputer is a medium-sized computer. That is more


powerful than a microcomputer. These computers are usually designed to
serve multiple users simultaneously (Parallel Processing). They are more
expensive than microcomputers.

Mainframe computers: - Computers with large storage capacities and very


high speed of processing (compared to mini- or microcomputers) are known
as mainframe computers. They support a large number of terminals for
simultaneous use by a number of users like ATM transactions. They are also
used as central host computers in distributed data processing system.

Examples: - IBM 370, S/390.

Supercomputer: -Supercomputers have extremely large storage capacity


and computing speeds which are many times faster than other computers. A
supercomputer is measured in terms of tens of millions Instructions per
second (mips), an operation is made up of numerous instructions. The

Page 8
UNIT 1 -BASIC CONCEPTS
supercomputer is mainly used for large scale numerical problems in scientific
and engineering disciplines such as Weather analysis.

Examples: - IBM Deep Blue

GENERATIONS OF COMPUTERS

First Generation Computers(1940-1956):

These computers were vacuum tube based machines.

They used magnetic drums for memory.

Input were fed into the computer using Punched cards

The size of these computers were very large and it produce more heat.

They lacked in versatility and speed.

They were more expensive.

Speed: Fastest computing device of its time

Technology: Vacuum Tubes :

Made up of glass contains filaments, when heated generates


electrons which helps in amplification and de amplification of
signals

I/p & O/p : Punched card and print out

Programming language: Machine level language

Example:

EDSAC: Electronic delay storage automatic calculator

EDVAC: Electronic discrete variable automatic computer

Advantages:

Fastest computing device of their time

Execute complex mathematical problems in an efficient manner

Page 9
UNIT 1 -BASIC CONCEPTS
Disadvantages:

Large & Bulky

Difficult to program

Cannot be transferred from one place to another

These are special purpose computers

Generates huge amount of heat and hence prone to hardware


faults

Second Generation Computers (1956-1963)

Here the Transistor replaced the bulky vacuum tubes.

Transistors are smaller than vacuum tubes and have higher operating
speed.

Thus the size of the computer got reduced considerably.

Manufacturing cost was also very low

Speed: Faster than first generation

Technology: Transistor :

Used to increase the power of incoming signals.

It has 3 connections:

Base : Through which incoming signals are sent

Collector : Collects amplified signal

Emitter : Emits amplified signal

I/p & O/p : Punched card and print out

Programming language: Assembly language

Example:

IBM 1401

IBM 1620

Page 10
UNIT 1 -BASIC CONCEPTS
Advantages:

Fastest computing device of their time

Easy to program

Light weight

Low power consumption

Low maintenance

Transferred from one place to another easily

Disadvantages:

High cost

Limited to special purpose tasks

Generates considerable amount of heat

Third Generation Computers (1964-1975)

These computers were based on Integrated Circuits (ICs)


Technology.

A single IC has many transistors, registers and capacitors built on a


single thin slice of silicon.

So that the size of the computer got further reduced.

These Computers were small in size, low cost, large memory and
processing speed is very high.

Speed: Fastest computing device of its time

Technology: Integrated Circuits : Also known as micro electronics


technology

Programming language: High level language

Example:

IBM 360

Honeywell 6000
Page 11
UNIT 1 -BASIC CONCEPTS
Advantages:

Computational time was measured in nano seconds

Requires low power to operate

Small size

Installation is very easy

Able to execute any type of applications

More reliable & requires less maintenance

Easily transportable

Disadvantages:

Storage capacity was very small

Performance will get degrade while executing large applications

Cost is very high

Required to be placed in air conditioned plates

Fourth Generation Computers(1975-1989)

It uses very large scale Integrated Circuits (VLSI) built on a single


silicon chip called microprocessors .

These computers are called microcomputers.

Thus the size of the computer got reduced.

The personal computer (PC) are comes under the Fourth Generation.

Speed: Fastest computing device of its time

Technology: VLSI : Very large scale Integration

It leads to the development of GUI, Operating Systems, Various


storage devices, I/O devices and LAN

It has 3 components:

Microprocessors

Page 12
UNIT 1 -BASIC CONCEPTS
Memory

I/O Controls

Programming language: High level language

Example:

IBM PC series

Apple Series

Advantages:

Very powerful in terms of speed & time

Storage capacity is very high & it is very fast

Highly reliable and requires low maintenance

Provides user friendly environment using GUI(Graphical user


interface)

Programs are highly portable

Highly versatile and requires less power

Disadvantages:

The soldering of VLSI chips on the wiring board was not an easy
task

Working of these computers depends on instructions given by


the programmer

Fifth Generation Computer(1989-Till date)

The speed is extremely high in fifth generation computer.

The concept of Artificial intelligence has been introduced to allow the


computer to take its own decision.

It is still in a developmental stage .

Speed: Faster of all times


Page 13
UNIT 1 -BASIC CONCEPTS
Technology: ULSI : Ultra large scale Integration

It has more than10 million electronic components

It increases the power & speed of the microprocessor

Programming language:

High level language

Integrated development environment

Example:

Laptop ,PDA

Advantages:

Fastest & powerful computers till date

Able to execute a large no of application at very high speed.

ULSI Technology helps in decreasing the size of computers.

Multimedia features are available

Resource sharing is possible & is highly versatile

Disadvantages:

Lack of human like Intelligence

Page 14
UNIT 1 -BASIC CONCEPTS
NUMBER SYSTEM

When we type some letters or words, the computer translates them in


numbers as computers can understand only numbers. A computer can
understand the positional number system where there are only a few
symbols called digits and these symbols represent different values
depending on the position they occupy in the number.

The value of each digit in a number can be determined using

The digit

The position of the digit in the number

The base of the number system (where the base is defined as the total
number of digits available in the number system)

Decimal Number System

The number system that we use in our day-to-day life is the decimal number
system. Decimal number system has base 10 as it uses 10 digits from 0 to
9. In decimal number system, the successive positions to the left of the
decimal point represent units, tens, hundreds, thousands, and so on.

Each position represents a specific power of the base (10). For example, the
decimal number 1234 consists of the digit 4 in the units position, 3 in the
tens position, 2 in the hundreds position, and 1 in the thousands position. Its
value can be written as

(1 x 1000)+ (2 x 100)+ (3 x 10)+ (4 x l)

(1 x 103)+ (2 x 102)+ (3 x 101)+ (4 x l00)

1000 + 200 + 30 + 4

1234

Page 15
UNIT 1 -BASIC CONCEPTS

S.No. Number System and Description

Binary Number System


1
Base 2. Digits used : 0, 1

Octal Number System


2
Base 8. Digits used : 0 to 7

Hexa Decimal Number System


3
Base 16. Digits used: 0 to 9, Letters used : A- F

Binary Number System

Characteristics of the binary number system are as follows

Uses two digits, 0 and 1

Also called as base 2 number system

Each position in a binary number represents a 0 power of the base (2).


Example 20

Last position in a binary number represents a x power of the base (2).


Example 2x where x represents the last position - 1.

Example

Binary Number: 101012

Calculating Decimal Equivalent

Page 16
UNIT 1 -BASIC CONCEPTS

Step Binary Decimal Number


Number

Step 101012 ((1 x 24) + (0 x 23) + (1 x 22) + (0 x 21) +


1 (1 x 20))10

Step 101012 (16 + 0 + 4 + 0 + 1)10


2

Step 101012 2110


3

Note 101012 is normally written as 10101.

Octal Number System

Characteristics of the octal number system are as follows

Uses eight digits, 0,1,2,3,4,5,6,7

Also called as base 8 number system

Each position in an octal number represents a 0 power of the base (8).


Example 80

Last position in an octal number represents a x power of the base (8).


Example 8x where x represents the last position - 1

Example
Octal Number: 125708

Page 17
UNIT 1 -BASIC CONCEPTS

Calculating Decimal Equivalent

Step Octal Decimal Number


Number

Step 125708 ((1 x 84) + (2 x 83) + (5 x 82) + (7 x 81) +


1 (0 x 80))10

Step 125708 (4096 + 1024 + 320 + 56 + 0)10


2

Step 125708 549610


3

Note 125708 is normally written as 12570.

Hexadecimal Number System


Characteristics of hexadecimal number system are as follows

Uses 10 digits and 6 letters, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F

Letters represent the numbers starting from 10. A = 10. B = 11, C = 12, D
= 13, E = 14, F = 15

Also called as base 16 number system

Each position in a hexadecimal number represents a 0 power of the base


(16). Example, 160

Last position in a hexadecimal number represents a x power of the base


(16). Example 16x where x represents the last position - 1

Example
Hexadecimal Number: 19FDE16

Calculating Decimal Equivalent

Page 18
UNIT 1 -BASIC CONCEPTS

Step Binary Decimal Number


Number

Step 19FDE16 ((1 x 164) + (9 x 163) + (F x 162) + (D x 161) +


1 (E x 160))10

Step ((1 x 164) + (9 x 163) + (15 x 162) + (13 x 161)


19FDE16
2 + (14 x 160))10

Step 19FDE16 (65536+ 36864 + 3840 + 208 + 14)10


3

Step 19FDE16 10646210


4

Note 19FDE16 is normally written as 19FDE.

here are many methods or techniques which can be used to convert


numbers from one base to another. In this chapter, we'll demonstrate the
following

Decimal to Other Base System

Other Base System to Decimal

Other Base System to Non-Decimal

Shortcut method - Binary to Octal

Shortcut method - Octal to Binary

Shortcut method - Binary to Hexadecimal

Shortcut method - Hexadecimal to Binary

Decimal to Other Base System


Step 1 Divide the decimal number to be converted by the value of the
new base.

Step 2 Get the remainder from Step 1 as the rightmost digit (least
significant digit) of the new base number.

Page 19
UNIT 1 -BASIC CONCEPTS

Step 3 Divide the quotient of the previous divide by the new base.

Step 4 Record the remainder from Step 3 as the next digit (to the left) of
the new base number.

Repeat Steps 3 and 4, getting remainders from right to left, until the
quotient becomes zero in Step 3.

The last remainder thus obtained will be the Most Significant Digit (MSD) of
the new base number.

Example
Decimal Number: 2910

Calculating Binary Equivalent

Step Operation Result Remainder

Step 1 29 / 2 14 1

Step 2 14 / 2 7 0

Step 3 7/2 3 1

Step 4 3/2 1 1

Step 5 1/2 0 1

As mentioned in Steps 2 and 4, the remainders have to be arranged in the


reverse order so that the first remainder becomes the Least Significant Digit
(LSD) and the last remainder becomes the Most Significant Digit (MSD).

Decimal Number : 2910 = Binary Number : 111012.

Page 20
UNIT 1 -BASIC CONCEPTS

Other Base System to Decimal System


Step 1 Determine the column (positional) value of each digit (this
depends on the position of the digit and the base of the number system).

Step 2 Multiply the obtained column values (in Step 1) by the digits in
the corresponding columns.

Step 3 Sum the products calculated in Step 2. The total is the equivalent
value in decimal.

Example
Binary Number: 111012

Calculating Decimal Equivalent

Step Binary Number Decimal Number

Step 1 111012 ((1 x 24) + (1 x 23) + (1 x 22) + (0 x 21) + (1 x 20))10

Step 2 111012 (16 + 8 + 4 + 0 + 1)10

Step 3 111012 2910

Binary Number : 111012 = Decimal Number : 2910

Other Base System to Non-Decimal System


Step 1 Convert the original number to a decimal number (base 10).

Step 2 Convert the decimal number so obtained to the new base


number.

Example
Octal Number : 258

Calculating Binary Equivalent

Page 21
UNIT 1 -BASIC CONCEPTS

Step 1 - Convert to Decimal


Step Octal Number Decimal Number

Step 1 258 ((2 x 81) + (5 x 80))10

Step 2 258 (16 + 5)10

Step 3 258 2110

Octal Number : 258 = Decimal Number : 2110

Step 2 - Convert Decimal to Binary


Step Operation Result Remainder

Step 1 21 / 2 10 1

Step 2 10 / 2 5 0

Step 3 5/2 2 1

Step 4 2/2 1 0

Step 5 1/2 0 1

Decimal Number : 2110 = Binary Number : 101012

Octal Number : 258 = Binary Number : 101012

Shortcut Method Binary to Octal


Step 1 Divide the binary digits into groups of three (starting from the
right).

Step 2 Convert each group of three binary digits to one octal digit.

Page 22
UNIT 1 -BASIC CONCEPTS

Example
Binary Number : 101012

Calculating Octal Equivalent

Step Binary Number Octal Number

Step 1 101012 010 101

Step 2 101012 28 58

Step 3 101012 258

Binary Number : 101012 = Octal Number : 258

Shortcut Method Octal to Binary


Step 1 Convert each octal digit to a 3-digit binary number (the octal
digits may be treated as decimal for this conversion).

Step 2 Combine all the resulting binary groups (of 3 digits each) into a
single binary number.

Example
Octal Number : 258

Calculating Binary Equivalent

Step Octal Number Binary Number

Step 1 258 210 510

Step 2 258 0102 1012

Step 3 258 0101012

Octal Number : 258 = Binary Number : 101012

Page 23
UNIT 1 -BASIC CONCEPTS

Shortcut Method Binary to Hexadecimal


Step 1 Divide the binary digits into groups of four (starting from the
right).

Step 2 Convert each group of four binary digits to one hexadecimal


symbol.

Example
Binary Number : 101012

Calculating hexadecimal Equivalent

Step Binary Number Hexadecimal Number

Step 1 101012 0001 0101

Step 2 101012 110 510

Step 3 101012 1516

Binary Number : 101012 = Hexadecimal Number : 1516

Shortcut Method - Hexadecimal to Binary


Step 1 Convert each hexadecimal digit to a 4-digit binary number (the
hexadecimal digits may be treated as decimal for this conversion).

Step 2 Combine all the resulting binary groups (of 4 digits each) into a
single binary number.

Example
Hexadecimal Number : 1516

Page 24
UNIT 1 -BASIC CONCEPTS

Calculating Binary Equivalent

Step Hexadecimal Number Binary Number

Step 1 1516 110 510

Step 2 1516 00012 01012

Step 3 1516 000101012

Hexadecimal Number : 1516 = Binary Number : 101012

There are many methods or techniques which can be used to convert


numbers from one base to another. In this chapter, we'll demonstrate the
following

Decimal to Other Base System


Other Base System to Decimal
Other Base System to Non-Decimal
Shortcut method - Binary to Octal
Shortcut method - Octal to Binary
Shortcut method - Binary to Hexadecimal
Shortcut method - Hexadecimal to Binary
Decimal to Other Base System
Step 1 Divide the decimal number to be converted by the value of the
new base.

Step 2 Get the remainder from Step 1 as the rightmost digit (least
significant digit) of the new base number.

Step 3 Divide the quotient of the previous divide by the new base.

Step 4 Record the remainder from Step 3 as the next digit (to the left) of
the new base number.

Page 25
UNIT 1 -BASIC CONCEPTS

Repeat Steps 3 and 4, getting remainders from right to left, until the
quotient becomes zero in Step 3.

The last remainder thus obtained will be the Most Significant Digit (MSD) of
the new base number.

Example
Decimal Number: 2910

Calculating Binary Equivalent

Step Operation Result Remainder

Step 1 29 / 2 14 1

Step 2 14 / 2 7 0

Step 3 7/2 3 1

Step 4 3/2 1 1

Step 5 1/2 0 1

As mentioned in Steps 2 and 4, the remainders have to be arranged in the


reverse order so that the first remainder becomes the Least Significant Digit
(LSD) and the last remainder becomes the Most Significant Digit (MSD).

Decimal Number : 2910 = Binary Number : 111012.

Other Base System to Decimal System


Step 1 Determine the column (positional) value of each digit (this
depends on the position of the digit and the base of the number system).

Step 2 Multiply the obtained column values (in Step 1) by the digits in
the corresponding columns.

Page 26
UNIT 1 -BASIC CONCEPTS

Step 3 Sum the products calculated in Step 2. The total is the equivalent
value in decimal.

Example
Binary Number: 111012

Calculating Decimal Equivalent

Step Binary Number Decimal Number

Step 1 111012 ((1 x 24) + (1 x 23) + (1 x 22) + (0 x 21) + (1 x 20))10

Step 2 111012 (16 + 8 + 4 + 0 + 1)10

Step 3 111012 2910

Binary Number : 111012 = Decimal Number : 2910

Other Base System to Non-Decimal System


Step 1 Convert the original number to a decimal number (base 10).

Step 2 Convert the decimal number so obtained to the new base


number.

Example
Octal Number : 258

Calculating Binary Equivalent

Step 1 - Convert to Decimal


Step Octal Number Decimal Number

Step 1 258 ((2 x 81) + (5 x 80))10

Step 2 258 (16 + 5)10

Page 27
UNIT 1 -BASIC CONCEPTS

Step 3 258 2110

Octal Number : 258 = Decimal Number : 2110

Step 2 - Convert Decimal to Binary


Step Operation Result Remainder

Step 1 21 / 2 10 1

Step 2 10 / 2 5 0

Step 3 5/2 2 1

Step 4 2/2 1 0

Step 5 1/2 0 1

Decimal Number : 2110 = Binary Number : 101012

Octal Number : 258 = Binary Number : 101012

Shortcut Method Binary to Octal


Step 1 Divide the binary digits into groups of three (starting from the
right).

Step 2 Convert each group of three binary digits to one octal digit.

Example
Binary Number : 101012

Calculating Octal Equivalent

Step Binary Number Octal Number

Step 1 101012 010 101

Page 28
UNIT 1 -BASIC CONCEPTS

Step 2 101012 28 58

Step 3 101012 258

Binary Number : 101012 = Octal Number : 258

Shortcut Method Octal to Binary


Step 1 Convert each octal digit to a 3-digit binary number (the octal
digits may be treated as decimal for this conversion).

Step 2 Combine all the resulting binary groups (of 3 digits each) into a
single binary number.

Example
Octal Number : 258

Calculating Binary Equivalent

Step Octal Number Binary Number

Step 1 258 210 510

Step 2 258 0102 1012

Step 3 258 0101012

Octal Number : 258 = Binary Number : 101012

Shortcut Method Binary to Hexadecimal


Step 1 Divide the binary digits into groups of four (starting from the
right).

Step 2 Convert each group of four binary digits to one hexadecimal


symbol.

Example
Binary Number : 101012
Page 29
UNIT 1 -BASIC CONCEPTS

Calculating hexadecimal Equivalent

Step Binary Number Hexadecimal Number

Step 1 101012 0001 0101

Step 2 101012 110 510

Step 3 101012 1516

Binary Number : 101012 = Hexadecimal Number : 1516

Shortcut Method - Hexadecimal to Binary


Step 1 Convert each hexadecimal digit to a 4-digit binary number (the
hexadecimal digits may be treated as decimal for this conversion).

Step 2 Combine all the resulting binary groups (of 4 digits each) into a
single binary number.

Example
Hexadecimal Number : 1516

Calculating Binary Equivalent

Step Hexadecimal Number Binary Number

Step 1 1516 110 510

Step 2 1516 00012 01012

Step 3 1516 000101012

Hexadecimal Number : 1516 = Binary Number : 101012

Page 30
UNIT 1 -BASIC CONCEPTS

PROBLEM SOLVING TECHNIQUES

Introduction
Procedure (steps involved in problem solving)
Algorithm
Flow Chart
Symbols used in Flow Charts
Pseudo Code

Introduction

A computer is a very powerful and versatile machine capable of performing


a multitude of different tasks, yet it has no intelligence or thinking power.
The intelligence Quotient (I.Q) of a computer is zero. A computer performs
many tasks exactly in the same manner as it is told to do. This places
responsibility on the user to instruct the computer in a correct and precise
manner, so that the machine is able to perform the required job in a proper
way. A wrong or ambiguous instruction may sometimes prove disastrous.

In order to instruct a computer correctly, the user must have clear


understanding of the problem to be solved. A part from this he should be
able to develop a method, in the form of series of sequential steps, to solve
it. Once the problem is well-defined and a method of solving it is developed,
then instructing The computer to solve the problem becomes relatively
easier task. Thus, before attempt to write a computer program to solve a
given problem. It is necessary to formulate or define the problem in a
precise manner. Once the problem is defined, the steps required to solve it,
must be stated clearly in the required order.

Procedure (Steps Involved in Problem Solving)

A computer cannot solve a problem on its own. One has to provide step
by step solutions of the problem to the computer. In fact, the task of
problem solving is not that of the computer. It is the programmer who has
to write down the solution to the problem in terms of simple operations
which the computer can understand and execute.

In order to solve a problem by the computer, one has to pass though certain
stages or steps. They are
1. Understanding the problem
2. Analyzing the problem

Page 31
UNIT 1 -BASIC CONCEPTS
3. Developing the solution
4. Coding and implementation.

1. Understanding the problem: Here we try to understand the problem


to be solved in totally. Before with the next stage or step, we should be
absolutely sure about the objectives of the given problem.

2. Analyzing the problem: After understanding thoroughly the problem


to be solved, we look different ways of solving the problem and evaluate
each of these methods. The idea here is to search an appropriate solution to
the problem under consideration. The end result of this stage is a broad
overview of the sequence of operations that are to be carries out to solve
the given problem.
3. Developing the solution: Here the overview of the sequence of
operations that was the result of analysis stage is expanded to form a
detailed step by step solution to the problem under consideration.

4. Coding and implementation: The last stage of the problem solving is


the conversion of the detailed sequence of operations in to a language that
the computer can understand. Here each step is converted to its equivalent
instruction or instructions in the computer language that has been chosen
for the implantation.

Algorithm
Definition
A set of sequential steps usually written in Ordinary Language to solve a
given problem is called Algorithm.

It may be possible to solve to problem in more than one ways, resulting in


more than one algorithm. The choice of various algorithms depends on the
factors like reliability, accuracy and easy to modify. The most important
factor in the choice of algorithm is the time requirement to execute it, after
writing code in High-level language with the help of a computer. The
algorithm which will need the least time when executed is considered the
best.

Steps involved in algorithm development


An algorithm can be defined as a complete, unambiguous, finite number of
logical steps for solving a specific problem

Step1. Identification of input: For an algorithm, there are quantities to be


supplied called input and these are fed externally. The input is to be
indentified first for any specified problem.

Page 32
UNIT 1 -BASIC CONCEPTS
Step2: Identification of output: From an algorithm, at least one quantity
is produced, called for any specified problem.

Step3 : Identification the processing operations : All the calculations to be


performed in order to lead to output from the input are to be identified in an
orderly manner.

Step4 : Processing Definiteness : The instructions composing the algorithm


must be clear and there should not be any ambiguity in them.

Step5 : Processing Finiteness : If we go through the algorithm, then for all


cases, the algorithm should terminate after a finite number of steps.

Step6 : Possessing Effectiveness : The instructions in the algorithm must be


sufficiently basic and in practice they can be carries out easily.

An algorithm must possess the following properties

1. Finiteness: An algorithm must terminate in a finite number of steps


2. Definiteness: Each step of the algorithm must be precisely and
unambiguously stated
3. Effectiveness: Each step must be effective, in the sense that it should
be primitive easily convert able into program statement) can be performed
exactly in a finite amount of time.
4. Generality: The algorithm must be complete in itself so that it can be
used to solve problems of a specific type for any input data.
5. Input/output: Each algorithm must take zero, one or more quantities as
input data produce one or more output values. An algorithm can be written
in English like sentences or in any standard representation sometimes,
algorithm written in English like languages are called Pseudo Code

Example

Suppose we want to find the average of three numbers, the algorithm is


as follows

Step 1 Read the numbers a, b, c


Step 2 Compute the sum of a, b and c
Step 3 Divide the sum by 3
Step 4 Store the result in variable d
Step 5 Print the value of d
Step 6 End of the program

Page 33
UNIT 1 -BASIC CONCEPTS
Algorithm for Simple Problems

Write an algorithm to calculate the simple interest using the formula.


Simple interest = P*N* R/100.

Where P is principle Amount, N is the number of years and R is the rate


of interest.
Step 1: Read the three input quantities P, N and R.
Step 2 : Calculate simple interest as
Simple interest = P* N* R/100
Step 3: Print simple interest.
Step 4: Stop.

Area of Triangle

Write an algorithm to find the area of the triangle.

Let b, c be the sides of the triangle ABC and A the included angle between
the given sides.
Step 1: Input the given elements of the triangle namely sides b, c and angle
between the sides A.
Step 2: Area = (1/2) *b*C* sin A
Step 3: Output the Area
Step 4: Stop.

3. Write an algorithm to find the largest of three numbers X, Y,Z.

Step 1: Read the numbers X,Y,Z.


Step 2: if (X > Y)
Big = X
else BIG = Y
Step 3 : if (BIG < Z)
Step 4: Big = Z
Step 5: Print the largest number i.e. Big
Step 6: Stop.

Write an algorithm which will test whether a given integer value is


prime or not.
Algorithm prime testing:
Step 1: M 2
Step 2: read N
Step 3: MAX SQRT (N)
Step 4: While M < = MAX do
4.1 if (M* (N/M) = N

Page 34
UNIT 1 -BASIC CONCEPTS
4.1.1 then
4.1.1.1 go to step 7
4.2. M M + 1
Step 5: Write number is prime
Step 6: go to step 8
Step 7: Write number is not a prime
Step 8: end.

Write algorithm to find the factorial of a given number N

Step 1: PROD 1
Step 2: I 0
Step 3: read N
Step 4: While I < N do
4.1 I I + 1
4.2. PROD PROD* I
Step 5: Write Factorial of, N, is, PROD
Step 6: end.

Write an algorithm to find sum of given data values until negative


value is entered.

Algorithm Find Sum


Step 1: SUM 0
Step 2: I 0
Step 3: read NEW VALUE
Step 4: While NEW VALUE < = 0 do
4.1 SUM SUM + NEW VALUE
4.2 1 I + 1
4.3 read NEW VALUE
Step 5: Write Sum of, I, data value is, SUM Step 6: END

Write an algorithm to calculate the perimeter and area of rectangle.


Given its length and width.

Step 1: Read length of the rectangle.


Step 2: Read width of the rectangle.
Step 3: Calculate perimeter of the rectangle using the formula perimeter =
2* (length + width)
Step 4: Calculate area of the rectangle using the formula area = length
*width.
Step 5: Print perimeter.
Step 6: Print area.
Step 7: Stop.

Page 35
UNIT 1 -BASIC CONCEPTS

Flowchart

A flow chart is a step by step diagrammatic representation of the logic paths


to solve a given problem. Or A flowchart is visual or graphical representation
of an algorithm.

The flowcharts are pictorial representation of the methods to b used to solve


a given problem and help a great deal to analyze the problem and plan its
solution in a systematic and orderly manner. A flowchart when translated in
to a proper computer language, results in a complete program.

Advantages of Flowcharts

1. The flowchart shows the logic of a problem displayed in pictorial fashion


which felicitates easier checking of an algorithm.
2. The Flowchart is good means of communication to other users. It is also
a compact means of recording an algorithm solution to a problem.
3. The flowchart allows the problem solver to break the problem into parts.
These parts can be connected to make master chart.
4. The flowchart is a permanent record of the solution which can be
Consulted at a later time.

Symbols

Symbol Purpose Description

Used to indicate the flow of logic by connecting


Flow line
symbols.

Terminal(Stop/Start) Used to represent start and end of flowchart.

Input/Output Used for input and output operation.

Used for airthmetic operations and data-


Processing
manipulations.

Page 36
UNIT 1 -BASIC CONCEPTS

Symbol Purpose Description

Used to represent the operation in which there are


Desicion
two alternatives, true and false.

On-page Connector Used to join different flowline

Off-page Connector Used to connect flowchart portion on different page.

Predefined Used to represent a group of statements performing


Process/Function one processing task.

Examples of flowcharts
Draw a flowchart to add two numbers entered by user.

Draw flowchart to find the largest among three different numbers entered by user.

Page 37
UNIT 1 -BASIC CONCEPTS

Pseudo code

The Pseudo code is neither an algorithm nor a program. It is an abstract


form of a program. It consists of English like statements which perform the
specific operations. It is defined for an algorithm. It does not use any
graphical representation. In pseudo code, the program is represented in
terms of words and phrases, but the syntax of program is not strictly
followed.

Advantages:

* Easy to read

* Easy to understand

* Easy to modify.

Example:

Write a pseudo code to perform the basic arithmetic operations.

Read n1, n2

Sum = n1 + n2

Page 38
UNIT 1 -BASIC CONCEPTS
Diff = n1 n2

Mult = n1 * n2

Quot = n1/n2

Print sum, diff, mult, quot

End.

Page 39
UNIT 2-INTRODUCTION TO C LANGUAGE

UNIT 2-INTRODUCTION TO C LANGUAGE 10

Overview of C - Constants, Variables and Data Types- Compilation and


Linking - Operators and Expressions- Decision Making and Branching
Looping statements

Overview of C

The C Language is developed for creating system applications that direct


interacts to the hardware devices such as drivers, kernals 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 following ways:

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

1) C as a mother language

C language is considered as the mother language of all the modern


languages because most of the compilers, JVMs, Kernals etc. are
written in C language and most of languages follows c syntax e.g. C++,
Java etc.

It provides the core concepts like array, functions, file handling etc. that is
being used in many languages like C++, java, C# etc.

2) C as a system programming language

A system programming language is used to create system softwares. C


language is a system programming language because it can be used to do
low level programming (e.g. driver and kernel). It is generally used to
create hardware devices, OS, drivers, kernels etc. For example, linux kernel
is written in C.

It cant be used in internet programming like java, .net, php etc.

3) C as a procedural language

Page 40
UNIT 2-INTRODUCTION TO C LANGUAGE

A procedure is known as function, method, routine, subroutine etc. A


procedural language specifies a series of steps or procedures for the
program to solve the problem.

A procedural language breaks the program into functions, data structures


etc.

C is a procedural language. In C, variables and function prototypes must be


declared before being used.

4) C as a structured programming language

A structured programming language is a subset of procedural


language. Structure means to break a program into parts or blocks so
that it may be easy to understand.

In C language, we break the program into parts using functions. It makes


the program easier to understand and modify.

5) C as a mid-level programming language

C is considered as a middle level language because it supports the feature


of both low-level and high level language. C language program is
converted into assembly code, supports pointer arithmetic (low level), but it
is machine independent (feature of high level).

Low level language is specific to one machine i.e. machine dependent. It is


machine dependent, fast to run. But it is not easy to understand.

High Level language is not specific to one machine i.e. machine


independent. It is easy to understand.

History of C Language

C programming language was developed in 1972 by Dennis Ritchie at bell


laboratories of AT&T (American Telephone & Telegraph), located in U.S.A.

Dennis Ritchie is known as the founder of c language.

It was developed to overcome the problems of previous languages such as


B, BCPL etc.Initially, C language was developed to be used in UNIX
operating system. It inherits many features of previous languages such as
B and BCPL.Let's see the programming languages that were developed
before C language.

Page 41
UNIT 2-INTRODUCTION TO C LANGUAGE

Language Year Developed By

Algol 1960 International Group

BCPL 1967 Martin Richard

B 1970 Ken Thompson

Traditional C 1972 Dennis Ritchie

K&RC 1978 Kernighan & Dennis Ritchie

ANSI C 1989 ANSI Committee

ANSI/ISO C 1990 ISO Committee

C99 1999 Standardization Committee

Features of C Language

C is the widely used language. It provides a lot of featuresthat are given


below.

1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. structured programming language

Page 42
UNIT 2-INTRODUCTION TO C LANGUAGE

5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible

1) Simple

C is a simple language in the sense that it provides structured


approach (to break the problem into parts), rich set of library
functions, data types etc.

2) Machine Independent or Portable

Unlike assembly language, c programs can be executed in many


machines with little bit or no change. But it is not platform-independent.

3) Mid-level prorgramming language

C is also used to do low level programming. It is used to develop system


applications such as kernel, driver etc. It also supports the feature of
high level language. That is why it is known as mid-level language.

4) Structured prorgramming language

C is a structured programming language in the sense that we can break


the program into parts using functions. So, it is easy to understand and
modify.

5) Rich Library

C provides a lot of inbuilt functions that makes the development fast.

6) Memory Management

It supports the feature of dynamic memory allocation. In C language, we


can free the allocated memory at any time by calling the free() function.

7) Speed

The compilation and execution time of C language is fast.

Page 43
UNIT 2-INTRODUCTION TO C LANGUAGE

8) Pointer

C provides the feature of pointers. We can directly interact with the memory
by using the pointers. We can use pointers for memory, structures,
functions, array etc.

9) Recursion

In c, we can call the function within the function. It provides code


reusability for every function.

10) Extensible

C language is extensible because it can easily adopt new features.

First C Program

#include <stdio.h>
#include <conio.h>
void main()
{
printf("Hello C Language");
getch();
}

#include <stdio.h> includes the standard input output library functions.


The printf() function is defined in stdio.h .

#include <conio.h> includes the console input output library functions.


The getch() function is defined in conio.h file.

void main() The main() function is the entry point of every


program in c language. The void keyword specifies that it returns no value.

printf() The printf() function is used to print data on the console.

getch() The getch() function asks for a single character. Until you press
any key, it blocks the screen.

How to compile and run the c program

There are 2 ways to compile and run the c program, by menu and by
shortcut.

Page 44
UNIT 2-INTRODUCTION TO C LANGUAGE

Flow of C Program

The C program follows many steps in execution. To understand the flow of C


program well, let us see a simple program first.

Simple .c
#include <stdio.h>
#include <conio.h>
void main(){
clrscr();
printf("Hello C Language");

getch();
}

Page 45
UNIT 2-INTRODUCTION TO C LANGUAGE

1) C program (source code) is sent to preprocessor first. The preprocessor is


responsible to convert preprocessor directives into their respective values.
The preprocessor generates an expanded source code.

2) Expanded source code is sent to compiler which compiles the code and
converts it into assembly code.

3) The assembly code is sent to assembler which assembles the code and
converts it into object code. Now a simple.obj file is generated.

4) The object code is sent to linker which links it to the library such as
header files. Then it is converted into executable code. A simple.exe file is
generated.

5) The executable code is sent to loader which loads it into memory and
then it is executed. After execution, output is sent to console.

printf and scanf in C

The printf() and scanf() functions are used for input and output in C
language. Both functions are inbuilt library functions, defined in stdio.h
(header file).

printf() function

The printf() function is used for output. It prints the given statement to
the console.

The syntax of printf() function is given below:

printf("format string",argument_list);

scanf() function

The scanf() function is used for input. It reads the input data from the
console.

1. scanf("format string",argument_list);

Page 46
UNIT 2-INTRODUCTION TO C LANGUAGE

Program to print cube of given number

Let's see a simple example of c language that gets input from the user and
prints the cube of the given number.

#include<stdio.h>
#include<conio.h>
void main()
{
int number;
clrscr();
printf("enter a number:");
scanf("%d",&number);
printf("cube of number is:%d ",number*number*number);
getch();
}
Output
enter a number:5
cube of number is:125

The scanf("%d",&number) statement reads integer number from the


console and stores the given value in number variable.

The printf("cube of number


is:%d",number*number*number) statement prints the cube of number
on the console.
VARIABLES IN C

A variable is a name of memory location. It is used to store data. Its value


can be changed and it can be reused many times.

It is a way to represent memory location through symbol so that it can be


easily identified.

Let's see the syntax to declare a variable:

1. type variable_list;

The example of declaring variable is given below:

int a;

Page 47
UNIT 2-INTRODUCTION TO C LANGUAGE

float b;
char c;

Here, a, b, c are variables and int,float,char are data types.

We can also provide values while declaring the variables as given below:

int a=10,b=20;//declaring 2 variable of integer type


float f=20.8;
char c='A';

Rules for defining variables

o A variable can have alphabets, digits and underscore.


o A variable name can start with alphabet and underscore only. It can't
start with digit.
o No white space is allowed within variable name.
o A variable name must not be any reserved word or keyword e.g. int,
float etc.

Valid variable names:

1. int a;
2. int _ab;
3. int a30;

Invalid variable names:

int 2;
int a b;
int long;

Types of Variables in C

There are many types of variables in c:

1. local variable
2. global variable
3. static variable
4. automatic variable

Page 48
UNIT 2-INTRODUCTION TO C LANGUAGE

5. external variable

Local Variable

A variable that is declared inside the function or block is called local variable.

It must be declared at the start of the block.

void function1(){
int x=10;//local variable
}

You must have to initialize the local variable before it is used.

Global Variable

A variable that is declared outside the function or block is called global


variable. Any function can change the value of the global variable. It is
available to all the functions.

It must be declared at the start of the block.

int value=20;//global variable


void function1(){
int x=10;//local variable
}

Static Variable

A variable that is declared with static keyword is called static variable.

It retains its value between multiple function calls.

void function1(){
int x=10;//local variable
static int y=10;//static variable
x=x+1;
y=y+1;
printf("%d,%d",x,y);
}

If you call this function many times, local variable will print the same
value for each function call e.g, 11,11,11 and so on. But static variable

Page 49
UNIT 2-INTRODUCTION TO C LANGUAGE

will print the incremented value in each function call e.g. 11, 12, 13 and
so on.

Automatic Variable

All variables in C that is declared inside the block, are automatic variables by
default. By we can explicitly declare automatic variable using auto
keyword.

void main(){
int x=10;//local variable (also automatic)
auto int y=20;//automatic variable
}

External Variable

We can share a variable in multiple C source files by using external variable.


To declare a external variable, you need to use extern keyword.

myfile.h

extern int x=10;//external variable (also global)


program1.c

#include "myfile.h"
#include <stdio.h>
void printValue(){
printf("Global variable: %d", global_variable); }

Page 50
UNIT 2-INTRODUCTION TO C LANGUAGE

DATA TYPES IN C
A data type specifies the type of data that a variable can store such as
integer, floating, character etc.

There are 4 types of data types in C language.

Types Data Types

Basic Data Type int, char, float, double

Derived Data Type array, pointer, structure, union

Enumeration Data Type Enum

Void Data Type Void

Basic Data Types

The basic data types are integer-based and floating-point based. C language
supports both signed and unsigned literals.

The memory size of basic data types may change according to 32 or 64 bit
operating system.

Let's see the basic data types. Its size is given according to 32 bit
architecture.

Data Types Memory Size Range

Char 1 byte 128 to 127

signed char 1 byte 128 to 127

unsigned char 1 byte 0 to 255

Short 2 byte 32,768 to 32,767

signed short 2 byte 32,768 to 32,767

Page 51
UNIT 2-INTRODUCTION TO C LANGUAGE

unsigned short 2 byte 0 to 65,535

Int 2 byte 32,768 to 32,767

signed int 2 byte 32,768 to 32,767

unsigned int 2 byte 0 to 65,535

short int 2 byte 32,768 to 32,767

signed short int 2 byte 32,768 to 32,767

unsigned short int 2 byte 0 to 65,535

long int 4 byte -2,147,483,648 to 2,147,483,647

signed long int 4 byte -2,147,483,648 to 2,147,483,647

unsigned long int 4 byte 0 to 4,294,967,295

Float 4 byte

double 8 byte

long double 10 byte

OPERATORS

operators are the symbols which tell the computer to execute certain
mathematical or logical operations. A mathematical or logical expression is
generally formed with the help of an operator. C programming offers a
number of operators which are classified into 8 categories viz.

1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and Decrement operators
6. Conditional operators

Page 52
UNIT 2-INTRODUCTION TO C LANGUAGE

7. Bitwise operators
8. Special operators

1. Arithmetic Operators
C programming language provides all basic arithmetic operators: +, -, *, /
and %.

Note: / is integer division which only gives integer part as result


after division. % is modulo division which gives the remainder of
integer division as result.
Some examples of arithmetic operators are:

a+b

ab

a*b

a /b

a%b

In these examples, a and b are variables and are called operands.


Note: % cannot be used on floating data type.

Page 53
UNIT 2-INTRODUCTION TO C LANGUAGE

Example Program using Arithmetic Operators

#include<stdio.h> // Header File


#include <conio.h>
void main ( ) /* main is the starting of every c program */
{
int a=5,b=2; //Local Declaration
clrscr( );
printf(Addition : %d\n,(a+b));
printf(Subtraction : %d\n,(a-b));
printf(Multiplication : %d\n,(a*b));
printf(Division : %d\n,(a/b));
printf(Modulus(remainder): %d,(a%b));
getch( );
}

Output

Addition :7
Subtraction :3
Multiplication : 10
Division :2
Modulus(remainder): 1

2. Relational Operators
Relational operators are used when we have to make comparisons. C
programming offers 6 relational operators.

Page 54
UNIT 2-INTRODUCTION TO C LANGUAGE

Relational expression is an expression which contains the relational operator.


Relational operators are most commonly used in decision statements
like if, while, etc. Some simple relational expressions are:

1<5 9 != 8 2 > 1+3

Note: Arithmetic operators have higher priority than relational


operators meaning that if arithmetic expressions are present on two
sides of a relational operator then arithmetic expressions will be
calculated first and then the result will be compared.

Example Program using Relational Operators


#include<stdio.h>
#include <conio.h>
void main()
{
clrscr();
printf(\n5!=3:%d,(5!=3));
printf(\n5<=3:%d,(5<=3));
printf(\n5>=3:%d,(5>=3));
printf(\n5<7 :%d,(5<7));
printf(\n5>4 :%d,(5>4));
getch();
}

Output

5!=3 :1
5<=3 :0
5>=3 :1
5<7 :1
5>4 :1

Page 55
UNIT 2-INTRODUCTION TO C LANGUAGE

3. Logical Operators
Logical operators are used when more than one conditions are to be tested
and based on that result, decisions have to be made. C programming offers
three logical operators. They are:

For example:

a < 18 || a> 60

An expression which combines two or more relational expressions is known


as logical expression.

Example Program using Logical Operators


#include<stdio.h>
#include <conio.h>
void main ( )
{
clrscr( );
printf(\n(5<=8)&&(4>=2):%d,((5<=8)&&(4>=2)));
printf(\n(5>=3)||(6<4):%d,((5>=3)||(6<4)));
printf(\n!(7==7):%d,!(7==7));
getch( );
}

Output

(5<=8)&&(4>=2) : 1
(5>=3)||(6<4) : 1
!(7==7) : 0

Page 56
UNIT 2-INTRODUCTION TO C LANGUAGE

4. Assignment Operators
Assignment operators are used to assign result of an expression to a
variable. = is the assignment operator in C. Furthermore, C also allows the
use of shorthand assignment operators. Shorthand operators take the form:

var op = exp;

where var is a variable, op is arithmetic operator, exp is an expression. In


this case, op= is known as shorthand assignment operator.
The above assignment

var op = exp;

is the same as the assignment

var = var op exp;

Consider an example:

x += y;

Here, the above statement means the same as

x = x + y;

Note: Shorthand assignment can be used with all arithmetic


operators.

5. Increment and Decrement Operators


C programming allows the use of ++ and operators which are increment
and decrement operators respectively. Both the increment and decrement
operators are unary operators. The increment operator ++ adds 1 to the
operand and the decrement operator subtracts 1 from the operand. The
general syntax of these operators are:
Increment Operator: m++ or ++m;
Decrement Operator: m--or --m;

Page 57
UNIT 2-INTRODUCTION TO C LANGUAGE

In the example above, m++ simply means m=m+1; and m-- simply
means m=m-1;
Increment and decrement operators are mostly used in for and while loops.

++m and m++ performs the same operation when they form statements
independently but they function differently when they are used in right hand
side of an expression.
++m is known as prefix operator and m++ is known as postfix operator. A
prefix operator firstly adds 1 to the operand and then the result is assigned
to the variable on the left whereas a postfix operator firstly assigns value to
the variable on the left and then increases the operand by 1. Same is in the
case of decrement operator.
For example,

X=10;
Y=++X;

Example Program using Increment and Decrement Operators

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf(Enter a & b value : \n);
scanf(%d%d,&a,&b);
printf(Value of a & b before increment : %d %d\n,a,b);
printf(Value of a & b after increment : %d %d\n,a++,b++);
printf(Value of a & b after decrement : %d %d\n,a--,b--);
getch();
}

Output

Enter a & b value :

Page 58
UNIT 2-INTRODUCTION TO C LANGUAGE

Value of a & b before increment : 6 9

Value of a & b after increment :7 10

Value of a & b after decrement :5 8

6. Conditional Operator
The operator pair ? and : is known as conditional operator. These pair of
operators are ternary operators. The general syntax of conditional operator
is:

expression1 ? expression2 : expression3 ;

This syntax can be understood as a substitute of if else statement.

For example,

a=3;

b=5;

Consider an if else statement as:

if (a > b)

x=a;

else

x=b;

Now, this if else statement can be written by using conditional operator as:

x = (a > b) ? a : b ;

Page 59
UNIT 2-INTRODUCTION TO C LANGUAGE

Example Program using Conditional Operator

#include<stdio.h>
#include <conio.h>
void main ( )
{
int a=5,b=8,c;
clrscr( );
c = a>b?a:b; //Conditional operator
printf(" \n The Larger Value is %d",c);
getch( );
}

Output
The Larger Value is 8

7. Bitwise Operator
In C programming, bitwise operators are used for testing the bits or shifting
them left or right. The bitwise operators available in C are:

8. Special Operators
C programming supports special operators like comma operator, sizeof
operator, pointer operators (& and *) and member selection operators (. and
->). The comma operator and sizeof operator are discussed in this section

Page 60
UNIT 2-INTRODUCTION TO C LANGUAGE

whereas the pointer and member selection operators are discussed in later
sections.

1. Comma Operator
The comma operator can be used to link the related expressions together. A
comma linked expression is evaluated from left to right and the value of the
right most expression is the value of the combined expression.

For example:

x = (a = 2, b = 4, a+b)

In this example, the expression is evaluated from left to right. So at first,


variable a is assigned value 2, then variable b is assigned value 4 and then
value 6 is assigned to the variable x. Comma operators are commonly used
in for loops, while loops, while exchanging values, etc.

2 .Sizeof() operator
The sizeof operator is usually used with an operand which may be variable,
constant or a data type qualifier. This operator returns the number of bytes
the operand occupies. Sizeof operator is a compile time operator. Some
examples of use of sizeof operator are:

x = sizeof (a);

y = sizeof(float);

The sizeof operator is usually used to determine the length of arrays and
structures when their sizes are not known. It is also used in dynamic
memory allocation.

9.C Expressions
Arithmetic expression in C is a combination of variables, constants and
operators written in a proper syntax. C can easily handle any complex
mathematical expressions but these mathematical expressions have to be

Page 61
UNIT 2-INTRODUCTION TO C LANGUAGE

written in a proper syntax. Some examples of mathematical expressions


written in proper syntax of C are:

Note: C does not have any operator for exponentiation.

10.C Operator Precedence


At first, the expressions within parenthesis are evaluated. If no parenthesis
is present, then the arithmetic expression is evaluated from left to right.
There are two priority levels of operators in C.

High priority: * / %
Low priority: + -
The evaluation procedure of an arithmetic expression includes two left to
right passes through the entire expression. In the first pass, the high priority
operators are applied as they are encountered and in the second pass, low
priority operations are applied as they are encountered.

Suppose, we have an arithmetic expression as:

x = 9 12 / 3 + 3 *2 - 1

This expression is evaluated in two left to right passes as:

First Pass
Step 1: x = 9-4 + 3 * 2 1

Step 2: x = 9 4 + 6 1

Second Pass

Step 1: x = 5 + 6 1
Step 2: x = 11 1
Step 3: x = 10
But when parenthesis is used in the same expression, the order of
evaluation gets changed.

For example,

Page 62
UNIT 2-INTRODUCTION TO C LANGUAGE

x = 9 12 / (3 + 3) * (2 1)

When parentheses are present then the expression inside the parenthesis
are evaluated first from left to right. The expression is now evaluated in
three passes as:

First Pass
Step 1: x = 9 12 / 6 * (2 1)

Step 2: x= 9 12 / 6 * 1

Second Pass
Step 1: x= 9 2 * 1

Step 2: x = 9 2

Third Pass
Step 3: x= 7

There may even arise a case where nested parentheses are present (i.e.
parenthesis inside parenthesis). In such case, the expression inside the
innermost set of parentheses is evaluated first and then the outer
parentheses are evaluated.

For example, we have an expression as:

x = 9 ((12 / 3) + 3 * 2) 1

The expression is now evaluated as:

First Pass:
Step 1: x = 9 (4 + 3 * 2) 1

Step 2: x= 9 (4 + 6) 1

Step 3: x= 9 10 -1

Page 63
UNIT 2-INTRODUCTION TO C LANGUAGE

Second Pass
Step 1: x= - 1 1 Step 2: x = -2

DECISION MAKING AND BRANCHING

if else Statement

The if statement in C language is used to perform operation on the basis of


condition. By using if-else statement, you can perform operation either
condition is true or false.

There are many ways to use if statement in C language:

o If statement
o If-else statement
o If else-if ladder
o Nested if

If Statement

The single if statement in C language is used to execute the code if condition


is true. The syntax of if statement
is given below:

1. if(expression){
2. //code to be executed
3. }

Flowchart of if statement in C

Let's see a simple example of c


language if statement.

#include<stdio.h>
#include<conio.h>
void main(){
int number=0;
clrscr();
printf("enter a number:");
scanf("%d",&number);
if(number%2==0){
printf("%d is even number",number);

Page 64
UNIT 2-INTRODUCTION TO C LANGUAGE

}
getch();
}

Output
enter a number:4
4 is even number

If-else Statement

The if-else statement in C language is used to execute the code if condition


is true or false. The syntax of if-else statement is given below:

if(expression){
//code to be executed if condition is true
}else{
//code to be executed if condition is false
}

Flowchart of if-else statement in C


Let's see the simple example of even and odd number using if-else statement in C
language.

#include<stdio.h>
#include<conio.h>
void main(){
int number=0;
clrscr();

printf("enter a number:");
scanf("%d",&number);

if(number%2==0){
printf("%d is even number",
number);
}
else{
printf("%d is odd number",number);
}
getch();
}

Output
enter a number:4

Page 65
UNIT 2-INTRODUCTION TO C LANGUAGE

4 is even number
enter a number:5
5 is odd number

If else-if ladder Statement

The if else-if statement is used to execute one code from multiple conditions.
The syntax of if else-if statement is given below:

if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}

Flowchart of else-if ladder statement in C

The example of if-else-if statement in C language is given below.

Page 66
UNIT 2-INTRODUCTION TO C LANGUAGE

#include<stdio.h>
#include<conio.h>
void main(){
int number=0;
clrscr();

printf("enter a number:");
scanf("%d",&number);

if(number==10){
printf("number is equals to 10");
}
else if(number==50){
printf("number is equal to 50");
}
else if(number==100){
printf("number is equal to 100");
}
else{
printf("number is not equal to 10, 50 or 100");
}
getch();
}

Output
enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50

SWITCH STATEMENT

The switch statement in C language is used to execute the code from


multiple conditions. It is like if else-if ladder statement.

The syntax of switch statement in c language is given below:

switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:

Page 67
UNIT 2-INTRODUCTION TO C LANGUAGE

//code to be executed;
break; //optional
......

default:
code to be executed if all cases are not matched;
}

Rules for switch statement in C language

1) The switch expression must be of integer or character type.

2) The case value must be integer or character constant.

3) The case value can be used only inside the switch statement.

4) The break statement in switch case is not must. It is optional. If there is


no break statement found in switch case, all the cases will be executed after
matching the case value. It is known as fall through state of C switch
statement.

Let's try to understand it by the examples. We are assuming there are


following variables.

1. int x,y,z;
2. char a,b;
3. float f;

Valid Switch Invalid Switch Valid Case Invalid Case

switch(x) switch(f) case 3; case 2.5;

switch(x>y) switch(x+2.5) case 'a'; case x;

switch(a+b-2) case 1+2; case x+2;

switch(func(x,y)) case 'x'>'y'; case 1,2,3;

Page 68
UNIT 2-INTRODUCTION TO C LANGUAGE

Flowchart of switch statement in C

Let's see a simple example of c language switch statement.

#include<stdio.h>
#include<conio.h>
void main(){
int number=0;
clrscr();

Page 69
UNIT 2-INTRODUCTION TO C LANGUAGE

printf("enter a number:");
scanf("%d",&number);

switch(number){
case 10:
printf("number is equals to 10");
break;
case 50:
printf("number is equal to 50");
break;
case 100:
printf("number is equal to 100");
break;
default:
printf("number is not equal to 10, 50 or 100");
}
getch();
}

Output
enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50

C Switch statement is fall-through

In C language, switch statement is fall through, it means if you don't use


break statement in switch case, all the case after matching case will be
executed.

Example

#include<stdio.h>
#include<conio.h>
void main(){
int number=0;
clrscr();

printf("enter a number:");
scanf("%d",&number);

Page 70
UNIT 2-INTRODUCTION TO C LANGUAGE

switch(number){
case 10:
printf("number is equals to 10\n");
case 50:
printf("number is equal to 50\n");
case 100:
printf("number is equal to 100\n");
default:
printf("number is not equal to 10, 50 or 100");
}
getch();
}

Output
enter a number:10
number is equals to 10
number is equals to 50
number is equals to 100
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
number is equals to 100
number is not equal to 10, 50 or 100

LOOPING STATEMENT

The loops in C language are used to execute a block of code or a part of the
program several times.

In other words, it iterates a code or group of code many times.

Why use loops in C language?

Suppose that you have to print table of 2, then you need to write 10 lines of
code.

By using the loop statement, you can do it by 2 or 3 lines of code only.

Advantage of loops in C

1) It saves code.

2) It helps to traverse the elements of array (which is covered in next


pages).

Page 71
UNIT 2-INTRODUCTION TO C LANGUAGE

types of C Loops

There are three types of loops in C language that is given below:

1. do while
2. while
3. for

do while loop

To execute a part of program or code several times, we can use do-while


loop of C language. The code given between the do and while block will be
executed until condition is true.

In do while loop, statement is given before the condition, so statement or


code will be executed at lease one time. In other words, we can say it is
executed 1 or more times.

It is better if you have to execute the code at least once.

do while loop syntax

syntax

do{
//code to be executed
}while(condition);

Flowchart of do while loop

Page 72
UNIT 2-INTRODUCTION TO C LANGUAGE

do while example

There is given the simple program of c language do while loop where we are
printing the table of 1.

#include <stdio.h>
#include <conio.h>
void main(){
int i=1;
clrscr();

do{
printf("%d \n",i);
i++;
}while(i<=10);

getch();
}

Output
1
2
3
4
5
6
7
8
9
10

Program to print table for the given number using do while loop

#include <stdio.h>
#include <conio.h>
void main(){
int i=1,number=0;
clrscr();
printf("Enter a number: ");
scanf("%d",&number);
do{
printf("%d \n",(number*i));
i++;

Page 73
UNIT 2-INTRODUCTION TO C LANGUAGE

}while(i<=10);
getch();
}

Output
Enter a number: 5
5
10
15
20
25
30
35
40
45
50
Enter a number: 10
10
20
30
40
50
60
70
80
90
100

infinitive do while loop

If you pass 1 as a expression in do while loop, it will run infinite number of


times.

do{
//statement
}while(1);

while loop

The while loop in C language is used to iterate the part of program or


statements many times.

In while loop, condition is given before the statement. So it is different from


the do while loop. It can execute the statements 0 or more times.

Page 74
UNIT 2-INTRODUCTION TO C LANGUAGE

When use while loop in C

The C language while loop should be used if number of iteration is uncertain


or unknown.

Syntax

The syntax of while loop in c language is given below:

while(condition){
//code to be executed
}

Flowchart of while loop in C

Example of while loop in C language

Let's see the simple program of while loop that prints table of 1.

#include <stdio.h>
#include <conio.h>
void main(){
int i=1;
clrscr();
while(i<=10){
printf("%d \n",i);

Page 75
UNIT 2-INTRODUCTION TO C LANGUAGE

i++;
}
getch();
}

Output
1
2
3
4
5
6
7
8
9
10

Program to print table for the given number using while loop in C

#include <stdio.h>
#include <conio.h>
void main(){
int i=1,number=0;
clrscr();
printf("Enter a number: ");
scanf("%d",&number);
while(i<=10){
printf("%d \n",(number*i));
i++;
}
getch();
}

Output
Enter a number: 50
50
100
150
200
250
300
350
400
450

Page 76
UNIT 2-INTRODUCTION TO C LANGUAGE

500
Enter a number: 100
100
200
300
400
500
600
700
800
900
1000

Infinitive while loop

If you pass 1 as a expression in while loop, it will run infinite number of


times.

while(1){
//statement
}

FOR LOOP
The for loop in C language is also used to iterate the
statement or a part of the program several times, like
while and do-while loop.

But, we can initialize and increment or decrement the variable also at the
time of checking the condition in for loop.

Unlike do while loop, the condition or expression in for loop is given before
the statement, so it may execute the statement 0 or more times.

When use for loop in C

For loop is better if number of iteration is known by the programmer.

Syntax

The syntax of for loop in c language is given below:

for(initialization;condition;incr/decr){

Page 77
UNIT 2-INTRODUCTION TO C LANGUAGE

//code to be executed
}

Flowchart of for loop in C

Example of for loop in C language

Let's see the simple program of for loop that prints table of 1.

#include <stdio.h>
#include <conio.h>
void main(){
int i=0;
clrscr();

for(i=1;i<=10;i++){
printf("%d \n",i);
}

getch();
}

Output
1
2
3
4
5

Page 78
UNIT 2-INTRODUCTION TO C LANGUAGE

6
7
8
9
10

C Program : Print table for the given number using C for loop

#include <stdio.h>
#include <conio.h>
void main(){
int i=1,number=0;
clrscr();

printf("Enter a number: ");


scanf("%d",&number);

for(i=1;i<=10;i++){
printf("%d \n",(number*i));
}

getch();
}

Output
Enter a number: 2
2
4
6
8
10
12
14
16
18
20
Enter a number: 1000
1000
2000
3000
4000
5000
6000
7000
8000

Page 79
UNIT 2-INTRODUCTION TO C LANGUAGE

9000
10000

Infinitive for loop

If you don't initialize any variable, check condition and increment or


decrement variable in for loop, it is known as infinitive for loop.

In other words, if you place 2 semicolons in for loop, it is known as infinitive


for loop.

for(;;){
printf("infinitive for loop example by javatpoint");
}

If you run this program, you will see above statement infinite times.

C break statement

The break statement in C language is used to break the execution of loop


(while, do while and for) and switch case.

In case of inner loops, it terminates the control of inner loop only.

There can be two usage of C break keyword:

1. With switch case


2. With loop

Syntax:

jump-statement;
break;

The jump statement in c break syntax can be while loop, do while loop, for
loop or switch case.

Flowchart of break in c

Example of C break statement with switch case

Click here to see the example of C break with switch statement.

Example of C break statement with loop

Page 80
UNIT 2-INTRODUCTION TO C LANGUAGE

#include <stdio.h>
#include <conio.h>
void main(){
int i=1;//initializing a local variable
clrscr();

//starting a loop from 1 to 10


for(i=1;i<=10;i++){
printf("%d \n",i);
if(i==5){//if value of i is equal to 5, it will break the loop
break;
}
}//end of for loop

getch();
}

Output
1
2
3
4
5

As you can see on console output, loop from 1 to 10 is not printed after
i==5.

C break statement with inner loop

In such case, it breaks only inner loop, but not outer loop.

#include <stdio.h>
#include <conio.h>
void main(){
int i=1,j=1;//initializing a local variable
clrscr();

for(i=1;i<=3;i++){
for(j=1;j<=3;j++){
printf("%d &d\n",i,j);
if(i==2 && j==2){
break;//will break loop of j only
}
Page 81
UNIT 2-INTRODUCTION TO C LANGUAGE

}
}//end of for loop

getch();
}

Output
11
12
13
21
22
31
32
33

As you can see the output on console, 2 3 is not printed because there is
break statement after printing i==2 and j==2. But 3 1, 3 2 and 3 3 is
printed because break statement works for inner loop only.

continue statement

The continue statement in C language is used to continue the execution of


loop (while, do while and for). It is used with if condition within the loop.

In case of inner loops, it continues the control of inner loop only.

Syntax:
jump-statement;
continue;

The jump statement can be while, do while and for loop.

Example of continue statement in c

#include <stdio.h>
#include <conio.h>
void main(){
int i=1;//initializing a local variable
clrscr();

//starting a loop from 1 to 10


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

Page 82
UNIT 2-INTRODUCTION TO C LANGUAGE

if(i==5){//if value of i is equal to 5, it will continue the loop


continue;
}
printf("%d \n",i);
}//end of for loop

getch();
}

Output
1
2
3
4
6
7
8
9
10

As you can see, 5 is not printed on the console because loop is continued at
i==5.

continue statement with inner loop

In such case, C continue statement continues only inner loop, but not outer
loop.

#include <stdio.h>
#include <conio.h>
void main(){
int i=1,j=1;//initializing a local variable
clrscr();

for(i=1;i<=3;i++){
for(j=1;j<=3;j++){
if(i==2 && j==2){
continue;//will continue loop of j only
}
printf("%d &d\n",i,j);
}
}//end of for loop

Page 83
UNIT 2-INTRODUCTION TO C LANGUAGE

getch();
}

Output
11
12
13
21
23
31
32
33

As you can see, 2 2 is not printed on the console because inner loop is
continued at i==2 and j==2.

goto statement

The goto statement is known as jump statement in C language. It is used to


unconditionally jump to other label. It transfers control to other parts of the
program.

It is rarely used today because it makes program less readable and complex.

Syntax:

goto label;

goto example

Let's see a simple example to use goto statement in C language.

#include <stdio.h>
#include <conio.h>
void main()
{
int age;
clrscr();
ineligible:
printf("You are not eligible to vote!\n");
break;
printf("Enter you age:\n");
scanf("%d", &age);
if(age<18)
goto ineligible;

Page 84
UNIT 2-INTRODUCTION TO C LANGUAGE

else
printf("You are eligible to vote!\n");
getch();
}

Output:

You are not eligible to vote!


Enter you age:
11
You are not eligible to vote!
Enter you age:
44
You are eligible to vote!

Page 85
UNIT 3-ARRAYS AND STRINGS

UNIT 3-ARRAYS AND STRINGS 9

Arrays-One Dimensional Array- Declaration and Initialization-Two


Dimensional Array-Declaration and Initialization- Programs using Arrays-
Strings- String Handling Functions, Programs using Strings- Managing I/O
Operations

Array

Array in C language is a collection or group of elements (data). All the


elements of c array are homogeneous (similar). It has contiguous
memory location.

C array is beneficial if you have to store similar elements. Suppose you


have to store marks of 50 students, one way to do this is allotting 50
variables. So it will be typical and hard to manage. For example we can
not access the value of these variables with only 1 or 2 lines of code.

Another way to do this is array. By using array, we can access the


elements easily. Only few lines of code is required to access the elements
of array.

Advantage of Array

1) Code Optimization: Less code to the access the data.

2) Easy to traverse data: By using the for loop, we can retrieve the
elements of an array easily.

3) Easy to sort data: To sort the elements of array, we need a few lines
of code only.

4) Random Access: We can access any element randomly using the


array.

Page 86
UNIT 3-ARRAYS AND STRINGS
Disadvantage of C Array

1) Fixed Size: Whatever size, we define at the time of declaration of


array, we can't exceed the limit. So, it doesn't grow the size dynamically
like LinkedList which we will learn later.

Declaration of C Array

We can declare an array in the c language in the following way.

data_type array_name[array_size];

Now, let us see the example to declare array.

int marks[5];

Here, int is the data_type, marks is the array_name and 5 is


the array_size.

Initialization of Array

A simple way to initialize array is by index. Notice that array index


starts from 0 and ends with [SIZE - 1].

marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;

Page 87
UNIT 3-ARRAYS AND STRINGS
Array example Program

#include <stdio.h>
#include <conio.h>
void main(){
int i=0;
int marks[5];//declaration of array
clrscr();
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}//end of for loop
getch();
}

Output

80
60
70
85
75

Array: Declaration with Initialization

We can initialize the c array at the time of declaration. Let's see the code.

int marks[5]={20,30,40,50,60};

In such case, there is no requirement to define size. So it can also be


written as the following code.

int marks[]={20,30,40,50,60};

Page 88
UNIT 3-ARRAYS AND STRINGS
Let's see the full program to declare and initialize the array in C.

#include <stdio.h>
#include <conio.h>
void main(){
int i=0;
int marks[5]={20,30,40,50,60};//declaration and initialization of array
clrscr();

//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}

getch();
}

Output

20
30
40
50
60

Program to get values of array from users and display it

#include<stdio.h>
#include<conio.h>
void main()
{
int a[5],i;
clrscr();
printf("Enter five values : \n");
for(i=0;i<5;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<5;i++)
{
printf("\nThe value in a[%d] is %d",i,a[i]);
}
getch();

Page 89
UNIT 3-ARRAYS AND STRINGS
}

OUTPUT

Enter five values :

10

20

30

40

50

The value in a[0] is 10

The value in a[1] is 20

The value in a[2] is 30

The value in a[3] is 40

The value in a[4] is 50

Program to find maximum number in an array

#include<stdio.h>
#include<conio.h>
void main()
{
int a[5],i,max;
clrscr();
printf("Enter five values : \n");
for(i=0;i<5;i++)
{
scanf("%d",&a[i]);
}
max=a[0];
for(i=1;i<5;i++)
{
if(max<a[i])
{
max=a[i];
}

Page 90
UNIT 3-ARRAYS AND STRINGS
}
printf(Maximum no is %d,max);

getch(); }

OUTPUT

Enter five values :

10

20

30

40

50

Maximum no is 50

Program to find the sum of the elements in an array

#include<stdio.h>
#include<conio.h>
void main()
{
int a[5],i,sum=0;
clrscr();
printf("Enter five values : \n");
for(i=0;i<5;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<5;i++)
{
sum=sum+a[i];
}
printf(The sum of elements in array is : %d,sum);
getch();
}

OUTPUT

Enter five values :

Page 91
UNIT 3-ARRAYS AND STRINGS
2

The sum of elements in array is : 15

Program to sort the numbers in ascending order

#include<stdio.h>
#include<conio.h>
void main()
{
int a[80],i,j,t,n; // maximum elements in the array is 80
clrscr();
printf(Enter the number of elements to be sorted \n);
scanf(%d,&n);

for(i=0;i<n;i++)
{
printf("Enter %d element : \n",i+1);
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}

}
}
printf(Ascending order : \n);
for(i=0;i<n;i++)
{
printf(%d\t,a[i]);
}
getch();
}

Page 92
UNIT 3-ARRAYS AND STRINGS
OUTPUT

Enter the number of elements to be sorted

Enter 1 element :

40

Enter 2 element :

10

Enter 3 element :

30

Enter 4 element :

50

Enter 5 element :

20

Ascending order :

10 20 30 40 50

Program to search element in array(Linear Search)

#include<stdio.h>
#include<conio.h>
void main()
{
int a[5]={10,20,30,40,50};
int key;
clrscr();
printf("Enter search value:\n");
scanf("%d",&key);
for(i=0;i<5;i++)
{
if(key==a[i])
{
printf(Value found);
break;
}

Page 93
UNIT 3-ARRAYS AND STRINGS
else
{
printf(Value not found);
}
}
getch();
}

OUTPUT

Enter search value : 40

Value found

Two Dimensional Array

The two dimensional array in C language is represented in the form of


rows and columns, also known as matrix. It is also known as array of
arrays or list of arrays.

The two dimensional, three dimensional or other dimensional arrays are


also known as multidimensional arrays.

Declaration of two dimensional Array in C

We can declare an array in the c language in the following way.

data_type array_name[size1][size2];

A simple example to declare two dimensional array is given below.

int twodimen[4][3];

Here, 4 is the row number and 3 is the column number.

Initialization of 2D Array

A way to initialize the two dimensional array at the time of declaration is


given below.

int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};

Two dimensional array example in C

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

Page 94
UNIT 3-ARRAYS AND STRINGS

int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
clrscr();

//traversing 2D array
for(i=0;i<4;i++){
for(j=0;j<3;j++){
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
}//end of j
}//end of i

getch();
}

Output

arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

Program to assign values to array from user and to display it

#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],i,j;
clrscr();
printf(Enter 9 values in array : \n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf(%d,&a[i][j]);

Page 95
UNIT 3-ARRAYS AND STRINGS
}
}
printf(Values in array : \n);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf(a[%d][%d] = %d\n,i,j,a[i][j]);
}
}

getch();

Output

Enter 9 values in array :

10

20

30

40

50

60

70

80

90

Values in array :

a[0][0]=10

a[0][1]=20

a[0][2]=30

a[1][0]=40

a[1][1]=50

a[1][2]=60

Page 96
UNIT 3-ARRAYS AND STRINGS
a[2][0]=70

a[2][1]=80

a[2][2]=90

Program to implement Matrix addition

#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],b[3][3],c[3][3],i,j;
clrscr();
printf(Enter values of Matrix A : \n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf(%d,&a[i][j]);
}
}
printf(Enter values of Matrix B : \n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf(%d,&b[i][j]);
}
}

for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
printf(Added Matrix\n);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf(%d\t,c[i][j]);
}
printf(\n);
}

Page 97
UNIT 3-ARRAYS AND STRINGS
getch();
}

Output

Enter values of Matix A :

Enter values of Matix B :

Addded Matrix

2 4 6

8 10 12

Page 98
UNIT 3-ARRAYS AND STRINGS
14 16 18

Program to implement Matrix multiplication

#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],b[3][3],c[3][3],i,j,k;
clrscr();
printf(Enter values of Matix A : \n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf(%d,&a[i][j]);
}
}
printf(Enter values of Matix B : \n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf(%d,&b[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j]=0;
for(k=0;k<3;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
printf(Multiplied Matrix\n);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{

Page 99
UNIT 3-ARRAYS AND STRINGS
printf(%d\t,c[i][j]);
}
printf(\n);
}
getch();
}
Output

Enter values of Matrix A :

Enter values of Matrix B :

Page 100
UNIT 3-ARRAYS AND STRINGS
Multiplied Matrix

1 1 1

1 1 1

1 1 1

Program to find transpose of Matrix

#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],i,j;
clrscr();
printf(Enter values in matrix : \n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf(%d,&a[i][j]);
}
}
printf(\nTranspose of given Matrix : \n);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf(%d\t,i,j,a[j][i]);
}
printf(\n);
}
getch();
}
Output

Enter values in matrix :

Page 101
UNIT 3-ARRAYS AND STRINGS
5

Transpose of given Matrix :

1 4 7

2 5 8

3 6 9

STRINGS

String in C language is an array of characters that is terminated by \0


(null character).

There are two ways to declare string in c language.

1. By char array
2. By string literal

Let's see the example of declaring string by char array in C language.

1. char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};

As you know well, array index starts from 0, so it will be represented as in


the figure given below.

While declaring string, size is not mandatory. So you can write the above
code as given below:

1. char ch[]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};

You can also define string by string literal in C language. For example:

Page 102
UNIT 3-ARRAYS AND STRINGS

1. char ch[]="javatpoint";

In such case, '\0' will be appended at the end of string by the compiler.

Difference between char array and string literal

The only difference is that string literal cannot be changed whereas string
declared by char array can be changed.

String Example in C

#include <stdio.h>
void main ()
{
char ch[11]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
char ch2[11]="javatpoint";

printf("Char Array Value is: %s\n", ch);


printf("String Literal Value is: %s\n", ch2);
}

Output:

Char Array Value is: javatpoint


String Literal Value is: javatpoint

C gets() and puts() functions

The gets() function reads string from user and puts() function prints the
string. Both functions are defined in <stdio.h> header file.

Example

#include<stdio.h>
#include<conio.h>
void main()
{
char name[50];
clrscr();
printf("Enter your name: ");
gets(name); //reads string from user
printf("Your name is: ");

Page 103
UNIT 3-ARRAYS AND STRINGS

puts(name); //displays string


getch();
}

Output:

Enter your name: Sonoo Jaiswal


Your name is: Sonoo Jaiswal

C String Functions

There are many important string functions defined in "string.h" library.

No. Function Description

1) strlen(string_name) returns the length of string name.

2) strcpy(destination, copies the contents of source string to


source) destination string.

3) strcat(first_string, concats or joins first string with second


second_string) string. The result of the string is stored in
first string.

4) strcmp(first_string, compares the first string with second


second_string) string. If both strings are same, it returns
0.

5) strrev(string) returns reverse string.

6) strlwr(string) returns string characters in lowercase.

7) strupr(string) returns string characters in uppercase.

C String Length: strlen() function

The strlen() function returns the length of the given string. It doesn't
count null character '\0'.

#include <stdio.h>
void main()

Page 104
UNIT 3-ARRAYS AND STRINGS

{
char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
printf("Length of string is: %d",strlen(ch));
}

Output:

Length of string is: 10

Copy String: strcpy()

The strcpy(destination, source) function copies the source string in


destination.

#include <stdio.h>
void main()
{
char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
char ch2[20];
strcpy(ch2,ch);
printf("Value of second string is: %s",ch2);
}

Output:

Value of second string is: javatpoint

String Concatenation: strcat()

The strcat(first_string, second_string) function concatenates two strings


and result is returned to first_string.

#include <stdio.h>
void main()
{
char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};
char ch2[10]={'c', '\0'};
strcat(ch,ch2);
printf("Value of first string is: %s",ch);
}

Output:

Page 105
UNIT 3-ARRAYS AND STRINGS
Value of first string is: helloc

Compare String: strcmp()

The strcmp(first_string, second_string) function compares two string and


returns 0 if both strings are equal.

Here, we are using gets() function which reads string from the console.

#include <stdio.h>
void main()
{
char str1[20],str2[20];
printf("Enter 1st string: ");
gets(str1);//reads string from console
printf("Enter 2nd string: ");
gets(str2);
if(strcmp(str1,str2)==0)
printf("Strings are equal");
else
printf("Strings are not equal");
}

Output:

Enter 1st string: hello


Enter 2nd string: hello
Strings are equal

Reverse String: strrev()

The strrev(string) function returns reverse of the given string. Let's see a
simple example of strrev() function.

#include<stdio.h>
#include<conio.h>
void main(){
char str[20];
clrscr();
printf("Enter string: ");

Page 106
UNIT 3-ARRAYS AND STRINGS

gets(str);//reads string from console


printf("String is: %s",str);
printf("\nReverse String is: %s",strrev(str));
getch(); }

Output:

Enter string: javatpoint


String is: javatpoint
Reverse String is: tnioptavaj

String Lowercase: strlwr()

The strlwr(string) function returns string characters in lowercase. Let's


see a simple example of strlwr() function.

#include<stdio.h>
#include<conio.h>
void main(){
char str[20];
clrscr();
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nLower String is: %s",strlwr(str));
getch();
}

Output:

Enter string: JAVATpoint


String is: JAVATpoint
Lower String is: javatpoint

String Uppercase: strupr()

The strupr(string) function returns string characters in uppercase. Let's


see a simple example of strupr() function.

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

Page 107
UNIT 3-ARRAYS AND STRINGS

char str[20];
clrscr();
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nUpper String is: %s",strupr(str));
getch();
}

Output:

Enter string: javatpoint


String is: javatpoint
Upper String is: JAVATPOINT

String strstr()

The strstr() function returns pointer to the first occurrence of the matched
string in the given string. It is used to return substring from first match
till the last character.

Syntax:

char *strstr(const char *string, const char *match)

String strstr() parameters

string: It represents the full string from where substring will be searched.

match: It represents the substring to be searched in the full string.

String strstr() example printf("\nSubstring is: %s",sub);

#include<stdio.h> getch();
#include<conio.h> }
#include<string.h>
void main(){ Output:
char str[100]="this is javatpoin
javatpoint with c and java
t with c and java";
char *sub;
clrscr();
sub=strstr(str,"java");

Page 108
UNIT-4 FUNCTIONS & STRUCTURES

UNIT-4-FUNCTIONS & STRUCTURES 10

Functions-

Function Prototypes-Declaring, Defining and Calling Functions-Call by value


and Call by Reference-Recursive Functions-Structures- Declaration and
Definition -Accessing Structure Members-Arrays of Structures-Unions-
Programs using Structures and Unions

FUNCTION

A function is a group of statements that together perform a task. Every C


program has at least one function, which is main(), and all the most trivial
programs can define additional functions.

You can divide up your code into separate functions. How you divide up
your code among different functions is up to you, but logically the division is
such that each function performs a specific task.

A function declaration tells the compiler about a function's name, return


type, and parameters. A function definition provides the actual body of the
function.

The C standard library provides numerous built-in functions that your


program can call. For example, strcat() to concatenate two
strings, memcpy() to copy one memory location to another location, and
many more functions.

A function definition in C programming consists of a function header and


a function body. Here are all the parts of a function

Return Type A function may return a value. The return_type is the data
type of the value the function returns. Some functions perform the desired
operations without returning a value. In this case, the return_type is the
keyword void.

Function Name This is the actual name of the function. The function name
and the parameter list together constitute the function signature.

Page 109
UNIT-4 FUNCTIONS & STRUCTURES

Parameters A parameter is like a placeholder. When a function is invoked,


you pass a value to the parameter. This value is referred to as actual parameter
or argument. The parameter list refers to the type, order, and number of the
parameters of a function. Parameters are optional; that is, a function may
contain no parameters.

Function Body The function body contains a collection of statements that


define what the function does.

EXAMPLE

#include <stdio.h>

int addNumbers(int a, int b); // function prototype

int main()
{
int n1,n2,sum;

printf("Enters two numbers: ");


scanf("%d %d",&n1,&n2);

sum = addNumbers(n1, n2); // function call

printf("sum = %d",sum);

return 0;
}

int addNumbers(int a,int b) // function definition


{
int result;
result = a+b;
return result; // return statement
}

Page 110
UNIT-4 FUNCTIONS & STRUCTURES

Function prototypes

Function with no arguments and no return value


Function with no arguments and a return value
Function with arguments and no return value
Function with arguments and a return value.

Function with no arguments and no return value

Example

#include <stdio.h>
void checkPrimeNumber();
int main()
{
checkPrimeNumber(); // no argument is passed to prime()
return 0;
}
// return type of the function is void becuase no value is returned from the
function
void checkPrimeNumber()
{
int n, i, flag=0;
printf("Enter a positive integer: ");
scanf("%d",&n);
for(i=2; i <= n/2; ++i)
{
if(n%i == 0)
{
flag = 1;
}
}
if (flag == 1)
printf("%d is not a prime number.", n);
else
printf("%d is a prime number.", n);
}

Page 111
UNIT-4 FUNCTIONS & STRUCTURES

The checkPrimeNumber() function takes input from the user, checks


whether it is a prime number or not and displays it on the screen.

The empty parentheses in checkPrimeNumber(); statement inside the


main() function indicates that no argument is passed to the function.

The return type of the function is void. Hence, no value is returned from the
function.

No arguments passed but a return value

Example

#include <stdio.h>
int getInteger();
int main()
{
int n, i, flag = 0;
// no argument is passed to the function
// the value returned from the function is assigned to n
n = getInteger();
for(i=2; i<=n/2; ++i)
{
if(n%i==0){
flag = 1;
break;
}
}
if (flag == 1)
printf("%d is not a prime number.", n);
else
printf("%d is a prime number.", n);
return 0;
}
// getInteger() function returns integer entered by the user
int getInteger()
{
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
return n;

Page 112
UNIT-4 FUNCTIONS & STRUCTURES

The empty parentheses in n = getInteger(); statement indicates that no


argument is passed to the function. And, the value returned from the
function is assigned to n.

Here, the getInteger() function takes input from the user and returns it.
The code to check whether a number is prime or not is inside the main()
function.

Argument passed but no return value

Example

#include <stdio.h>
void checkPrimeAndDisplay(int n);
int main()
{
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
// n is passed to the function
checkPrimeAndDisplay(n);
return 0;
}
// void indicates that no value is returned from the function
void checkPrimeAndDisplay(int n)
{
int i, flag = 0;
for(i=2; i <= n/2; ++i)
PROGRAMMING USING C (prepared by S.Aravindan AP/CSE) Page 15
{
if(n%i == 0){
flag = 1;
break;
}
}
if(flag == 1)
printf("%d is not a prime number.",n);
else
printf("%d is a prime number.", n);

Page 113
UNIT-4 FUNCTIONS & STRUCTURES

The integer value entered by the user is passed to checkPrimeAndDisplay()


function.

Here, the checkPrimeAndDisplay() function checks whether the argument


passed is a prime number or not and displays the appropriate message.

Argument passed and a return value

Example

#include <stdio.h>
int checkPrimeNumber(int n);
int main()
{
int n, flag;
printf("Enter a positive integer: ");
scanf("%d",&n);
// n is passed to the checkPrimeNumber() function
// the value returned from the function is assigned to flag variable
flag = checkPrimeNumber(n);
if(flag==1)
printf("%d is not a prime number",n);
else
printf("%d is a prime number",n);
return 0;
}
// integer is returned from the function
int checkPrimeNumber(int n)
{
/* Integer value is returned from function checkPrimeNumber() */
int i;
for(i=2; i <= n/2; ++i)
{
if(n%i == 0)
return 1;
}
return 0;
}

Page 114
UNIT-4 FUNCTIONS & STRUCTURES

The input from the user is passed to checkPrimeNumber() function.

The checkPrimeNumber() function checks whether the passed argument is


prime or not. If the passed argument is a prime number, the function
returns 0. If the passed argument is a non-prime number, the function
returns 1. The return value is assigned to flag variable.

Then, the appropriate message is displayed from the main() function.

FUNCTION CALLING TYPES

1. call by value
2. call by reference

CALL BY VALUE

The call by value method of passing arguments to a function copies the


actual value of an argument into the formal parameter of the function. In
this case, changes made to the parameter inside the function have no effect
on the argument.

By default, C programming uses call by value to pass arguments. In


general, it means the code within a function cannot alter the arguments
used to call the function. Consider the function swap() definition as
follows.

/* function definition to swap the values */

void swap(int x, int y) {

int temp;

temp = x; /* save the value of x */

x = y; /* put y into x */

y = temp; /* put temp into y */

Page 115
UNIT-4 FUNCTIONS & STRUCTURES

return;

Now, let us call the function swap() by passing actual values as in the
following example

#include <stdio.h>

/* function declaration */

void swap(int x, int y);

int main () {

/* local variable definition */

int a = 100;

int b = 200;

printf("Before swap, value of a : %d\n", a );

printf("Before swap, value of b : %d\n", b );

/* calling a function to swap the values */

swap(a, b);

printf("After swap, value of a : %d\n", a );

printf("After swap, value of b : %d\n", b );

return 0;

OUTPUT

Before swap, value of a :100

Page 116
UNIT-4 FUNCTIONS & STRUCTURES

Before swap, value of b :200

After swap, value of a :100

After swap, value of b :200

CALL BY REFERENCE

The call by reference method of passing arguments to a function copies the


address of an argument into the formal parameter. Inside the function, the
address is used to access the actual argument used in the call. It means the
changes made to the parameter affect the passed argument.

To pass a value by reference, argument pointers are passed to the functions


just like any other value. So accordingly you need to declare the function
parameters as pointer types as in the following function swap(), which
exchanges the values of the two integer variables pointed to, by their
arguments.

Example

/* function definition to swap the values */

void swap(int *x, int *y) {

int temp;

temp = *x; /* save the value at address x */

*x = *y; /* put y into x */

*y = temp; /* put temp into y */

return;

Page 117
UNIT-4 FUNCTIONS & STRUCTURES

Let us now call the function swap() by passing values by reference


as in the following example

#include <stdio.h>

/* function declaration */

void swap(int *x, int *y);

int main () {

/* local variable definition */

int a = 100;

int b = 200;

printf("Before swap, value of a : %d\n", a );

printf("Before swap, value of b : %d\n", b );

/* calling a function to swap the values.

* &a indicates pointer to a ie. address of variable a and

* &b indicates pointer to b ie. address of variable b.

*/

swap(&a, &b);

printf("After swap, value of a : %d\n", a );

printf("After swap, value of b : %d\n", b );

return 0;

Page 118
UNIT-4 FUNCTIONS & STRUCTURES

OUTPUT

Before swap, value of a :100

Before swap, value of b :200

After swap, value of a :200

After swap, value of b :100

RECURSION

A function that calls itself is known as a recursive function. And, this


technique is known as recursion.

How recursion works?


void recurse()

... .. ...

recurse();

... .. ...

int main()

... .. ...

recurse();

Page 119
UNIT-4 FUNCTIONS & STRUCTURES

... .. ...

Example: Sum of Natural Numbers Using Recursion

#include <stdio.h>

int sum(int n);

int main()

int number, result;

printf("Enter a positive integer: ");

Page 120
UNIT-4 FUNCTIONS & STRUCTURES

scanf("%d", &number);

result = sum(number);

printf("sum=%d", result);

int sum(int num)

if (num!=0)

return num + sum(num-1); // sum() function calls itself

else

return num;

Output

Enter a positive integer:


3
6

Initially, the sum() is called from the main() function with number passed
as an argument.

Suppose, the value of num is 3 initially. During next function call, 2 is


passed to the sum() function. This process continues until num is equal to
0.

When num is equal to 0, the if condition fails and the else part is executed
returning the sum of integers to the main() function.

Page 121
UNIT-4 FUNCTIONS & STRUCTURES

EXPLANATION

Page 122
UNIT-4 FUNCTIONS & STRUCTURES

Factorial program using recursion

#include<stdio.h>

long factorial(int);

int main()
{
int n;
long f;

printf("Enter an integer to find factorial\n");


scanf("%d", &n);

if (n < 0)
printf("Negative integers are not allowed.\n");
else
{
f = factorial(n);
printf("%d! = %ld\n", n, f);
}
return 0;
}

long factorial(int n)
{
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}

Page 123
UNIT-4 FUNCTIONS & STRUCTURES

STRUCTURES

Arrays allow to define 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 to combine 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

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

Syntax

struct [structure tag] {

member definition;

member definition;

...

member definition;

} [one or more structure variables];

Page 124
UNIT-4 FUNCTIONS & STRUCTURES

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

int book_id;

} book;

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 struct to define variables of structure type. The following
example shows how to use a structure in a program

Example

#include <stdio.h>

#include <string.h>

struct Books {

char title[50];

char author[50];

Page 125
UNIT-4 FUNCTIONS & STRUCTURES

char subject[100];

int book_id;

};

int main( ) {

struct Books Book1; /* Declare Book1 of type Book */

struct Books Book2; /* 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);

Page 126
UNIT-4 FUNCTIONS & STRUCTURES

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

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

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.

Page 127
UNIT-4 FUNCTIONS & STRUCTURES

#include <stdio.h>

#include <string.h>

struct Books {

char title[50];

char author[50];

char subject[100];

int book_id;

};

/* function declaration */

void printBook( struct Books book );

int main( ) {

struct Books Book1; /* Declare Book1 of type Book */

struct Books Book2; /* 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");

Page 128
UNIT-4 FUNCTIONS & STRUCTURES

strcpy( Book2.author, "Zara Ali");

strcpy( Book2.subject, "Telecom Billing Tutorial");

Book2.book_id = 6495700;

/* print Book1 info */

printBook( Book1 );

/* Print Book2 info */

printBook( Book2 );

return 0;

void printBook( struct Books book ) {

printf( "Book title : %s\n", book.title);

printf( "Book author : %s\n", book.author);

printf( "Book subject : %s\n", book.subject);

printf( "Book book_id : %d\n", book.book_id);

Output

Book title : C Programming

Book author : Nuha Ali

Book subject : C Programming Tutorial

Book book_id : 6495407

Page 129
UNIT-4 FUNCTIONS & STRUCTURES

Book title : Telecom Billing

Book author : Zara Ali

Book subject : Telecom Billing Tutorial

Book book_id : 6495700

ARRAY OF STRUCTURES

There can be array of structures in C programming to store many


information of different data types. The array of structures is also known as
collection of structures.

Let's see an example of structure with array that stores information


of 5 students and prints it.

#include<stdio.h>

#include<conio.h>

#include<string.h>

struct student{

int rollno;

char name[10];

};

void main(){

int i;

struct student st[5];

clrscr();

Page 130
UNIT-4 FUNCTIONS & STRUCTURES

printf("Enter Records of 5 students");

for(i=0;i<5;i++){

printf("\nEnter Rollno:");

scanf("%d",&st[i].rollno);

printf("\nEnter Name:");

scanf("%s",&st[i].name);

printf("\nStudent Information List:");

for(i=0;i<5;i++){

printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);

getch();

OUTPUT:

Enter Records of 5 students

Enter Rollno:1

Enter Name:Sonoo

Enter Rollno:2

Enter Name:Ratan

Enter Rollno:3

Page 131
UNIT-4 FUNCTIONS & STRUCTURES

Enter Name:Vimal

Enter Rollno:4

Enter Name:James

Enter Rollno:5

Enter Name:Sarfraz

Student Information List:

Rollno:1, Name:Sonoo

Rollno:2, Name:Ratan

Rollno:3, Name:Vimal

Rollno:4, Name:James

Rollno:5, Name:Sarfraz

Page 132
UNIT-4 FUNCTIONS & STRUCTURES

UNION

A union is a special data type available in C that allows to store 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.

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

SYNTAX

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 {

Page 133
UNIT-4 FUNCTIONS & STRUCTURES

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 {

int i;

float f;

char str[20];

};

int main( ) {

union Data data;

printf( "Memory size occupied by data : %d\n", sizeof(data));

Page 134
UNIT-4 FUNCTIONS & STRUCTURES

return 0;

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

Page 135
UNIT-4 FUNCTIONS & STRUCTURES

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

Page 136
UNIT - 5- POINTERS & FILES
UNIT - 5- POINTERS & FILES 8

Pointers-Dynamic Memory Allocation-Arithmetic Operations using Pointers, Files


File Manipulation-I/O Operations, Preprocessor Directives, Storage Classes

POINTERS

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 address. The general form of a pointer
variable declaration is

datatype *var-name;

Here, datatype is the pointer's base type; it must be a valid C data type and var-
name is the name of the pointer variable. The asterisk * used to declare a pointer is
the same asterisk used for multiplication. However, in this statement the asterisk is
being used to designate a variable as a pointer. Take a look at some of the valid
pointer declarations

int *ip; /* pointer to an integer */

double *dp; /* pointer to a double */

float *fp; /* pointer to a float */

char *ch /* pointer to a character */

The actual data type of the value of all pointers, whether integer, float, character,
or otherwise, is the same, a long hexadecimal number that represents a memory
address. The only difference between pointers of different data types is the data
type of the variable or constant that the pointer points to.

How to Use Pointers?

There are a few important operations, which we will do with the help of pointers
very frequently. (a) We define a pointer variable, (b) assign the address of a
variable to a pointer and (c) finally access the value at the address available in the
pointer variable. This is done by using unary operator * that returns the value of
the variable located at the address specified by its operand. The following
example makes use of these operations

Page 137
UNIT - 5- POINTERS & FILES
#include <stdio.h>

int main () {

int var = 20; /* actual variable declaration */

int *ip; /* pointer variable declaration */

ip = &var; /* store address of var in pointer variable*/

printf("Address of var variable: %x\n", &var );

/* address stored in pointer variable */

printf("Address stored in ip variable: %x\n", ip );

/* access the value using the pointer */

printf("Value of *ip variable: %d\n", *ip );

return 0;

OUTPUT

Address of var variable: bffd8b3c

Address stored in ip variable: bffd8b3c

Value of *ip variable: 20

NULL Pointers

It is always a good practice to assign a NULL value to a pointer variable in case you
do not have an exact address to be assigned. This is done at the time of variable
declaration. A pointer that is assigned NULL is called a null pointer.

The NULL pointer is a constant with a value of zero defined in several standard
libraries. Consider the following program

Page 138
UNIT - 5- POINTERS & FILES
#include <stdio.h>

int main ()

int *ptr = NULL;

printf("The value of ptr is : %x\n", ptr );

return 0;

OUTPUT

The value of ptr is 0

ARITHMETIC OPERATIONS USING POINTERS

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 -

To understand pointer arithmetic, let us consider that ptr is an integer pointer


which points to the address 1000. Assuming 32-bit integers, let us perform the
following arithmetic operation on the pointer

ptr++

After the above operation, the ptr will point to the location 1004 because each time
ptr is incremented, it will point to the next integer location which is 4 bytes next to
the current location. This operation will move the pointer to the next memory
location without impacting the actual value at the memory location. If ptr points to
a character whose address is 1000, then the above operation will point to the
location 1001 because the next character will be available at 1001.

Incrementing a Pointer

We prefer using a pointer in our program instead of an array because the variable
pointer can be incremented, unlike the array name which cannot be incremented
because it is a constant pointer. The following program increments the variable
pointer to access each succeeding element of the array

Page 139
UNIT - 5- POINTERS & FILES

#include <stdio.h>

const int MAX = 3;

int main () {

int var[] = {10, 100, 200};

int i, *ptr;

/* let us have array address in pointer */

ptr = var;

for ( i = 0; i < MAX; i++) {

printf("Address of var[%d] = %x\n", i, ptr );

printf("Value of var[%d] = %d\n", i, *ptr );

/* move to the next location */

ptr++;

return 0;

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

Address of var[0] = bf882b30

Value of var[0] = 10

Address of var[1] = bf882b34

Value of var[1] = 100

Address of var[2] = bf882b38

Value of var[2] = 200

Page 140
UNIT - 5- POINTERS & FILES

Decrementing a Pointer

The same considerations apply to decrementing a pointer, which decreases its value
by the number of bytes of its data type as shown below

#include <stdio.h>

const int MAX = 3;

int main () {

int var[] = {10, 100, 200};

int i, *ptr;

/* let us have array address in pointer */

ptr = &var[MAX-1];

for ( i = MAX; i > 0; i--) {

printf("Address of var[%d] = %x\n", i-1, ptr );

printf("Value of var[%d] = %d\n", i-1, *ptr );

/* move to the previous location */

ptr--;

return 0;

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

Address of var[2] = bfedbcd8

Value of var[2] = 200

Address of var[1] = bfedbcd4

Value of var[1] = 100

Page 141
UNIT - 5- POINTERS & FILES
Address of var[0] = bfedbcd0

Value of var[0] = 10

Array of pointers

An array of pointers is an indexed set of variables in which the variables are


pointers (a reference to a location in memory). Pointers are an important tool in
computer science for creating, using, and destroying all types of data structures

Before we understand the concept of arrays of pointers, let us consider the following
example, which uses an array of 3 integers

#include <stdio.h>

const int MAX = 3;

int main () {

int var[] = {10, 100, 200};

int i;

for (i = 0; i < MAX; i++) {

printf("Value of var[%d] = %d\n", i, var[i] );

return 0;

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

Value of var[0] = 10

Value of var[1] = 100

Value of var[2] = 200

There may be a situation when we want to maintain an array, which can store
pointers to an int or char or any other data type available. Following is the
declaration of an array of pointers to an integer

int *ptr[MAX];

Page 142
UNIT - 5- POINTERS & FILES
It declares ptr as an array of MAX integer pointers. Thus, each element in ptr, holds
a pointer to an int value. The following example uses three integers, which are
stored in an array of pointers, as follows

#include <stdio.h>

const int MAX = 3;

int main () {

int var[] = {10, 100, 200};

int i, *ptr[MAX];

for ( i = 0; i < MAX; i++) {

ptr[i] = &var[i]; /* assign the address of integer. */

for ( i = 0; i < MAX; i++) {

printf("Value of var[%d] = %d\n", i, *ptr[i] );

return 0;

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

Value of var[0] = 10

Value of var[1] = 100

Value of var[2] = 200

You can also use an array of pointers to character to store a list of strings as
follows

Page 143
UNIT - 5- POINTERS & FILES
#include <stdio.h>

const int MAX = 4;

int main () {

char *names[] = {

"Zara Ali",

"Hina Ali",

"Nuha Ali",

"Sara Ali"

};

int i = 0;

for ( i = 0; i < MAX; i++) {

printf("Value of names[%d] = %s\n", i, names[i] );

return 0;

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

Value of names[0] = Zara Ali

Value of names[1] = Hina Ali

Value of names[2] = Nuha Ali

Value of names[3] = Sara Ali

Page 144
UNIT - 5- POINTERS & FILES
Passing pointers to functions

C programming allows passing a pointer to a function. To do so, simply declare the


function parameter as a pointer type.

Following is a simple example where we pass an unsigned long pointer to a function


and change the value inside the function which reflects back in the calling function

#include <stdio.h>

#include <time.h>

void getSeconds(unsigned long *par);

int main () {

unsigned long sec;

getSeconds( &sec );

/* print the actual value */

printf("Number of seconds: %ld\n", sec );

return 0;

void getSeconds(unsigned long *par) {

/* get the current number of seconds */

*par = time( NULL );

return;

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

Number of seconds :1294450468

Page 145
UNIT - 5- POINTERS & FILES
The function, which can accept a pointer, can also accept an array as shown in the
following example

#include <stdio.h>

/* function declaration */

double getAverage(int *arr, int size);

int main () {

/* an int array with 5 elements */

int balance[5] = {1000, 2, 3, 17, 50};

double avg;

/* pass pointer to the array as an argument */

avg = getAverage( balance, 5 ) ;

/* output the returned value */

printf("Average value is: %f\n", avg );

return 0;

double getAverage(int *arr, int size) {

int i, sum = 0;

double avg;

for (i = 0; i < size; ++i) {

sum += arr[i];

avg = (double)sum / size;

return avg;

Page 146
UNIT - 5- POINTERS & FILES
When the above code is compiled together and executed, it produces the following
result

Average value is: 214.40000

Page 147
UNIT - 5- POINTERS & FILES

DYNAMIC MEMORY ALLOCATION

The concept of dynamic memory allocation in c language enables the C programmer


to allocate memory at runtime. Dynamic memory allocation in c language is
possible by 4 functions of stdlib.h header file.

1. malloc()
2. calloc()
3. realloc()
4. free()

Before learning above functions, let's understand the difference between static
memory allocation and dynamic memory allocation.

static memory allocation dynamic memory allocation

memory is allocated at compile time. memory is allocated at run time.

memory can't be increased while memory can be increased while


executing program. executing program.

used in array. used in linked list.

malloc() allocates single block of requested memory.

calloc() allocates multiple block of requested memory.

realloc() reallocates the memory occupied by malloc() or calloc() functions.

free() frees the dynamically allocated memory.

Page 148
UNIT - 5- POINTERS & FILES
malloc() function

The malloc() function allocates single block of requested memory.

It doesn't initialize memory at execution time, so it has garbage value


initially.

It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

ptr=(cast-type*)malloc(byte-size);

Example

#include <stdio.h>
#include <stdlib.h>
void main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
}

Output
Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

Page 149
UNIT - 5- POINTERS & FILES
calloc() function
The calloc() function allocates multiple block of requested memory.

It initially initialize all bytes to zero.

It returns NULL if memory is not sufficient.

The syntax of calloc() function is given below:

ptr=(cast-type*)calloc(number, byte-size)

Example

#include <stdio.h>
#include <stdlib.h>
void main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
}

Output:
Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

Page 150
UNIT - 5- POINTERS & FILES
realloc() function
If memory is not sufficient for malloc() or calloc(), you can reallocate the memory
by realloc() function. In short, it changes the memory size.

Let's see the syntax of realloc() function.

ptr=realloc(ptr, new-size)

free() function

The memory occupied by malloc() or calloc() functions must be released by calling


free() function. Otherwise, it will consume memory until program exit.

free(ptr)

Page 151
UNIT - 5- POINTERS & FILES
FILE HANDLING IN C

A file represents a sequence of bytes on the disk where a group of related data is
stored. File is created for permanent storage of data. It is a ready made structure.
In C language, we use a structure pointer of file type to declare a file.

FILE *fp;

Function Description

fopen() create a new file or open a existing file

fclose() closes a file

getc() reads a character from a file

putc() writes a character to a file

fscanf() reads a set of data from a file

fprintf() writes a set of data to a file

getw() reads a integer from a file

putw() writes a integer to a file

fseek() set the position to desire point

ftell() gives current position in the file

rewind() set the position to the begining point

Page 152
UNIT - 5- POINTERS & FILES
Opening a File or Creating a File

The fopen() function is used to create a new file or to open an existing file.

General Syntax :

*fp = FILE *fopen(const char *filename, const char *mode);

Here filename is the name of the file to be opened and mode specifies the purpose
of opening the file. Mode can be of following types,
*fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or
created) file.

mode Description

r opens a text file in reading mode

w opens or create a text file in writing mode.

a opens a text file in append mode

r+ opens a text file in both reading and writing mode

w+ opens a text file in both reading and writing mode

a+ opens a text file in both reading and writing mode

Closing a File

The fclose() function is used to close an already opened file.

General Syntax :

int fclose( FILE *fp );

Page 153
UNIT - 5- POINTERS & FILES
Here fclose() function closes the file and returns zero on success, or EOF if there is
an error in closing the file. This EOF is a constant defined in the header file stdio.h.

Input/Output operation on File

Using getc and putc

getc is one of the character input functions. getc reads the next character from a
file, it takes a file pointer to the file. It is the simplest function to read a file

putc is the function in stdio.h. It is simplest way to write the file once it is open

Example

#include<stdio.h>
#include<conio.h>
main()
{
FILE *fp;
char ch;
fp = fopen("one.txt", "w");
printf("Enter data");
while( (ch = getchar()) != EOF) {
putc(ch,fp);
}
fclose(fp);
fp = fopen("one.txt", "r");

while( (ch = getc(fp)! = EOF)


printf("%c",ch);

fclose(fp);
}

Reading and Writing from File using fprintf() and fscanf()

The fprintf() function is used to write set of characters into file. It sends formatted
output to a stream

fscanf reads from a file pointed by the FILE pointer (ptr), instead of reading from
the input stream.

Page 154
UNIT - 5- POINTERS & FILES
Example

#include<stdio.h>
#include<conio.h>
struct emp
{
char name[10];
int age;
};

void main()
{
struct emp e;
FILE *p,*q;
p = fopen("one.txt", "a");
q = fopen("one.txt", "r");
printf("Enter Name and Age");
scanf("%s %d", e.name, &e.age);
fprintf(p,"%s %d", e.name, e.age);
fclose(p);
do
{
fscanf(q,"%s %d", e.name, e.age);
printf("%s %d", e.name, e.age);
}
while( !feof(q) );
getch();
}

In this program, we have create two FILE pointers and both are refering to the
same file but in different modes. fprintf() function directly writes into the file, while
fscanf() reads from the file, which can then be printed on console usinf standard
printf() function.

Difference between Append and Write Mode

Write (w) mode and Append (a) mode, while opening a file are almost the same.
Both are used to write in a file. In both the modes, new file is created if it doesn't
exists already.

The only difference they have is, when you open a file in the write mode, the file is
reset, resulting in deletion of any data already present in the file. While in append
mode this will not happen. Append mode is used to append or add data to the
existing data of file(if any). Hence, when you open a file in Append(a) mode, the
cursor is positioned at the end of the present data in the file

Page 155
UNIT - 5- POINTERS & FILES
PREPROCESSOR DIRECTIVES

The C Preprocessor is not a part of the compiler, but is a separate step in the
compilation process. In simple terms, a C Preprocessor is just a text substitution
tool and it instructs the compiler to do required pre-processing before the actual
compilation. We'll refer to the C Preprocessor as CPP.

All preprocessor commands begin with a hash symbol (#). It must be the first
nonblank character, and for readability, a preprocessor directive should begin in the
first column. The following section lists down all the important preprocessor
directives

Directive Description

#define Substitutes a preprocessor macro.

#include Inserts a particular header from another file.

#undef Undefines a preprocessor macro.

#ifdef Returns true if this macro is defined.

#ifndef Returns true if this macro is not defined.

#if Tests if a compile time condition is true.

#else The alternative for #if.

#elif #else and #if in one statement.

#endif Ends preprocessor conditional.

#error Prints error message on stderr.

#pragma Issues special commands to the compiler, using a


standardized method.

Page 156
UNIT - 5- POINTERS & FILES
Example 1:-

#include <stdio.h>
#define PI 3.1415

int main()
{
float radius, area;
printf("Enter the radius: ");
scanf("%d", &radius);
// Notice, the use of PI
area = PI*radius*radius;
printf("Area=%.2f",area);
return 0;
}

Example 2:-

#include <stdio.h>
#define PI 3.1415
#define circleArea(r) (PI*r*r)

int main()
{
int radius;
float area;

printf("Enter the radius: ");


scanf("%d", &radius);
area = circleArea(radius);
printf("Area = %.2f", area);

return 0;
}

Page 157
UNIT - 5- POINTERS & FILES
Macros

A macro is a name given to a block of C statements as a pre-processor directive.


Being a pre-processor, the block of code is communicated to the compiler before
entering into the actual coding (main () function). A macro is defined with the
preprocessor directive, #define.

There are some predefined macros which are readily for use in C programming.

Predefined macro Value

__DATE__ String containing the current date

__FILE__ String containing the file name

__LINE__ Integer representing the current line number

__STDC__ If follows ANSI standard C, then value is a nonzero integer

__TIME__ String containing the current date.

Example 3:-

#include <stdio.h>
int main()
{
printf("Current time: %s",__TIME__); //calculate the current time
}

Page 158
UNIT - 5- POINTERS & FILES
STORAGE CLASSES
Storage classes

In C language, each variable has a storage class which decides the


following things:

scope i.e in which all functions, the value of the variable would be available.
default initial value i.e if we do not explicitly initialize that variable, what will
be its default initial value.
lifetime of that variable i.e for how long will that variable exist.

The following storage classes are most oftenly used in C programming,

Automatic variables
External variables
Static variables
Register variables

Automatic variables

Scope: Local to the method block in which the variable is defined.

Default Initial Value: Any random value i.e garbage value.

Lifetime: Till the end of method block where the variable is defined.

A variable declared inside a function without any storage class specification, is by


default an automatic variable. They are created when a function is called and are
destroyed automatically when the function exits. Automatic variables can also be
called local variables because they are local to a function. By default they are
assigned garbage value by the compiler.

void main()
{
int detail;
or
auto int detail; //Both are same
}

Page 159
UNIT - 5- POINTERS & FILES
External or Global variable

Scope: Global i.e everywhere in the program.


Default initial value: 0(zero).
Lifetime: Till the whole program doesn't finish its execution.
A variable that is declared outside any function is a Global Variable. Global variables
remain available throughout the entire program.By default, initial value of the
Global variable is 0(zero). One important thing to remember about global variable
is that their values can be changed by any function in the program.
#include
int number; //global variable
void main()
{
number=10;
printf("I am in function main. My value is %d\n",number);
fun1(); //function calling, discussed in next topic
fun2(); //function calling, discussed in next topic
}
fun1()
{
number=20;
printf("I am in function fun1. My value is %d",number);
}
fun2()
{
printf("\nI am in function fun2. My value is %d",number);
}

Output:

I am in function main. My value is 10


I am in function fun1. My value is 20
I am in function fun2. My value is 20

Here the global variable number is available to all three functions and thus, if one
function changes the value of the variable, it gets changed in every function.

Note: Declaring storage class of all the variables in the program as global or
external can waste a lot of memory space because these variables has a lifetime till
the end of the whole program.Thus, variables, which are not needed till the end of
the program, still occupies the memory and thus , memory is wasted

Page 160
UNIT - 5- POINTERS & FILES
extern keyword

The extern keyword is used before a variable to inform the compiler that this
variable is declared somewhere else. The extern declaration does not allocate
storage for variables.

Problem when extern is not used


main()
{
a = 10; //Error:cannot find variable a
printf("%d",a);
}
int a;

Example Using extern in same file

main()
{
extern int a; //Tells compiler that it is defined somewhere else
a = 10;
printf("%d",a);
}

int x; //Global variable x

Page 161
UNIT - 5- POINTERS & FILES
Static variables

Scope: Local to the block in which the variable is defined

Default initial value: 0(Zero).

Lifetime: Till the whole program doesn't finish its execution.

A static variable tells the compiler to persist the variable until the end of program.
Instead of creating and destroying a variable every time when it comes into and
goes out of scope, static is initialized only once and remains into existence till the
end of program. A static variable can either be internal or external depending upon
the place of declaraction. Scope of internal static variable remains inside the
function in which it is defined. External static variables remain restricted to scope of
file in each they are declared.

They are assigned 0 (zero) as default value by the compiler.

void test(); //Function declaration (discussed in next topic)

main()
{
test();
test();
test();
}
void test()
{
static int a = 0; //Static variable
a = a+1;
printf("%d\t",a);
}

output :
1 2 3

Register variable
Scope: Local to the function in which it is declared.

Default initial value: Any random value i.e garbage value

Lifetime: Till the end of method block, where the variable is defined, doesn't finish
its execution.

Register variable inform the compiler to store the variable in CPU register instead of
memory. Register variable has faster access than normal variable. Frequently used

Page 162
UNIT - 5- POINTERS & FILES
variables are kept in register. Only few variables can be placed inside register. An
application of register storage class can be in using loops, where the variable gets
used a number of times in the program.

NOTE : We can never get the address of such variables.

syntax
register int number;

Page 163