302
Panimalar Institute of Technology FOC Semester 1 1 PANIMALAR INSTITUTE OF TECHNOLOGY (JAISAKTHI EDUCATIONAL TRUST) CHENNAI 600 123 DEPARTMENT OF CSE / IT GE2112 - FUNDAMENTALS OF COMPUTING AND PROGRAMMING I YEAR I SEMESTER (Common to all the Branches) LECTURE NOTES UNIT - I

LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Embed Size (px)

Citation preview

Page 1: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

1

PANIMALAR INSTITUTE OF TECHNOLOGY

(JAISAKTHI EDUCATIONAL TRUST)

CHENNAI 600 123

DEPARTMENT OF CSE / IT

GE2112 - FUNDAMENTALS OF COMPUTING AND PROGRAMMING

I YEAR – I SEMESTER

(Common to all the Branches)

LECTURE NOTES

UNIT - I

Page 2: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

2

Unit - I

Introduction to Computers

Syllabus:-

Generations and Classification of Computers – Basic Computer organization –

Number Systems – Binary – Decimal – Conversion – Problems – need for

logical analysis and thinking – Algorithm – Pseudo code – Flowchart.

Introduction

- Commonly Operated Machine Particularly Used for Technical and Educational Research - COMPUTER

- In the beginning of the civilization, people used fingers and pebbles for

computing purposes. In fact, the word digitus in Latin actually means finger and calculus means pebble.

- The term computer is derived from the word compute, which means to calculate.

- Computer is one of the major components of an information technology network and gaining increasing popularity.

Computer – Definitions (Give one definition)

- A computer is an electronic machine, devised for performing calculations and controlling operations that can be expressed either in logical or numerical terms.

- A computer is an electronic device that performs diverse operations with the help of instructions to process the information in order to achieve desired results.

- The computer is an electronic device designed in such a way, it automatically accepts and stores input data, process them and produce results under the direction of a detailed step by step program.

- The computer is an electronic device where we can store large amount of information that can be retrieved in any desired manner or in any form, processed in required form and can be utilized to carryout complicated

Page 3: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

3

mathematical and logical operations with speed and accuracy.

Data & Information

The computer may be defined as an electronic device that operates upon information

and data.

Data:

. Data is the raw material of information processing.

Information:

The processed data is called the information. It is a collection of data grouped together to give some meaning.

Basic Operations of Computer

The computers have the following five basic operations to carry out any task.

Input – It is the process of capturing or acquiring the information, or it is the raw data or information by using this we can do any process.

Process – It is the transformation process to convert the input in to output.

Output – It is the result, which comes from the transformation process or it is the outcome of the process. Storing – It is the process of saving data or information. Controlling – It is the process of directing and sequencing all the operations.

Page 4: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

4

Compare Computer with Human Being

S.No. Characteristics Computer Human Being

1. Speed Fast and excellent Very Slow

2. Accuracy Makes no error Possibility of error

3. Performance Very good Poor

4. Instructions Follow perfect Chances for imperfect

5. Remember Accurate and exact Inaccurate

6. Different situations Makes good Difficult

7. Trial and errors Makes good Difficult

8. Diligence High Low

Compare Computer with Calculator

The computer is not a calculator, but it can also do more operations. It has been developed based on some features of calculator.

Page 5: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

5

S.No. Characteristics Calculator Computer

1. Speed Fast Much faster

2. Performance Simple calculations and Complex problem

numeric processing solving and non-

numeric processing

3. Memory Less internal memory Large internal memory

and no permanent and large permanent

storage storage available

4. Machine Electronic device Electronic device

5. Operation Arithmetic Arithmetic and logical

Applications of Computers

Computer is essential in today‟s life comparing with human activities in various fields

like Industry, Government, Education, Medicine, Scientific Research, Arts, Music, and Painting

etc.

Some of the areas where computers are being used are:

Business

Industry

Home

Play

Education

Training

Entertainment

Arts

Science and Engineering

Medicine and healthcare.

Characteristics of Computers

Some of the characteristics of computers are listed below:

Speed – computers works much faster than human beings and calculators.

Page 6: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

6

Accuracy – Computers are perfect, accurate and precise. Automatic – Computer works automatically, once programs are stored data given to it. Endurance / Diligence – Computers can go on working continuously without any

tiredness. Versatility – Computers can be put to various jobs and has applications in various

fields. Reliability – Computers are more reliable than human beings. Storage Capacity – Computers can store large amounts of data and recall at later time

easily. Reduction in Cost – Now-a-days computer cost has become less. Resource Sharing – Data and information can be shared among groups of computers. Artificial Intelligence – Computers cannot think, it just works as per human

instructions.

Computer Generations

Introduction

o In computer terminology, the word generation is described as a stage of technological development or innovation.

o A major technological development that fundamentally changed the way computers operate, resulting in increasingly smaller, cheaper, more powerful and more efficient and reliable devices, characterizes each generation of computer.

o The computer generation means step-by-step growth in the technology. It is

often used in relation to the hardware of computer.

First generation Computers (1940 – 1956): Vacuum Tubes

Explanation

- First generation computers used vacuum tubes circuitry as such these were quite large.

- They had a poor reliability and had only a limited functional capability.

Page 7: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

7

- A vacuum tube was a fragile glass device that used filaments as a source of electrons and control and amplify electronic signals.

- First generation computers relied on binary-coded language to perform operations and were able to solve only one problem at a time.

- Input was based on punched cards and paper tape and output was in the form of printouts.

Sample Diagram – Vacuum Tubes

Advantages Vacuum tubes were the only electronic components available at that time.

These computers were the fastest calculating device of their time.

These computers could perform computations in milli seconds.

Disadvantages Very big in size

Occupies large space

High heat production

High power consumption

High cost

No reliability

Non portable

Need constant maintenance

Limited commercial use

Egs: ENIAC,EDSAC,UNIVAC

Page 8: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

8

Second generation Computers (1956 – 1963): Transistors

Explanation

Second generation computers used transistors, which were superior to vacuum

tubes

Transistor was highly reliable compared to tubes and it occupies less space and requires less power.

The storage capacity of the second generation computers was better than the first

generation.

They used Assembly level programming language and had a better processing speed than the first generation.

Commercial applications rapidly developed during this period and more than 80% of these computers were used in business and industries in the applications like payroll, inventory control, marketing etc.

Sample Diagram – Transistors

Advantages Small in size

Better reliability

Computational time is micro seconds

Less heat generated

Better speed and reliability

Disadvantages Frequent maintenance required

Need air-conditioning

Manual assembly of individual components into a functioning unit was required.

High cost

Page 9: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

9

Commercial production was difficult.

Egs: PDP-8,IBM-1620

Third generation Computers (1964 – 1975): Integrated Circuits

Explanation

The development of the Integrated Circuit (IC) was the foundation of the third generation computers.

An IC consist of a single chip (made of silicon) with many components such as transistors and resistors fabricated on it.

IC replaced several individually wired transistors. This development made computers smaller in size, reliable, and efficient.

Another concept developed during this period was an operating system and high

level programming languages are used.

Sample Diagram – Integrated Circuits (ICs)

Advantages Small in size

More reliability

Less heat generated

Computational time is Nano seconds

Less hardware failure

Low maintenance cost

Page 10: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

10

Easily portable

General purpose computers

Less power required

Commercial production was easier and cheaper

Disadvantages Need air-conditioning

Highly sophisticated technology required for the manufacturer of IC chips.

Egs: IBM-360 series, IBM-370/168.

Fourth generation Computers (1975 – 1989): Microprocessors

Explanation

The technology of this generation was still based on the integrated circuit, these have been made readily available to us because of the development of the microprocessor (circuit containing millions of transistors).

It led to an era of Large Scale Integration (LSI) and Very Large Scale Integration (VLSI) technology.

The fourth generation computers became more powerful, compact, reliable and affordable. As a result, it gave rise to the personal computer (PC) revolution.

Another significant development of this period was that these computers could be linked together to form networks, which eventually led to the development of the internet.

The fourth generation also saw simplification of the language. This made

managing of data much simpler and writing instructions made simple by using a language 4th Generation Languages (4GL), which were easy to learn and understand.

Sample Diagram – Microprocessors

Page 11: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

11

Advantages They are much more smaller in size

Very cheap as compared to previous generation computers

Consumes less power

Mainframes and super computers fall in this generation

Have more reliability

Less hardware failures

They had large and faster primary and secondary memory

Disadvantages Highly sophisticated technology required for the manufacture of VLSI chips.

Egs: INTEL-400L, APPLE series-I AND II, IBM compatible.

Fifth generation Computers (Present and Beyond): Artificial Intelligence

Explanation

The process of developing fifth generation computers is still in the development stage. However, the expert system concept is already in use.

Computers are unable to act or think on their own. Now human beings are leading towards a stage where an artificial intelligent machine could be developed which will even be in a position to think and decide.

Recent researches are aimed at designing the logic for the thinking computers for building expert systems and knowledge based systems.

Sample Diagram – Artificial Intelligence

Page 12: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

12

Advantages Super computers and portable PCs falls under this generation

It consumes less power than its predecessors

More user friendly

Supports wide operating system environments

Supports newer and powerful applications

Having much faster and large primary storage capacity

The price range are affordable

Supports parallel processing

Summary table of all 5 generations of computers

S.No. Parameters First Second Third Fourth Fifth

Generation Generation Generation Generation

Generation

1. Year 1950 1960 1965 1975 1980

2. Electronic Vacuum

Transistors Integrated

Microprocessors Artificial

component tubes circuits intelligence

Operating

Highly

3. No OS used No OS used OS used Improved OS sophisticated

system

OS

Languages

Machine Assembly High Level

Artificial

4. (Binary) Language, 4GL

used Language Intelligence

language Mnemonics

10,000 to Upto 64,000

Upto 4 Semi conductor

5. Memory 20, 000 million CMOS

characters memory

characters

characters

6. Operating

Milli seconds Micro

Nano seconds 1 to 10 Nano 1 to 100 Nano

speed seconds

seconds

seconds

7. Quantity in

1,000 5,000 35,000 2,00,000

More than

the world for

5,00,000

Page 13: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

13

Classification of computers: Introduction

These days, computers are available in many sizes and types. Computers also differ based on their data processing abilities. It can be classified into the following based on

1. Hardware 2. Utility 3. size and capacity

Mode of use

I. Classification based on Hardware Design 1. Analog computers 2. Digital computers 3. Hybrid computers.

1.Analog Computers Explanation

- Analog computer operates by measuring instead of counting. The input data is a continuously changing electrical or non-electrical information.

- Computations are carried out with physical quantities such as voltage,

length, current, temperature etc. - The devices measuring such quantities are called analog devices.

Sample Diagram

Page 14: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

14

Characteristics

It works by measuring It functions on continuously varying quantity. The output is usually represented in the form of graphs. It has limited memory space.

Speed is very slow. These computers are not suitable for business and industry.

Uses

The advantage of analog computer is that all calculation takes place in parallel and hence it is very fast.

It is used for engineering and scientific applications, but their accuracy is

poor as compared to digital computer.

2. Digital Computers Explanation

In digital computer, both numeric and non-numeric information‟s are represented as strings of digits.

The input data is discrete in nature. It is represented by binary notation in

the form of 0‟s and 1‟s.

Digital computers are much faster than analog computers and are more accurate.

Sample Diagram

Page 15: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

15

Characteristics

It operates by counting It functions on discrete numbers The calculations are converted into binary numbers Its accuracy is good It has large memory space It is versatile in nature Its processing speed is high.

Uses

Digital computers are largely used for business and scientific applications.

3.Hybrid Computers Explanation

In hybrid computer, an attempt is made to combine the qualities of both analog and digital computers.

In hybrid computer, the measuring functions are performed by the

analog way while control and logic functions are digital in nature.

Sample Diagram

Page 16: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

16

II. Classification based on Utility

1. General Purpose Computers.

2. Special purpose computers.

1.General Purpose Computers Explanation

These are designed and constructed to cater almost all the needs of the society. They can perform various operations.

They can be used for a variety of tasks from financial accounting

to mathematical calculations, from designing textile prints to controlling machinery.

They are also flexible and can be used to work on business and

scientific problems.

2. Special Purpose Computers

Explanation

Special purpose computer can be designed to perform specific functions. In such devices, the instructions are permanently pre-programmed.

The instructions needed to perform the particular task are incorporated into the internal memory of the computer.

Some of the special purpose computers are aircraft control

system, electronic voting machines etc.

Classification based on Size and Capacity

1.Micro Computer

2.Mini Computers

3.Mainframe Computers

4.Super Computers.

1.Micro Computer Explanation

A micro computer is a small, low cost digital computer, which usually consists of a microprocessor, a storage unit, an input channel, and an output channel, all of which may be on one chip inserted into one or several PC boards.

Page 17: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

17

These are mainly used in offices, homes, schools, shops, stores etc.

IBM PCs, Apple Mac, IBM PS/2 are some popular computers of this range.

Sample Diagram

Advantages

They are small and portable They are relatively inexpensive They work as soon as they are switched on They do not occupy much space They do not consume much power.

Disadvantages

They are relatively slow Its storage capacity is low.

2.Mini Computer

Explanation

The mini computer is a small digital computer whose process and storage capacity is lesser than that of a mainframe, but more than that of micro computer.

Its speed of processing data is in between that of a mainframe and a micro

computer.

Mini computers are mainly multiprocessor systems where many users simultaneously work on the systems.

Page 18: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

18

Sample Diagram

Advantages

It is a general purpose computer Its storage capacity is about 2 mega words It can support all high level languages It is relatively inexpensive

Disadvantages

They are slower when compared with the mainframe computers The memories of mini computers are smaller than mainframes.

3.Mainframe Computer Explanation

Mainframe computers are larger, faster and more expensive than other general purpose computers.

A mainframe is an ultra-high performance computer made for high-

volume, processor-intensive computing.

It consists of a high-end computer processor, with related peripheral devices, capable of supporting large volumes of data processing, high performance online transaction processing systems, and extensive data storage and retrieval.

Mainframe allows its user to maintain large information storage at a

centralized location and be able to access and process this data from different computers located at different locations.

Sample Diagram

Page 19: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

19

Advantages

They are capable of handling all tasks. They require large room space Consumption of electricity is very high Maintenance cost is also very high.

4.Super Computer Explanation

Super computer is the fastest, costliest and the most powerful computer available today.

They are specially designed to maximize the number of parallel

operations.

A super computer has the highest processing speed at a given time for solving scientific and engineering problems.

It contains a number of CPUs that operate in parallel to make it faster. Sample Diagram

Advantages

There are several processors working simultaneously They process at a rapid speed They have more main memory

IV Classification based on Mode of Use

1. Palmtop Computers

2.Laptop Computers

3. Personal Computers

4. WorkStations

5. Mainframe System

6. Client and Server.

Page 20: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

20

1.Palmtop Computer Explanation

The palmtop computers accept handwritten inputs using an electronic pen, which can be used to write on a palmtop‟s screen.

They have small disk storage and can be connected to a wireless network.

It also has facilities to be used as a mobile phone, fax and e-mail machine.

Sample Diagram

2.Laptop Computer Explanation

A laptop is a portable computer, that is, a user can carry it around. Since the laptop computer resembles a notebook, it is also known as “notebook”.

The biggest advantage of this computer is that one can use this

computer anywhere and at anytime, especially when one in traveling.

These computers do not need any external power

supply, as a rechargeable battery is completely self-contained in them.

Laptops are small computers enclosing all the basic features of

a normal desktop computer. These are expensive as compared to desktop computers.

Sample Diagram

Page 21: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

21

3.Personal Computer / Desktop Computer Explanation

They are mainly designed to meet the personal computing requirements of users at working place or at home.

It is a non-portable and general purpose computer which can easily fit in

on a normal size office table.

The personal computers are almost used by the children and adults for education and entertainments and hence they are now common everywhere.

It typically consists of a system unit, a display monitor, a keyboard,

internal hard disk storage, and other peripheral devices. Sample Diagram

4.Workstations Explanation

It is a powerful desktop computer designed to meet the computing needs of users or clients, with better processing, high storage capacity and with efficient and effective graphics display facility.

It looks similar to a personal computer and can be used by only one

person at a time through the LAN. Sample Diagram

Page 22: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

22

5.Clients and Servers Explanation

It is possible to interconnect several computers for communicating over the networks to share the several resources or services among the multiple users.

SERVER – It is a large computer that manages shared resources and

provides a set of shared user services to the client.

CLIENT – It is a single user personal computer or workstation and supports a user friendly interface with the end user. It sends request to the server and then gains access with the server.

Sample Diagram

Basic Computer Organization

Introduction

A computer system consists of a number of interrelated components that work together with the aim of converting data into information.

To attain information, data is entered through input devices. This data is processed using the central processing unit and then the processed data is displayed to the users using various output devices. All these parts are referred to as Hardware of the computer.

Page 23: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

23

Basic Computer Organization - Block diagram

CONTROL UNIT

INPUT UNIT MEMORY UNIT OUTPUT UNIT

A&L UNIT

Control flow

SECONDARY STORAGE

Data flow

Main Parts of Computer

1. Input Unit 2. CPU 3. Output Unit

1.Input Unit

Explanation

Input devices are electromechanical devices that allow the user to feed information into the computer for analysis, storage and to give commands to the central processing unit.

Functions of input unit

Accept data and instructions from the outside world. Convert it to a form that the computer can understand. Supply the converted data to the computer system for further

processing. Input devices – Examples

Keyboard Mouse Light Pen

Digitizer Trackball

Joystick

Page 24: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

24

2.Output Unit

Explanation

Computers can communicate with human beings using output devices. Output devices take the machine-coded output results from the CPU and convert them into a form that is easily readable by human beings.

Functions of output unit

Output unit is the communication between the user and the computer.

It provides the information and results of a computation to the outside

world. It also converts the binary data into a form that users can understand.

Output devices – Examples

VDU or Monitor Printer Plotter

3.Central Processing Unit (CPU)

Explanation

It is the heart of the computer system, converts data (input) into meaningful information (output). It is a highly complex, extensive set of electronic circuitry, which executes stored program instructions.

Functions of CPU

It performs all calculations and all decisions. It controls and co-ordinates all units of the computer. It interprets instructions of a program.

It stores data temporarily and monitors external requests.

Parts of CPU 1.control unit

2.ALU unit 3.memory unit 1,Control Unit

Explanation This unit checks the correctness of sequence of operations. It fetches program instruction from the primary storage unit, interprets them, and ensures correct execution of the program. It also controls the input / output devices and directs the overall functioning of the other units of the computer.

Page 25: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

25

Uses

It instructs the computer how to carry out program instructions.

It directs the flow of data between different parts of the computer.

It controls all other units in the computer.

Arithmetic & Logic Unit (ALU)

Explanation

It contains the electronic circuitry that executes all arithmetic and logical

operations on the data made available to it.

Uses

All calculations are performed in the ALU of the computer. It also does comparisons and takes decisions.

3.Memory Unit

Explanation Computers require memory to process data and store output.

Memory refers to the electronic holding place for instructions and data.

Memory is a device, which is used to store information temporarily / permanently, it is a place where information is safely kept.

Uses

Used to store data and retrieve for later use.

Types of Memory

Primary Memory

Explanation

o It is also known as main memory, stores data and instructions temporarily for processing.

o It is an integral component of the CPU but physically, it is a separate part placed on the computer‟s motherboard.

o It can be further classified into random access memory

(RAM) and read only memory (ROM).

Page 26: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

26

Functions of Primary Memory p Used to hold the program being currently

executed in the computer.

o Fast Access – usually in the order of nano seconds.

o Contents will be lost when we switch off the computer.

(include current size of the memory – company wise as an example)

Secondary Memory

Explanation O Also known as auxiliary memory or external memory.

O Used for storing instructions and data permanently.

O It is slower and cheaper than the primary memory.

Functions of Secondary Memory

Not directly accessible – transferred through an I/O system.

Non-Volatile and long-term storage. o Holds large amount of data

Works slower than primary memory.

Uses o Used mainly for taking back-up of large data. o To store and retrieve data for later use.

(include current size of the memory – company wise as an example)

Number System

Introduction

o A number is required for counting or to express the amount of some quantity. It consists of a group of symbols called digits, which are arranged in a definite manner. There can

be many ways in which the digits can be arranged to form a number. This gives rise to what we call a Number System.

o The most widely adopted system is the decimal number system which has 10 digits

(0,1,2,…9), the octal system has eight digits (0,1,2,…7), the hexadecimal system has sixteen digits (0,1,2,…9,A,B,C,D,E,F), the binary number system

Page 27: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

27

has only two digits (0,1).

o The number of digits in a system is called “radix” or “base”. Thus, the decimal

system may be called as radix – 10 system, the binary system as radix – 2 system and so on.

Types of Number System

1. Non-Positional Number System

2. Positional Number System1.Non-Positional Number System Explanation

In olden days human beings counted the numbers using their fingers. When twenty fingers were not adequate, stones or sticks were used to indicate values.

This method of counting uses the non-positional number system or additive approach. In non-positional number system each symbol represents the same values regardless of its position in the number. The symbols are simply added to find out the value of a particular number.

Example

Using this system, the symbols i.e., I for 1, II for 2, III for 3, IIII for 4, IIIII for 5 etc., are used. Drawbacks

It is difficult to perform arithmetic operations in non-positional number system.

2.Positional Number System

Explanation

The most widely used number system is positional number system. The

positional numbers uses only few symbols called digits. Such symbols

specify different values depending on the position they occupy in the

number.

The value of each digit in a number is determined by using the following

three considerations.

o The Digit

o The position of the digit in the number

o The base or radix of the number system

Page 28: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

28

Example

The decimal number 3977.39(10) is taken to mean

3 x 103 + 9 x 10

2 + 7 x 10

1 + 7 x 10

0 . 3 x 10

-1 + 9 x 10

-2

1000th

position

100th

position 10th

position Unit position 1/10th

position 1/100th

position

Characteristics

All positional number system have a “Base” or “Radix”.

The base or radix value determines the total number of digits available in

the number system. The maximum value of a single digit is always equal to one less than the value of the base. In day-to-day activities the commonly used number system is decimal number system i.e., Base-10 system.

Arithmetic operations can be easily performed using this number system.

Types of Positional Number System

Decimal Number System (Base 10 or Radix 10 System)

Explanation The number system that is most commonly used is the decimal

number system. In this number system the base or radix is 10 and there are altogether ten numbers i.e., 0,1,2,3,4,5,6,7,8,9.

In the decimal number system, the successive position to the left of the decimal point represents units, tens, hundreds, thousands etc.,

Number Representation

A number in a radix system would be written as

Page 29: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

29

6th 5th 4th 3rd 2nd 1st . -1st

-2nd

position

105 10

4 10

3 10

2 10

1 10

0 . 10-1 10-2 weights

10000 10000 1000 100 10 1 . 0.1 0.01 values

Example

In decimal number system 3967(10) or 3967.

Its values can be written as

3 x 103 + 9 x 10

2 + 6 x 10

1 + 7 x 10

0 3 x 1000 +

9 x 100 + 6 x 10 + 7 x 1 3000 + 900 + 60 + 7

3967

Binary Number System

Explanation

Almost all digital computers and systems are based on binary number system. Binary means two, it uses only two digits, i.e., 0‟s and 1‟s. In other words, binary numbers are strings of 0‟s and 1‟s.

Digital system accepts the binary numbers for their operation, because the electronic devices are most reliable when designed for two state operations. The two state operation is universal in digital electronics.

Almost all digital components are based on binary operations. This

is why it is convenient to use binary numbers when analyzing or designing digital circuits.

The right most bit is called Least Significant Bit (LSB) and left

most bit is called Most Significant Bit (MSB). The weights assigned to bits in this system are power of 2.

Number Representation

The following table explains the position, weight and its values of

binary number system.

Page 30: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

30

8th 7th 6th 5th 4th 3rd 2nd 1st . -1st

-2nd

position

27 26 25 24 23 22 21 20 . 2-1 2-2 weights

128 64 32 16 8 4 2 1 . 0.5 0.25 values

The table shows the decimal equivalent of binary system

Decimal Number Binary Equivalent

0 0000

1 0001

2 0010

3 0011

4 0100

5 0101

6 0110

7 0111

8 1000

9 1001

Example

Convert the binary number 1 0 0 1 1 1 (2) to decimal number.

Solution: 1 0 0 1 1 1(2) =?(10)

Step 1: Multiply column values by corresponding column digits.

6th 5th 4th 3rd 2nd 1st Column value from right

1 0 0 1 1 1 Given binary number

×25 ×2

4 ×2

3 ×2

2 ×2

1 ×2

0 weight

Step 2: Sum the products

Page 31: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

31

32 + 0 + 0 + 4 + 2 + 1 = 39

Ans:1 0 0 1 1 1(2) = 39(10)

Octal Number System

Explanation

The number system with base or radix digit (8) is known as octal number system. There are only eight digits i.e., 0,1,2,3,4,5,6,7.

Here the largest single digit is 7, which is one less than the base. Each position in this number system represents a power of the base (8).

Number Representation

The following table explains the position, weight and its values of octal number system.

8th 7th 6th 5th 4th 3rd 2nd 1st . -1st

-2nd

position

87 8

6 8

5 8

4 8

3 8

2 8

1 8

0 . 8-1 8-2 weights

2097152 262144 32768 4096 512 64 8 1 . 0.125 0.015 values

In octal number system only 8 digits are available. The decimal equivalent of the octal numbers is given below.

Decimal Number Octal Number

0 0

1 1

2 2

3 3

4 4

Page 32: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

32

5 5

6 6

7 7

8 10

Page 33: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

33

Example

The decimal equivalent of the octal number 3077(8) is

3077(8) = 3 x 83 + 0 x 82 + 7 x 81 + 7 x 80

= 3 x 512 + 0 x 64 + 7 x 8 + 7 x 1

= 1536 + 0 + 56 + 7

3077(8) = 1599(10)

Hexadecimal Number System

Explanation

1.The hexadecimal number system is one of the most popular computing systems and is extremely used in Microprocessor work. It has a base of 16 and this requires 16 distinct symbols to represent the number.

2.The first 10 digits are digits of decimal number system (0 to 9) and the remaining 6 digits are denoted by (A to F) representing decimal value (10 to 15) where A=10, B=11, C=12, D=13, E=14 and F=15.

3.Since numbers (0 to 9) and Alphabets (A to F) are used to represent the digits in hexadecimal number system, it is also called as Alphanumeric Number System.

Number Representation

The following table explains the position, weight and its values of hexadecimal number system.

8th 7th 6th 5th 4th 3rd 2nd 1st . -1st

-2nd

position

167 16

6 16

5 16

4 16

3 16

2 16

1 16

0 . 16

-1 16

-2 weights

268435456 16777216 1048576 65536 4096 256 16 1 . 0.062 0.003 values

The following table illustrates the conversion of decimal number to binary and hexadecimal number.

Page 34: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

34

Example

Convert the hexadecimal number E6C4(16) to decimal number.

Solution: E 6 C 4(16) = ? 10 = E×16

3 + 6×16

2 + C×16

1 + C×16

0 = 14×16

3 + 6×16

2 + 12×16

1

+ 4×160 = 57344 + 1536+ 192 +4 = 59076

E6C4(16) = 59076(10)

Conversion of Number Systems

o There are so many techniques available for converting the number from one number system to other number systems.

o The decimal number system can be converted into other system by using the following two methods:

4 4

5 5

6 6

7 7

8 8

9 9

10 A

11 B

12 C

13 D

14 E

15 F

Decimal Number Hexadecimal

Number

0 0

1 1

2 2

3 3

Page 35: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

35

Remainder Method Power Method

Remainder method:-

This is the most frequently used method to convert numbers. It includes the

following steps:

Step 1: Divide the given decimal system with the base „r‟ of the proposed system.

From this system, we will get quotient q1 and a remainder r1.

Step 2: Then divide the quotient q1 by the base „r‟ of the proposed system and

obtain the quotient q2 and remainder r2.

Step 3: Then divide the quotient q2 by the base „r‟ of the proposed system

and obtain the quotient q3 and remainder r3.

This process if division of the subsequent quotient by the base „R‟ of the

proposed system should be repeated until the quotient becomes less than the base „R‟.

Then the required number can be obtained by writing the last quotient first and then

the remainder in the reverse order.

i.e., rn r n-1 r n-2 …r2 r1

Example 1: Convert decimal number 15(10) to binary number.

Step 1: Divide 15 by 2.The quotient is 7 and remainder is 1.

2

15

2 7 -1

2 3 -1

1 -1

Page 36: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

36

Step 2: Divide 7 by 2.The quotient is 3 and remainder is 1. Step 3: Divide 3 by 2.The quotient is 1 and remainder is 1.

15(10)=1111(2)

Power method:-

The power method for converting decimal systems to any other

number system involves the following steps:

Fractions:-

Multiply the decimal fraction successively by 2, pick up 0 or 1 from the units

place of each product and write it in the binary result. Carry on this process with the

remaining fraction of each product.

Example 1: Convert Decimal number 0.39(10) to binary number.

0.39×2=0.78 -> 0.78×2 =1.56 -> 0.56×2 =1.12 -> Ans

0.39(10) = 0.011(2)

with a carry of 0 with a carry of 1 with a carry of 1

Example 2: Convert Decimal number 39.77(10) to binary number.

In this case split the decimal number 39.77 into an integer of 39 and a fraction

of 0.77 and apply the above methods to each part.

Page 37: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

37

39

2

Remainder

2 19 -1 -r1

2 9 -1 -r2

2 4 -1 -r3

2 4 -0 -r4

2 -0 -r5

r6

0.77×2 =1.54 ->0.54

0.54×2 =1.08 ->0.08

0.08×2 =0.16 ->0.16

0.16×2 =0.16 ->0.32

with a carry of 1

with a carry of 1

with a carry of 0

with a carry of 0

39.77(10) = 100111.1100 (2)

Decimal to Binary Conversion – Example

1. Convert decimal number 15(10) to binary number.

Step 1: Divide 15 by 2.The quotient is 7 and remainder is 1.

2 15

2 7 - 1

2 3 - 1

2 1 - 1

Step 2: Divide 7 by 2.The quotient is 3 and remainder is 1. Step 3: Divide 3 by 2.The quotient is 1 and remainder is 1.

Page 38: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

38

15(10)=1111(2)

2. Convert Decimal number 39.77(10) to binary number.

In this case split the decimal number 39.77 into an integer of 39

and a fraction of 0.77 and apply the above methods to each part.

39

2

Remainder

2 19 -1 -r1

2 9 -1 -r2

2 4 -1 -r3

2 4 -0 -r4

2 -0 -r5

r6

0.77×2 =1.54 ->0.54

0.54×2 =1.08 ->0.08

0.08×2 =0.16 ->0.16

0.16×2 =0.16 ->0.32

carry of 1

carry of 1

carry of 0

carry of 0

39.77(10) = 100111.1100 (2)

Decimal to Octal Conversion – Example

1. Convert the decimal number 3977(10) to octal number.

3977

8

Remainder

8 497 -1 -r1

8 62 -1 -r2

7 -6 -r3

Page 39: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

39

3977(10) =7611(8)

2. Convert the decimal number 0.39(10) to octal number.

0.39×8 =3.12 ---> 0.12×8 =0.96 ---> 0.96×8 =7.68 ----> 0.68×8 =5.44 ---->

Ans:

with a carry of 3 with a carry of 0 with a carry of 7 with a carry of 5

0.39(10) = 0.3075(8)

Decimal to Hexadecimal Conversion – Example

1. Convert the decimal number 39(10) to hexadecimal

16 39 2 -7

Ans: 39(10)=27(10)

2. Convert the decimal number 1723.256(10) =?(16)

Integer part Fractional Part

16

- 11 0.256x16=4.096--

0.096 with a carry of 4

1723

0.096x16=1.536-

0.536 with a carry of 1

16 107 -11 0.536x16=8.576-

0.576 with a carry of 8

6

Ans: 1723.256(10)=6BB.418(16)

Binary to Decimal Conversion – Example

Convert the binary number 1 0 0 1 1 1 (2) to decimal number.

Page 40: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

40

Solution: 1 0 0 1 1 1(2) =?(10)

Step 1: Multiply column values by corresponding column digits.

6th 5th 4th 3rd 2nd 1st Column value from right

1 0 0 1 1 1 Given binary number

×25 ×2

4 ×2

3 ×2

2 ×2

1 ×2

0 weight

Step 2: Sum the products

32 + 0 + 0 + 4 + 2 + 1 = 39

Ans:

1 0 0 1 1 1(2) = 39(10)

Binary to Octal Conversion – Example

Convert the binary number 10011.11001(2) to octal number

Soln:

10011.11001(2) ---

010 011 . 110 010

2 3 . 6 2

Ans:

10011.11001(2) =23.62(8)

Binary to Hexadecimal Conversion – Example

Convert the binary number 110101001.0010110(2) to octal number

Soln:

110101001.0010110(2) ---

1 1010 1001 . 0010 110 0001 1010 1001 . 0010 110

1 A 9 . 2 C

Page 41: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

41

Ans:

110101001.0010110(2) =1A9.2C(16)

Octal to Decimal Conversion – Example

Convert the octal number 37(8) to decimal number

37(8) = 3 x 81 + 7 x 8

0 = 24

+ 7 37 (8) = 31(10)

Octal to Binary Conversion – Example

Convert the octal number 377.77(8) to binary number

3 7 7 . 7 7

011 111 111. 111 111

377.77(8) =011111111.111111 (2) 47

Octal to Hexadecimal Conversion – Example

Convert the octal number 235.21(8) to hexadecimal number.

235.21(8)= 2 3 5 . 2 1

010 011 101 . 010 001

1001 1101 . 0100 0100

235.21(8) =10011101 . 01000100(16)

235.21(8) =9D.44(16)

Hexadecimal to Decimal Conversion – Example

1. Convert the hexadecimal number E6C4(16) to decimal number.

Solution: E 6 C 4(16) = ? 10

Page 42: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

42

=E×163 + 6×16

2 + C×16

1 + C×16

0 = 14×16

3 + 6×16

2

+ 12×161 + 4×16

0 = 57344 + 1536+ 192 +4 = 59076

E6C4(16) = 59076(10)

2. Convert the hexadecimal number 1 B D(16) to decimal number.

Solution: 1 B D(16) = ? 10

=1×162+ B×16

1+ D×16

0 = 1×256+

11×16+ 13×1 = 256 + 0176+ 13 1 B D(16) = 445(10)

Hexadecimal to Binary Conversion – Example

Convert the hexadecimal number 8FAC.BFC(16) to binary number

8 F A C . B F C

1000 1111 1010 1100 . 1011 1111 1100

Ans:

8FAC.BFC(16) = 1000111110101100.101111111100 (2)

Hexadecimal to Octal Conversion – Example

Convert the hexadecimal number A9C5.DB4 (16) to octal number.

A9C5.DB4 (16)= A 9 C 5 . D B 4

1010 1001 1100 0101 . 1101 1011 0100

001 010 100 111 000 101 . 110 110 110 100

1 2 4 7 0 5 . 6 6 6 4

A9C5.DB4 (16)= 124705.6664(8)

General Conversion:-

Convert the base-4 number system 10101(4) to decimal number.

Page 43: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

43

Solution : 1 0 1 0 14 = ? 10

=1×44+ 0×4

3+ 1×4

2+ 0×4

1+ 1×4

0

3 1×256+ 0×64+ 1×16+ 0×4+ 1×1 4 256 + 0 + 16 +0 +1

Ans: 1 0 1 0 1(4) = 273(10)

Page 44: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

44

Problem Solving Techniques

Definition

Problem solving technique is a set of techniques and graphical tools that helps in providing logic for solving a problem. These tools are used to express the logic of the problem by specifying the correct sequence of all instructions to be carried out

Problem Solving Techniques / Tools

There are three important problem solving tools used for program development. They

are: Algorithms.

Flowcharts.

Pseudo codes.

Algorithm

Introduction

After the preparation of a suitable plan for developing the program by its logic. i.e., the correct sequence and procedure of instructions required to carryout the task, the algorithm is often used to refer the logic of the program. It is one of the basic tools used to develop the problem solving.

Algorithm – Definition

o It is defined as “a sequence of instructions designed in such a way that if the instructions are executed in the specified sequence, the desired results will be obtained”.

o It is also defined as “any problem whose solution can be expressed in a list

of executable instruction”. o An algorithm is defined as a finite sequence of explicit instructions that, when

provided with a set of input values produces an output and then terminates.

Characteristics / Properties of Algorithms o Algorithms are one of the most basic tools that are used to develop the problem solving

logic.

o Each and every instruction should be precise and unambiguous. o Instructions in an algorithm should not be repeated infinitely. o It looks like normal English.

Page 45: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

45

o There should not be any uncertainty about which instruction to be executed next. o Algorithm should conclude after a finite number of steps. o Algorithm must be general enough to deal with any contingency.

Qualities of a good algorithm

The following are the primary factors that are often used to judge the quality of the algorithms.

Time – To execute a program, the computer system takes some amount of time. The

lesser is the time required, the better is the algorithm.

Memory – To execute a program, computer system takes some amount of memory space. The lesser is the memory required, the better is the algorithm.

Accuracy – Multiple algorithms may provide suitable or correct solutions to a given problem, some of these may provide more accurate results than others, and such algorithms may be suitable.

Sequence – The procedure of an algorithm must form in a sequence and some of the instructions of an algorithm may be repeated in number of times or until a particular condition is met.

Generability – The designed algorithm must solve a single isolated problem and more often algorithms are designed to handle a range of input data to meet these criteria, so the algorithms must be generalized.

Representation of Algorithms

Algorithms can be represented in several ways. Generally the programmers follow any one of the following ways to represent the algorithms.

1. Normal English

Algorithm can be easily represented in step by step sequential order in normal English, such algorithms are easy to understand, write and read.

2. Flowchart

Flowchart is a pictorial representation of an algorithm i.e., the sequential steps in an algorithm can be represented as a flowchart using the standard symbols.

3. Pseudo Code

Pseudocode is also a formal design tool with the rules of structured design and programming.

4. Decision Table

A decision table helps a lot in designing a specific segment of a design. It provides another way to look at a complex, nested selection to help clarify the conditions to be tested and how those conditions should be nested to arrive at the proper actions.

5. Program

Algorithms can be represented as a program using any high level language, which becomes a program.

Page 46: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

46

Sample Algorithm – Example

To find out the largest number among three numbers A,B&C.

Step 1: Start

Step 2: Read three Numbers A, B & C.

Step 3: Find the largest number between A & B and store it in Max_AB.

Step 4: Find the larger number between MAX_AB and C and

store it in MAX.

Step 5: Display MAX.

Step 6: Stop.

Flowchart

Introduction

o A flowchart is a diagrammatic representation that illustrates the sequence of operations to be performed to arrive at the solution. The operating instructions are placed in boxes which are connected by arrows to indicate the order of execution.

o It is a symbol oriented design that identifies the type of statement by the

shape of the symbol containing the statement, and it is used as a road map for a programmer which guides how to go from the starting point to the end point.

o A flowchart uses different shaped symbols to denote the different

appropriate instructions and these instructions can be written within the boxes using clear statements. Then these boxes are connected by lines having arrow marks to indicate the flow of operations that is the exact sequence in which the instructions are to be executed. The process of drawing a flowchart for an algorithm is called flowcharting.

Flowchart – Definition o Flowchart is a pictorial representation of an algorithm; it is the

layout and visual representation of the plan to be followed by the corresponding algorithm.

o A flowchart is a pictorial representation of an algorithm in which the steps

are drawn in the form of different shapes of boxes and the logical flow is indicated by interconnecting arrows.

Page 47: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

47

Why we need flowchart? o The primary purpose of the flowchart is to help the programmer in

understanding the

logic of the program. Therefore, it is always necessary to include all the required steps in detail. Flowcharts outline the general procedure.

o The program logic is made easy through the flowchart that have

standardized meaning. Every programmer uses the same basic shapes, so others can easily read and interpret the logic of the program.

Page 48: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

48

Flowchart Symbols (Commonly Used Important Flowchart Symbols)

Symbol Symbol Name Description

Flow Lines Used to connect

symbols

Terminal Used to represent start,

pause or halt in the

program logic.

Input/Output Represents the

information entering or

leaving the system.

Processing Represents arithmetic

and logical instructions.

Decision Represents a decision to

be made.

Connector Used to join different

flow lines.

Page 49: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

49

Page 50: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

50

Rules for drawing a flowchart

1. The flowchart should be clear, neat and easy to follow.

2. The flowchart must have a logical start and finish.

3. Only one flow line should come out from a process symbol.

4. Only one flow line should enter a decision symbol. However, two or three flow

lines may leave the decision symbol.

5. Only one flow line is used with a terminal symbol.

6. Within standard symbols, write briefly and precisely.

7. Intersection of flow lines should be avoided.

8. It is useful to test the validity of the flowchart with normal/unusual test data.

Advantages of flowchart A flowchart helps to clarify how things are currently working and how they

could be improved. It also assists in finding the key elements of a process by drawing

clear lines between the end of one process and the start of next one.

Reasons for using flowcharts as a problem solving tool are given below:

Makes Logic Clear

o Before coding the program the programmer must be known about the logic of

the program.

Page 51: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

51

o To make logic easier the programmer has to follow the task that provides pictorial

representation.

o If programmer has clear idea about the logic, then only they will produce good

programming.

Better Communication

o The flowcharts are better for communication, because “a picture is worth of

thousands words.”

o It is very easy for the programmer to explain the logic of the program through the

flowchart.

Effective Analysis

o The flowcharts are very well suited to analyze the problem and can be broken

down into parts for study and further analysis of the system.

Effective Synthesis

o A team of designers or programmers are associated with the design of complex

system. o Each designer or programmer is responsible for designing a part of the

entire system.

o So initially each designer or programmer draws a flowchart for their part, then all

the flowcharts from all the designers or programmers can be placed together to

visualize the overall system Effective coding

p After designing the flowchart, it is very easy to write programs for the

programmers, because flowchart is the road map for the programmers.

Appropriate documentation

o The flowcharts provide the documentation support obviously

Systematic debugging

p After taking care in program design, there may be chances for some errors. Such

errors can easily be found out in the flowcharts, and these can be eliminated easily

Page 52: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

52

Systematic Testing

o It is the process of executing the designed and developed program with sample

data. o A flowchart is helpful in designing the test data for systematic testing of

programs.

Efficient program maintenance

o The maintenance of operating program becomes easy with the help of

flowchart. o It helps the programmer to put efforts more efficiently on that part.

Disadvantages of flowchart

The limitations of flowcharts are:

i. Complex Logic ii. Costly.

iii. Difficult to alter and modify. iv. Reproduction is difficult. v.No update.

Sample flowchart – Example

Start

X=10, Y=20

Z=X+Y

Print Z

Page 53: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

53

Stop

Pseudo Code

Introduction

Pseudocode is also a formal design tool, developed with the structured programming. It is visual, narrative, and more easily used for structured design.

o It is a programming analysis tool that is commonly used for planning the program logic.

o Pseudocode is written in normal English and cannot be understood by the

computer. During the design of Pseudocode, the designer or programmer can only concentrate the logic of the program without worrying the syntax of the instructions.

o Pseudocode strikes a fine balance between the understandability and informality of a natural language like English, and the precision of a computer program code.

Pseudo Code – Definition o Pseudocode is made up of two words: pseudo and code. Pseudo means

imitation and code refers to instructions, written in a programming language. As the name suggests, Pseudocode is not a real programming code, but it models and may even look like programming code.

o It is a generic way of describing an algorithm without using any specific

programming language-related notations.

o Pseudocode is an outline of a program, written in a form that can be easily converted into real programming statements.

o Pseudocode uses plain English statements rather than symbols, to

represent the processes of a computer program. It is also known as PDL (Program Design Language), as it emphasizes more on the design aspect of a computer program or structured English.

Rules for writing Pseudo Code

The Pseudocode is very clear unlike flowcharts. It is more individualistic; hence use the following rules writing Pseudocode.

Statements should be written in simple English and should be programming

language independent.

Page 54: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

54

Steps must be understandable, and when the steps are followed, they must produce a solution to the specified problem.

Each set of instructions is written from top to bottom, with only one entry

and one exit.

Pseudocode should be concise. Write one statement per line. Capitalize initial keywords. Indent to show hierarchy. End multi-line structure. Keep statements language independent.

Advantages of Pseudo Code

o Since it is independent of any language, it can be used by most programmers.

o It is easy to develop a program from pseudo code than with a flowchart.

o It is easy to translate pseudo code into a programming language.

o Pseudo code is compact and does not tend to run over many pages.

Disadvantages of Pseudo Code

o It does not provide visual representation of the program‟s logic.

o There are no accepted standards for writing pseudo codes.

It cannot be compiled nor executed.

Sample Pseudo Code – Example

Pseudo code to calculate the area of a rectangle

PROMPT the user to enter the height of the rectangle.

PROMPT the user to enter the width of the rectangle.

COMPUTE the area by multiplying the height with width.

DISPLAY the area.

Page 55: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

55

STOP.

Some of the keywords used in pseudo code are given below:

Input: READ, OBTAIN, GET and PROMPT.

Output: PRINT, DISPLAY and SHOW.

Compute: COMPUTE, CALCULATE and DETERMINE.

Initialize: SET and INITIALISE

Add ONE: INCREMENT.

Algorithm, Flowchart and Pseudo code

Write a program to find the largest of three no‟s

Algorithm:

Step1: Start

Step2: READ a,b,c

Step3: IF (a>b) and (a>c) Then

Step 3.1: Print „A is big‟

ELSE

Step 4: IF (b>c) Then

Step 4.1: Print „B is big‟

ELSE

Step 4.2: Print „C is big‟

Step 5: Stop

Page 56: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

56

Flowchart:

Start

Read a,b,c

If a>b and

a>c

a

Print A is big

If b>c

Print B is big

Print C is big

stop

Page 57: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

57

Pseudo code:

READ the values for a,b,c

IF (a>b and a>c) THEN

WRITE „A is Big‟

ELSE IF (b>c) THEN

WRITE „B is Big‟

ELSE

WRITE „C is Big‟

ENDIF

Stop

GE6151 – COMPUTER PROGRAMMING

UNIT II C PROGRAMMING BASICS

Problem formulation – Problem Solving - Introduction to „ C‟ programming –fundamentals – structure of

a „C‟ program – compilation and linking processes – Constants, Variables – Data Types – Expressions

using operators in „C‟ – Managing Input and Output operations – Decision Making and Branching –

Looping statements – solving simple scientific and statistical problems.

2.1 Problem Formulation

Before attempting to solve a problem, we need to first formulate or define the problem.

It is important to precisely define the problem you intend to solve.

The more difficult it is to define the problem, the harder you have to try.

Why?

A problem formulation is/can be a question or something you are wondering about.

The problem should be something you can solve/give answers to.

Page 58: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

58

A conclusion in an analysis is always the answer to the problem formulation.

Different types of problem formulation:

"What” - descriptive

"Why” - explanatory

"How” - normative

Case

A company has trouble integrating new employees.

What

is what you call a descriptive problem formulation - it describes a problem!

Example: What kind of problems appear for the company and the employee in the

beginning of the employment?

Why

is the explanatory problem formulation - it wants to explain a problem!

Example: Why does it seems that the employees have trouble adapting the culture in the

organisation?

How

is the normative problem formulation - it tries to solve a problem!

Example: How can the company make sure that the new employees get all the support

they need?

Hypothesis

A problem formulation can be in the form of a hypothesis.

The company is hiring the wrong kind of people.

2.2 Problem Solving

A systematic approach to defining the problem (question or situation that presents uncertainty,

perplexity or difficulty) and creating a vast number of possible solutions without judging these solutions.

Problem solving is the mental process you follow when you have a goal but can‟t immediately

understand how to achieve it. It‟s a process that depends on you – how you perceive a problem, what you

know about it, and the end-state you want to reach.

Solving a problem involves a number of cognitive activities:

ascertaining what the problem really is

identifying the true causes of your problem and the opportunities for reaching your goal

generating creative solutions to the problem

evaluating and choosing the best solution, and

implementing the best solution, then monitoring your actions and their results to ensure the

problem is solved successfully

Clearly, problem solving isn‟t a one-step process. Your success will depend on whether you

approach and implement each of the stages effectively. The best way to do this is to use a well-

established, systematic problem-solving model.

2.2.1 The six steps of problem solving

Problems vary widely, and so do their solutions. Sometimes a problem and its solution are clear,

but you don‟t know how to get from point A to point B. At other times, you may find it hard to define

what‟s wrong or how to fix it. Regardless of what a problem is, you can use a six-step problem-solving

model to address it. This model is highly flexible and can be adapted to suit various types of problems. It

Page 59: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

59

also comes with a flexible set of tools to use at each step. The model is designed to be followed one step

at a time, but you may find that some stages don‟t require as much attention as others. This will depend

on your unique situation.

The steps in the problem-solving model are as follows:

1. Define the problem –

Clearly state the problem

Identify what circumstances lead to the cause of the problem.

Write a clear definition of the problem and the barriers encountered.

2. Analyze the problem –

Decide what type of problem it is.

Dig to the root causes of the problem, and detail the nature of the gap between where you

are and where you want to be.

The five-why analysis is a tool that‟ll help you get to the heart of the problem.

1. Ask “Why?” a number of times to dig through each layer of symptoms and so to

arrive at the problem‟s root cause.

2. You can get to the root of a more complicated problem using a cause-and-effect

diagram.

3. A cause is something that produces an effect, result, or consequence – or what

contributed to the current state of affairs.

4. Categories of causes include people, time, and the environment.

3. Identify as many potential solutions as you can –

1. Brainstorm creatively – ask lots of questions about who, what, where, when, and how of

the causes to point to various possibilities.

2. Don‟t limit yourself by considering practicalities at this stage;

3. Simply record your ideas.

4. Choose the best solution –

1. In evaluating your ideas, more options could present themselves.

2. You could do this by rating each possible solution you came up with in step 3 according

to criteria such as

1. how effective it will be,

2. how much time or effort it will take,

3. its cost, and

4. How likely it is to satisfy stakeholders.

5. Plan of action –

1. During this step, you determine what steps must be taken, designating tasks where

necessary.

2. And you decide on deadlines for completing the actions and estimate the costs of

implementing them.

3. You also create a contingency plan in case of unforeseen circumstances so that if

anything goes wrong with your plan, you have a “plan B” in place.

4. Typically, this stage involves narrowing down the possible ways to implement the

solution you‟ve chosen, based on any constraints that apply.

5. You also should draw up an action plan.

6. The complexity of the plan will depend on the situation, but it should include the who,

what, and when of your proposed solution.

6. Implement the solution –

1. This is an ongoing process.

Page 60: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

60

2. You need to ensure the required resources remain available and monitor progress in

solving the problem; otherwise, all the work you‟ve done might be for nothing.

This model is highly adaptable. Although you shouldn‟t skip any of the six steps, you can tailor

the amount of time you spend on each stage based on the demands of your unique situation.

The six-step problem-solving model, and the tools it provides, is an effective, systematic

approach to problem solving. By following each step consciously, you can ensure that generating

solutions is a fact-driven, objective, and reliable process. It encourages you to dig deeper to the root

cause, allows you to get input from others, to be creative when finding solutions, and to monitor your

solutions to make sure they‟re working. So by following this model you‟re more likely to come up with

good, original, lasting solutions.

To solve problems effectively, you need to use a good problem-solving model. The six-step

model is a tried-and-tested approach. Its steps include defining a problem, analyzing the problem,

identifying possible solutions, choosing the best solution, planning your course of action, and finally

implementing the solution while monitoring its effectiveness.

2.3 Introduction to C

What is a programming language?

--Human beings need language to communicate between them. Similarly to communicate

with computers we need a programming language. All the events in life can be communicated to

computers with the help of programming language. C is the basic of all programming language. Before

the introduction of C we had only Machine level languages. C is just like any other communication

Language.

2.3.1 History of C

C language is a structure oriented programming language, was developed at Bell Laboratories in

1972 by Dennis Ritchie

C features were derived from earlier language called “B” (BCPL language)

C was invented for implementing UNIX operating system

In 1978, Dennis Ritchie and Brian Kernighan published the first edition “The C Programming

Language” and commanly known as K&R C

In 1983, the American National Standards Institute (ANSI) established a committee to provide a

modern, comprehensive definition of C. The resulting definition, the ANSI standard, or “ANSI

C”, was completed late 1988.

C standards

C89/C90 standard – First standardized specification for C language was developed by American

National Standards Institute in 1989. C89 and C90 standards refer to the same programming

language.

C99 standard – Next revision was published in 1999 that introduced new futures like advanced

data types and other changes.

2.3.2 Features of C

Low Level Features :

Page 61: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

61

­ C Programming provides low level features that are generally provided by the Lower

level languages. C is closely related to Lower level Language such as “Assembly

Language“.

­ It is easier to write assembly language codes in C programming.

Portability :

­ C Programs are portable i.e. they can be run on any Compiler with little or no

modification

­ Compiler and Preprocessor make it Possible for C Program to run it on different PC

Powerful

­ Provides Wide variety of „Data Types„

­ Provides Wide variety of „Functions‟

­ Provides useful Control & Loop Control Statements

Bit Manipulation

­ C Programs can be manipulated using bits. We can perform different operations at bit

level. We can manage memory representation at bit level. [Eg. We can use Structure to

manage Memory at Bit Level]

­ It provides wide verity of bit manipulation Operators. We have bitwise operators to

manage data at bit level.

High Level Features

­ It is more User friendly as compare to previous languages. Previous languages such as

BCPL, Pascal and other programming languages never provide such great features to

manage data.

­ Previous languages have their pros and cons but C Programming collected all useful

features of previous languages thus C become more effective language.

Modular Programming

­ Modular programming is a software design technique that increases the extent to which

software is composed of separate parts, called modules.

­ C Program Consist of Different Modules that are integrated together to form complete

program

Efficient Use of Pointers

­ Pointers have direct access to memory.

­ C Supports efficient use of pointer.

More Efficient

2.3.3 Application of C Programming

Application of C Programming are listed below -

C language is used for creating computer applications.

Used in writing Embedded softwares.

Firmware for various electronics, industrial and communications products which use micro-

controllers.

Page 62: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

62

It is also used in developing verification software, test code,simulators etc. for various

applications and hardware products.

For Creating Compiles of different Languages which can take input from other language and

convert it into lower level machine dependent language.

C is used to implement different Operating System Operations.

UNIX kernel is completely developed in C Language.

2.3.4 Language Level

Which level the C language belonging to?

S.no High Level Middle Level Low Level

1

High level languages

provides almost everything

that the programmer might

need to do as already built

into the language

Middle level languages don‟t

provide all the built-in functions

found in high level languages,

but provides all building blocks

that we need to produce the

result we want

Low level

languages provides

nothing other than

access to the

machines basic

instruction set

2

Examples:Ada, BASIC,

COBOL,

FORTRAN, Modula-2

C, C++, JAVA,

FORTH, Macro-Assembler Assembler

C is categorized as middle as well as higher level language.

C is called as middle level language because :

­ It allows the manipulation of bits, bytes and address directly.

­ It allows assembly language programs.

­ It performs almost no run-time error checking.

­ It is not strongly typed language; it permits almost all type conversion.

­ It has only 32 keywords.

C is called as higher level language because :

­ It allows human readable source code (English) while writing the programs.

C is a structured language

S.no Structure oriented Object oriented Non structure

1

In this type of language, large programs

are divided into small programs called

functions

In this type of language, programs are

divided into objects

There is no specific structure

for programming this language

Page 63: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

63

2 Prime focus is on functions and

procedures that operate on data

Prime focus is on the data that is

being operated and not the functions

or procedures

N/A

3 Data moves freely around the systems

from one function to another

Data is hidden and cannot be

accessed by external functions N/A

4 Program structure follows “Top Down

Approach”

Program structure follows “Bottom

UP Approach” N/A

5 Examples: BASIC, COBOL,

FORTRAN C, C++, JAVA, Ada, Pascal Assembler

Key points to remember:

1. C is structured, middle level programming language developed by Dennis Ritchie

2. Operating system programs such as Windows, Unix, Linux are wriiten by C language

3. C89/C90 and C99 are two standardized editions of C

4. C has been written in assembly language

2.4 Basic Structure of C Program

Page 64: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

64

The basic structure of C is defined by set of rules called protocol, to be followed by

programmer while writing C program. Below is the C basic structure.

The

documentations section

Consists of comment lines giving the name of the program, the author and other

details which the programmer would like to use later.

These comments beginning with the two Characters “\*” and ending with the

characters “*\” for a multi line comment and “\\” for a single line comment

Comments are helpful in identifying the program features

Not executable

The Preprocessor Section

o The link section Provides to the compiler the link functions from the system library

For Example: #include<stdio.h>

o The definition section Defines all symbolic constants.

To define macros, for example #define A 10

To define conditional inclusions, for example #ifdef

Global declaration section There are some variables that are used in one or more functions throughout the program, such

variables are called global variables and are declared in the global declaration section that is outside of

all the functions before main().

A 'C' program can be viewed as a group of building blocks called functions. A function is a sub-

routine that may include one or more statements designed to perform a specific task. To write a 'C'

program we first create functions and then put them together. A 'C' program may contain a one or more

sections as given below.

Main function section //Must

{

Declaration part

Executable part.

} Sub program section //optional

Function 1

Function 2

Documentation Section //optional

Link section //optional

Defining section //optional

Global declaration section //optional

Page 65: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

65

…… Function n

Every C program must have one main () function section.

This section can contain two parts:

Declaration part

The declaration part declares all the variables used in the executable part.

Execution part

There is at least one statement in the executable part which contains instructions to

perform certain task.

The declaration and executable part must appear between the opening and closing braces. The

program execution begins at the opening braces and ends at the closing braces. The closing brace of

the function section is the logical end of the program.

All statements in the declaration and executable parts end with a semicolon.

The sub program section contains all the user defined functions that are called in the main ()

function. User defined functions are generally placed immediately after the main function.

Example:

1. /*Documentation Section : Program to find the area of circle */

2. #include<stdio.h> /* link section */

3. #include<conio.h> /* link section */

4. #define PI 3.14 /* definition section */

5. float area; /* global declaration section */

6. void main()

7. {

8. float r; /* declaration part */

9. clrscr();

10. printf(“Enter the radius of the circle \n”); /*executable part starts here */

11. scanf(“%f”,&r);

12. area=PI*r*r;

13. printf(“Area of the circle = %f”,area);

14. getch();

15. }

2.4.1 Writing First C Program

C Programming Introduction: Tips

Every C Program should have exactly one main function.

C Program Execution Always Starts from main.

Execution of C Program begins at Opening brace of function and ends at closing brace

of the function.

Generally all statements in c are written in Lowercase Letters.

Uppercase Letters are used for Symbolic names, output strings and messages.

Every C statement must ends with semicolon.

All variables must be declared with respective data types before using.

C is free form-Language.

Page 66: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

66

Comments can be inserted anywhere in C Program, but nested comments are not

supported by C.

Braces are Generally Used for the Grouping of statements

Key points to remember:

1. Execution of every C program starts from main() function.

2. Protocol is set of rules to be followed by a programmer to write a program.

2.5 Compiling and Linking

Preprocessing:

The program is first given to a preprocessor, which obeys commands that begin with #

(known as directives).

#include <stdio.h> (include the info in <stdio.h> before compiling)

Compiling:

The modified program now goes to a compiler, which translates it into machine

instructions (object code).

Linking:

A linker combines the object code produced by the compiler with any additional code

needed to yield a complete executable program.

test.c --> (compiled) --> test.obj (linked) --> executable file

Step By Step Execution : C Program

Step 1 : Edit

This is First Step i.e. Creating and Editing Program.

First Write C Program using Text Editor , such as [ *Borland C/C++ 3.0* ,

Notepad++,Notepad ]

Save Program by using [.C] Extension.

File Saved with [.C] extension is called “Source Program”.

Step 2: Compiling

Compiling C Program: C Source code with [.C] Extension is given as input to

compiler and compiler converts it into Equivalent Machine Instruction.

In Borland C/C++ 3.0 program can be compiled using key [Alt + F9 ].

Compiler Checks for errors. If source code is error-free then code is converted

into Object File [.Obj ].

Step 3: Checking Errors

During Compilation Compiler will check for error, if compiler finds any error

then it will report it.

Users have to re-edit the program.

After re-editing program, Compiler again check for any error.

If program is error-free then program is linked with appropriate libraries.

Step 4 : Linking Libraries

Program is linked with included header files.

Program is linked with other libraries.

This process is executed by Linker.

Page 67: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

67

Step 5 : Error Checking

If run time error occurs then “Run-time” errors are reported to user.

Again programmer have to review code and check for the solution.

2.6 Tokens

C Tokens: These are the basic buildings blocks in C language which are constructed together to

write a C program.

Each and every smallest individual unit in a C program is known as C Tokens.

C Tokens are of six types.

Keywords (eg: int, while),

Identifiers (eg: main, total),

Page 68: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

68

Constants (eg: 10, 20),

Strings (eg: “total”, “hello”),

Special symbols (eg: (), {}),

Operators (eg: +, /,-,*)

2.6.1 Character set

Character set are the set of alphabets, letters and some special characters that are valid in C

language.

Alphabets:

Uppercase: A B C.................................... X Y Z

Lowercase: a b c...................................... x y z

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

Special Characters:

Special Characters in C language

, < > . _ ( ) ; $ : % [ ] # ?

' & { } " ^ ! * / | - \ ~ +

White space Characters:

Blank space, new line, horizontal tab, carriage return and form feed

2.6.2 Keywords

Keywords are the reserved words used in programming. Each keywords has fixed meaning and

that cannot be changed by user. For example: int money;

Here, int is a keyword that indicates, 'money' is of type integer.

As C programming is case sensitive, all keywords must be written in lowercase.

Keywords in C Language

auto double int struct

break else long switch

case enum register typedef

char extern return union

continue for signed void

do if static while

Page 69: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

69

default goto sizeof volatile

const float short unsigned

2.6.3 Identifiers

Each program elements in a C program are given a name called identifiers.

Names given to identify Variables, functions and arrays are examples for identifiers For example:

int money;

int mango_tree;

Here, money is a identifier which denotes a variable of type integer. Similarly,

mango_tree is another identifier, which denotes another variable of type integer.

Rules for constructing identifier name:

First character should be an alphabet or underscore. But, it is discouraged to start an identifier

name with an underscore though it is legal. It is because, identifier that starts with underscore can

conflict with system names. In such cases, compiler will complain about it. Some system names

that start with underscore are _fileno, _iob, _wfopen etc.

Succeeding characters might be digits or letter.

Punctuations and special characters aren‟t allowed except underscore.

Identifiers should not be keywords.

There is no rule for the length of an identifier. However, the first 31 characters of an identifier

are discriminated by the compiler. So, the first 31 letters of two identifiers in a program should be

different.

Declaring & initializing C variable:

Variables should be declared in the C program before to use.

Memory space is not allocated for a variable while declaration. It happens only on variable

definition.

Variable initialization means assigning a value to the variable.

S.No Type Syntax Example

1 Variable declaration data_type variable_name; int x, y, z; char flat, ch;

2 Variable initialization data_type variable_name = value; int x = 50, y = 30; char flag = „x‟, ch=‟l‟;

There are three types of variables in C program,

1. Local variable

The scope of local variables will be within the function only. These variables are

declared within the function and can‟t be accessed outside the function.

2. Global variable

The scope of global variables will be throughout the program. These variables can be accessed

from anywhere in the program. This variable is defined outside the main function. So that, this

variable is visible to main function and all other sub functions.

3. Environment variable

Environment variable is a variable that will be available for all applications and programs

in a compiler.

Page 70: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

70

We can access these variables from anywhere in a C program without declaring and

initializing in an application or C program.

The inbuilt functions which are used to access modify and set these environment

variables are called environment functions.

Do you know difference between variable declaration & definition?

S.no Variable declaration Variable definition

1 Declaration tells the compiler about data type and

size of the variable. Definition allocates memory for the variable.

2 Variable can be declared many times in a

program.

It can happen only one time for a variable in a

program.

3 The assignment of properties and identification to

a variable. Assignments of storage space to a variable.

2.6.4 Constant

C Constants are also like normal variables except their values cannot be modified by the program

once they are defined. They refer to fixed values. They are also called as literals

They may be belonging to any of the data type. Please see below table for constants with respect

to their data type.

Types of C constant:

1. Integer constants

2. Real or Floating point constants

3. Character constants

4. String constants

5. Backslash character constants

S.no Constant type data type Example

1 Integer constants

int

unsigned int

long int

long long int

53 , 762 , -478 , etc

5000u , 1000U , etc

1000L , -300L , etc

5555555LL

2 Real or Floating point constants float, doule

111.22F , 2.22e-2f

111.22 , 4.0 ,

-0.34565

5 character constants char „A‟ , „B‟, „C‟

6 string constants char “ABCD” , “Hai”

Rules for constructing C constant:

Integer Constants

1. It must not have a decimal point.

2. It can either be positive or negative.

Page 71: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

71

3. No commas or blanks are allowed within an integer constant.

4. An integer constant must have at least one digit.

5. If no sign precedes an integer constant, it is assumed to be positive.

6. The allowable range for integer constants is -32768 to 32767

Real Constants

1. A real constant must have at least one digit

2. It must have a decimal point

3. It could be either positive or negative

4. If no sign precedes an integer constant, it is assumed to be positive.

5. No commas or blanks are allowed within a real constant.

Character constants

1. A character constant is a single alphabet, a single digit or a single special symbol enclosed

within single inverted commas. Both the inverted commas should point to left.

2. For example, ‟C‟ is a valid character constant whereas „C‟ is not.

3. The maximum length of a character constant is 1 character

Backslash Character Constants:

There are some characters which have special meaning in C language. They should be

preceded by back slash symbol to make use of special function of them. Given below is the list of

special characters and their purpose.

Character Meaning

\b Backspace

\f Form feed

\n New line

\r Carriage return

\t Horizontal tab

\” Double quote

\‟ Single quote

\\ Backslash

\v Vertical tab

\a Alert or bell

\? Question mark

\N Octal constant (N is an octal constant)

\XN Hexadecimal constant (N – hex.dcml cnst)

How to use constants in a C program?

We can define constants in a C program in the following ways.

Page 72: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

72

1. By “const” keyword

2. By “#define” preprocessor directive

2.7 Data Types

1. C data types are defined as the data storage format that a variable can store a data to perform a

specific operation.

2. Data types are used to define a variable before to use in a program.

3. Size of variable, constant and array are determined by data types.

There are four data types in C language. They are,

S.no Types Data Types

1 Basic data types int, char, float, double

2 Enumeration data type enum

3 Derived data type pointer, array, structure, union

4 Void data type void

1. Basic data types

Integer data type:

This data type allows a variable to store numeric values.

int keyword is used to refer integer data type.

The storage size of int data type is 2 or 4 or 8 byte.

It varies depend upon the processor in the CPU that we use.

If we are using 16 bit processor, 2 byte (16 bit) of memory will be allocated for

int data type.

int(2 byte) can store values from -32,768 to +32,767

int(4 byte) can store values from -2,147,483,648 to +2,147,483,647.

If you want to use the integer value that crosses the above limit, you can go for

long int and long long int for which the limits are very high.

Note:

You can‟t store decimal values using int data type.

If you use decimal values, those would be truncated and you will get only whole number.

Character data type:

This data type allows a variable to store only one character.

storage size of char data type is 1.

We can store only one character using char data type.

char keyword is used to refer character data type. For example, „A‟ can be stored using char datatype.

Page 73: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

73

Floating point data type:

Floating point data type consists of 2 types. They are:

float:

Float data type allows a variable to store decimal values.

storage size of float data type is 4.

This also varies depend upon the processor in the CPU.

We can use upto 6 digits after decimal using float data type. For example, 10.456789 can be stored in a variable using float data type.

double:

Double data type is also same as float data type which allows upto 10 digits after

decimal.

The range is from 1E–37 to 1E+37.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

#include <stdio.h>

#include <limits.h>

int main()

{

int a = 30;

char b = 'A';

float c = 20.456;

double d = 5500000;

printf("Value of int a : %d \n",a);

printf("Value of char b : %c \n",b);

printf("Value of float c : %f \n",c);

printf("Value of double d : %lf \n",d);

return 0;

}

Output: Value of int a : 30

Value of char b : A

Value of float c : 20.455999

Value of double d : 5500000.000000

Page 74: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

74

2. Enumeration data type:

Enumeration data type consists of named integer constants as a list.

It start with 0(zero) by default and value is incremented by 1 for the sequential identifiers.

Enum syntax in C:

enum identifier [optional{ enumerator-list }]

Example: enum month { Jan, Feb, Mar };

/* Jan, Feb and Mar variables will be assigned to 0, 1 and 2 respectively by default */

or enum month { Jan = 1, Feb, Mar };

/* Feb and Mar variables will be assigned to 2 and 3 respectively by default */

enum month { Jan = 20, Feb, Mar };

/* Jan, Feb and Mar variables will be assigned to 20, 21 and 22 respectively by default */

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

#include <stdio.h>

int main()

{

enum MONTH { Jan = 0, Feb, Mar };

enum MONTH month = Mar;

if(month == 0)

printf("Value of Jan");

else if(month == 1)

printf("Month is Feb");

if(month == 2)

printf("Month is Mar");

}

Output: Month is March

3. Derived data type:

Array, pointer, structure and union are called derived data type.

4. Void data type:

Void is an empty data type that has no value. This can be used in functions and pointers.

2.7.1 Modifiers

The amount of memory space to be allocated for a variable is derived by modifiers. Modifiers are

prefixed with basic data types to modify (either increase or decrease) the amount of storage space

allocated to a variable. For example, storage space for int data type is 4 byte for 32 bit processor. We can increase the range by using long int which is 8 byte.

We can decrease the range by using short int which is 2 byte. There are 5 modifiers available in C language. They are,

1. short

2. long

Page 75: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

75

3. signed

4. unsigned

5. long long

Below table gives the detail about the storage size of each C basic data type in 16 bit processor.

The storage size and range for int and float will vary depend on the CPU processor (8,16, 32 and

64 bit)

S.No C Data types storage Size Range

1 char 1 –127 to 127

2 int 2 –32,767 to 32,767

3 float 4 1E–37 to 1E+37 with six digits of precision

4 double 8 1E–37 to 1E+37 with ten digits of precision

5 long double 10 1E–37 to 1E+37 with ten digits of precision

6 long int 4 –2,147,483,647 to 2,147,483,647

7 short int 2 –32,767 to 32,767

8 unsigned short int 2 0 to 65,535

9 signed short int 2 –32,767 to 32,767

10 long long int 8 –(2power(63) –1) to 2(power)63 –1

11 signed long int 4 –2,147,483,647 to 2,147,483,647

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

13 unsigned long long int 8 2(power)64 –1

sizeof () operator is used to find the memory space allocated for each C data types.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

#include <stdio.h>

#include <limits.h>

int main()

{

int a;

char b;

float c;

double d;

printf("Storage size for int data type:%d \n",sizeof(a));

printf("Storage size for char data type:%d \n",sizeof(b));

printf("Storage size for float data type:%d \n",sizeof(c));

printf("Storage size for double data type:%d \n",sizeof(d));

return 0;

}

Output:

Page 76: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

76

Storage size for int data type:4

Storage size for char data type:1

Storage size for float data type:4

Storage size for double data type:8

Key points to remember:

1. Data types define a variable in a C program. int, char, float, double and void are C basic data

types

2. int data type returns a value from function call.

3. void data type does not return any value from function call. It has no size.

4. sizeof () operator is used to find the memory space allocated for each data type

2.8 Operators and Expressions

The symbols which are used to perform logical and mathematical operations are called C

operators.

These C operators join individual constants and variables to form expressions. Operators,

functions, constants and variables are combined together to form expressions. Example: A + B * 5

where,

+, * - operators

A, B - variables

5 – constant

A + B * 5 - expression

Types of C operators:

C language offers many types of operators. They are,

1. Arithmetic operators

2. Assignment operators

3. Relational operators

4. Logical operators

5. Bit wise operators

6. Conditional operators (ternary operators)

7. Increment/decrement operators

8. Special operators

1. Arithmetic Operators:

These operators are used to perform mathematical calculations like addition, subtraction,

multiplication, division and modulus.

S.no Operator Operation

1 + Addition

2 - Subtraction

3 * multiplication

4 / Division

5 % Modulus

Page 77: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

77

Example program for C arithmetic operators:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

# include <stdio.h>

int main()

{

int a=40,b=20, add,sub,mul,div,mod;

add = a+b;

sub = a-b;

mul = a*b;

div = a/b;

mod = a%b;

printf("Addition of a, b is : %d\n", add);

printf("Subtraction of a, b is : %d\n", sub);

printf("Multiplication of a, b is : %d\n", mul);

printf("Division of a, b is : %d\n", div);

printf("Modulus of a, b is : %d\n", mod);

}

Output:

Addition of a, b is : 60

Subtraction of a, b is : 20

Multiplication of a, b is : 800

Division of a, b is : 2

Modulus of a, b is : 0

2. Assignment operators:

The values for the variables are assigned using assignment operators.

For example, if the value 10 is to be assigned for the variable sum, it can be done like below.

sum = 10;

Below are some of other assignment operators:

Operator Example Explanation

Simple operator = sum = 10 Value 10 is assigned to variable sum

Compound assignment operator

+= sum+=10 This is same as sum = sum+10

-= sum – = 10 This is same as sum = sum – 10

*= sum*=10 This is same as sum = sum*10

/+ sum/=10 This is same as sum = sum/10

%= sum%=10 This is same as sum = sum%10

&= sum&=10 This is same as sum = sum&10

^= sum^=10 This is same as sum = sum^10

Page 78: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

78

Example program for assignment operators:

1

2

3

4

5

6

7

8

9

10

# include <stdio.h>

int main()

{

int Total=0,i;

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

{

Total+=i; // This is same as Total = Toatal+i

}

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

Output

Total = 45

3. Relational operators:

These operators are used to find the relation between two variables. That is, used to compare the

value of two variables.

Operator Example

> x > y

< x < y

>= x >= y

<= x <= y

== x == y

!= x != y

Example program for relational operators:

1

2

3

4

5

6

7

8

9

10

11

#include <stdio.h>

int main()

{

int m=40,n=20;

if (m == n) {

printf("m and n are equal");

}

else {

printf("m and n are not equal");

}

}

Output:

m and n are not equal

Page 79: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

79

4. Logical operators:

These operators are used to perform logical operations on the given two variables.

Operator Example

&& x && y

|| x || y

! x (x || y), !(x && y)

Example program for logical operators:

1

2

3

4

5

6

7

8

#include <stdio.h>

int main()

{

int m=40,n=20;

if (m>n && m !=0) {

printf("m is greater than n and not equal to 0");

}

}

Output:

m is greater than n and not equal to 0

5. Bit wise operators:

These operators are used to perform bit operations on given two variables.

Truth table for bitwise operation: Bitwise operators:

x y x/y x & y x ^ y Operator Explanation

0 0 0 0 0 & Bitwise AND

0 1 1 0 1 | Bitwise OR

1 0 1 0 1 ~ Bitwise NOT

1 1 1 1 0 ^ XOR

<< Left Shift

>> Right Shift

Example program for bitwise operators:

1

2

3

4

5

6

7

8

9

10

11

12

#include <stdio.h>

int main()

{

int m=40,n=20,AND_opr,OR_opr,XOR_opr ;

AND_opr = (m&n);

OR_opr = (m|n);

XOR_opr = (m^n);

printf("AND_opr value = %d\n",AND_opr );

printf("XOR_opr value = %d\n",XOR_opr );

printf("OR_opr value = %d\n",OR_opr );

}

Page 80: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

80

Output: AND_opr value = 0

XOR_opr value = 60

OR_opr value = 60

6. Conditional operators:

Conditional operators return one value if condition is true and returns other value is condition is

false. This operator is also called as ternary operator.

Syntax :

Example: (A > 100? 0: 1);

Here, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if else

conditional statements.

Example program for conditional/ternary operators:

1

2

3

4

5

6

7

8

#include <stdio.h>

int main()

{

int x=1, y ;

y = ( x ==1 ? 2 : 0 ) ;

printf("x value is %d\n", x);

printf("y value is %d", y);

}

Output:

x value is 1

y value is 2

7. Increment and decrement operators:

These operators are used to either increase or decrease the value of the variable by one.

Syntax :

++var_name; (or)

var_name++; (or)

- - var_name; (or)

var_name- -;

Example : ++i, i++, - -i, i- -

Example program for increment operators:

1

2

3

4

5

6

7

8

9

10

11

//Example for increment operators

#include <stdio.h>

int main()

{

int i=1;

while(i<10)

{

printf("%d\n",i);

i++;

}

(Condition? true_value: false_value);

Page 81: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

81

12 }

Output:

1

2

3

4

5

6

7

8

9

Example program for decrement operators:

1

2

3

4

5

6

7

8

9

10

11

12

//Example for decrement operators

#include <stdio.h>

int main()

{

int i=20;

while(i>10)

{

printf("%d\n",i);

i--;

}

}

Output:

20

19

18

17

16

15

14

13

12

11

8. Special Operators:

Below are some of special operators that the C language offers.

S.no Operators Description

1 & This is used to get the address of the variable.

Example:&a will give address of a.

2 * This is used as pointer to a variable.

Example: * a where, * is pointer to the variable a.

3 Size of () This gives the size of the variable.

Page 82: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

82

Example: size of (char) will give us 1.

4 ternary This is ternary operator and act exactly as if … else statement.

5 Type cast Type cast is the concept of modifying variable from one data type to other.

Do you know difference between pre/post increment and pre/post decrement operators?

S.no Operator Description

1 while(i++ < 5) The value of i is compared with 5, before incrementing i value by 1.

2 while(++i < 5) The value of i is incremented by 1, before comparing with 5.

3 while(i – - < 5) The value of i is compared with 5, before decrementing i value by 1.

4 while(- - i < 5) The value of i is decremented by 1, before comparing with 5.

Example program for pre – increment operators:

1

2

3

4

5

6

7

8

9

10

11

12

//Example for increment operators

#include <stdio.h>

int main()

{

int i=0;

while(++i < 5 )

{

printf("%d\n",i);

}

return 0;

}

Output

1

2

3

4

Example program for post – increment operators:

1

2

3

4

5

6

7

8

9

10

#include <stdio.h>

int main()

{

int i=0;

while(i++ < 5 )

{

printf("%d\n",i);

}

return 0;

}

Output:

1

2

3

4

5

Page 83: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

83

Example program for pre - decrement operators:

1

2

3

4

5

6

7

8

9

10

#include <stdio.h>

int main()

{

int i=10;

while(--i > 5 )

{

printf("%d\n",i);

}

return 0;

}

Output:

9

8

7

6

Example program for post - decrement operators:

1

2

3

4

5

6

7

8

9

10

#include <stdio.h>

int main()

{

int i=10;

while(i-- > 5 )

{

printf("%d\n",i);

}

return 0;

}

Output:

9

8

7

6

5

Arithmetic Expressions

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

syntax of C language. In C every expression evaluates to a value i.e., every expression results in some

value of a certain type that can be assigned to a variable. Some examples of C expressions are shown in

the table given below.

Algebraic

Expression

C Expression

a x b – c a * b – c

Page 84: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

84

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

(ab / c) a * b / c

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

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

Evaluation of Expressions

Expressions are evaluated using an assignment statement of the form Variable = expression;

Variable is any valid C variable name. When the statement is encountered, the expression is

evaluated first and then replaces the previous value of the variable on the left hand side. All variables

used in the expression must be assigned values before evaluation is attempted.

Example of evaluation statements are x = a * b – c

y = b / c * a

z = a – b / c + d;

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

void main ()

{

float a, b, c x, y, z;

a = 9;

b = 12;

c = 3;

x = a – b / 3 + c * 2 – 1;

y = a – b / (3 + c) * (2 – 1);

z = a – ( b / (3 + c) * 2) – 1;

printf (“x = %fn”,x);

printf (“y = %fn”,y);

printf (“z = %fn”,z);

}

Output x = 10.00

y = 7.00

z = 4.00

Precedence in Arithmetic Operators

An arithmetic expression without parenthesis will be evaluated from left to right using the rules

of precedence of operators. There are two distinct priority levels of arithmetic operators in C.

High priority * / %

Low priority + -

Rules for evaluation of expression

First parenthesized sub expression left to right are evaluated.

If parentheses are nested, the evaluation begins with the innermost sub expression.

Page 85: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

85

The precedence rule is applied in determining the order of application of operators in evaluating

sub expressions.

The associability rule is applied when two or more operators of the same precedence level appear

in the sub expression.

Arithmetic expressions are evaluated from left to right using the rules of precedence.

When Parenthesis is used, the expressions within parenthesis assume highest priority.

Type conversions in expressions

Implicit type conversion

C permits mixing of constants and variables of different types in an expression.

C automatically converts any intermediate values to the proper type so that the expression

can be evaluated without losing any significance.

This automatic type conversion is known as implicit type conversion

During evaluation it adheres to very strict rules and type conversion.

If the operands are of different types the lower type is automatically converted to the

higher type before the operation proceeds.

The result is of higher type.

The following rules apply during evaluating expressions

All short and char are automatically converted to int then

If one operand is long double, the other will be converted to long double and result

will be long double.

If one operand is double, the other will be converted to double and result will be double.

If one operand is float, the other will be converted to float and result will be float.

If one of the operand is unsigned long int, the other will be converted into unsigned

long int and result will be unsigned long int.

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

.....a. If unsigned int can be converted to long int, then unsigned int operand will be

converted as such and the result will be long int.

.....b. Else both operands will be converted to unsigned long int and the result will be

unsigned long int.

If one of the operand is long int, the other will be converted to long int and the result will

be long int

If one operand is unsigned int the other will be converted to unsigned int and the result

will be unsigned int.

Explicit Conversion

Many times there may arise a situation where we want to force a type conversion in a way that is

different from automatic conversion.

Consider for example the calculation of number of female and male students in a class

female_students

Ratio = -------------------

male_students

Since if female_students and male_students are declared as integers, the decimal part will be rounded off

and its ratio will represent a wrong figure.

Page 86: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

86

This problem can be solved by converting locally one of the variables to the floating point as shown below.

Ratio = (float) female_students / male_students

The operator float converts the female_students to floating point for the purpose of evaluation of the

expression. Then using the rule of automatic conversion, the division is performed by floating point mode, thus

retaining the fractional part of the result.

The process of such a local conversion is known as explicit conversion or casting a value.

The general form is (type_name) expression

Operators Precedence in C

Operator precedence determines the grouping of terms in an expression.

This affects how an expression is evaluated.

Certain operators have higher precedence than others;

for example, the multiplication operator has higher precedence than the addition operator: For example x = 7 + 3 * 2;

Here x is assigned 13, not 20

because operator * has higher precedence than +

so it first get multiplied with 3*2 and then adds into 7.

Here operators with the highest precedence appear at the top of the table, those with the lowest

appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative * / % Left to right

Additive + - Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

2.9 MANAGING INPUT AND OUTPUT OPERATIONS :

The input and output functions are used to provide input to the program and display the result to

the user respectively. These functions are available in the header file.

There are two types of input/output functions. They are:

Page 87: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

87

1. Formatted Input/Output Functions

2. Unformatted Input/Output Functions

Formatted Input/Output Functions:

The value to these functions has to be given in a particular order. They are classified as follows:

Input Output

scanf() printf()

fscanf() fprintf()

scanf() Function:

scanf() function is used to read a character, string, numeric data from keyboard.

The general syntax for the scanf() function is as follows:

Scanf(“control string”, address of the variable)

Example:

int a;

Scanf(”%d”,&a);

where & - address of operator which fetches the address of the variable a.

Rules to be followed:

1. The control string must be given within double quotation.

Page 88: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

88

2. The variables can be separated by using comma.

3. It should be terminated by a semi colon.

4. No empty space should be given between two control strings.

printf() Function:

The printf() function is used to print the character, string, float, integer, octal and

hexadecimal values onto the output screen.

The general syntax is as follows:

Example;

int a=10;

printf(“%d”,a);

Rules for writing printf() function:

1. The variable and the control string should match.

2. The control string must be given in double quotation.

3. Any number of values can be displayed. The variables must be separated by comma.

Sample Program using scanf() and printf() functions:

#include<stdio.h>

void main()

{

int a;

printf(“\nEnter the value for a‟);

scanf(“%d”,&a);

printf(“\n The value entered is %d”,a);

}

Output:

Enter the value for a 7

The value entered is 7

fscanf() Function: This function is used to read the data from a file.

printf(“control string”, variable name);

Page 89: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

89

fprintf() Function: This function is used to write data into a file.

Unformatted Input and Output Functions:

Some of the unformatted input and output functions are given below:

Single Character Input Function:

getc(): It is used to get a single character from the standard input to a character variable. The getc()

function is often used in file processing.

Syntax:

character variable = getc();

Example :

char c;

c = getc();

getchar() : It reads a single character from the standard input device. This function does not require any

arguments, through a pair of empty parentheses.

Syntax:

character variable = getchar();

Example :

char x;

x= getchar();

Single Character Output Function:

Page 90: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

90

putc(): It is used to display a single character in a character variable to standard output device. The putc()

function is often used in file processing.

Syntax:

putc(character variable);

Example :

char c;

putc(c);

putchar() : It display one character at a time on the standard output device. This function does the reverse

operation of the single character input function.

Syntax:

putchar( character variable);

Example :

char x;

putchar(x);

Sample program for single input & output function getchar() & putchar():

#include<stdio.h>

void main()

{

char x;

printf(“Enter any alphabet either in Lower or Uppercase….”);

x=getchar();

if(islower(x))

putchar(toupper(x));

else

putchar(tolower(x));

}

Output:

1. Enter any alphabet either in Lower or Uppercase……s

S

Page 91: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

91

2. Enter any alphabet either in Lower or Uppercase……M

m

String Function gets() and puts():

gets(): It is used to read the string (string is a group of character) from the standard input device.

Syntax:

gets(char type of array variable);

Example :

char c[10];

gets(c);

puts() : It display the string to the standard output device.

Syntax:

puts(char type array variable);

Example :

char c[];

puts(c);

Sample program for gets() & puts() functions:

#include<stdio.h>

void main()

{

char x[40];

puts(“Enter String….”);

gets(x);

puts(“Print the name….”);

puts(x);

}

Output:

Enter String…… Hello

Print the name……Hello

Page 92: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

92

Specifier Meaning

%c – Print a character

%d – Print a Integer

%i – Print a Integer

%e – Print float value in exponential form.

%f – Print float value

%g – Print using %e or %f whichever is smaller

%o – Print actual value

%s – Print a string

%x – Print a hexadecimal integer (Unsigned) using lower case a – F

%X – Print a hexadecimal integer (Unsigned) using upper case A – F

%a – Print a unsigned integer.

%p – Print a pointer value

%hx – hex short

%lo – octal long

%ld – long

2.10 Control Structures in C: Normally statements in C program are executed sequentially i.e. in the order in which they are

written. This is called sequential execution. We can transfer the control point to a desired location is

possible with control structures. C allows many kinds of control statements.

I. Conditional (decision) control structures

if

if –else

if-elseif – else

nested if

II. Jumping (branching) control structures

goto

break

return

continue

III. Loop (iterative) control structures

for loop

while loop

do - while loop

IV. Multi way conditional (case) control structures

switch- case

Decision Making

Decision making structures require that the programmer specify one or more conditions to be

evaluated or tested by the program, along with a statement or statements to be executed if the condition is

determined to be true, and optionally, other statements to be executed if the condition is determined to be

false.

Following is the general from of a typical decision making structure found in most of the

programming languages:

Page 93: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

93

C programming language assumes any non-zero and non-null values as true and if it is either

zero or null then it is assumed as false value.

C programming language provides following types of decision making statements

Statement Description

if statement An if statement consists of a boolean expression followed by one or more statements.

if...else statement An if statement can be followed by an optional else statement, which executes when the

boolean expression is false.

nested if statements You can use one if or else if statement inside another if or else if statement(s).

switch statement A switch statement allows a variable to be tested for equality against a list of values.

nested switch

statements You can use one swicth statement inside another switch statement(s).

if statement An if statement consists of a boolean expression followed by one or more statements.

Syntax:

The syntax of an if statement in C programming language is:

if(boolean_expression)

{

/* statement(s) will execute if the boolean expression is true */

}

If the boolean expression evaluates to true then the block of code inside the if statement will be

executed. If boolean expression evaluates to false then the first set of code after the end of the if statement

(after the closing curly brace) will be executed.

C programming language assumes any non-zero and non-null values as true and if it is either

zero or null then it is assumed as false value.

Page 94: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

94

Flow Diagram:

Example:

#include <stdio.h>

int main ()

{

int a = 10; /* local variable definition */

if( a < 20 ) /* check the boolean condition using if statement */

{

printf("a is less than 20\n" ); /* if condition is true then print the following */

}

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

return 0;

}

Output

a is less than 20;

value of a is : 10

if...else statement An if statement can be followed by an optional else statement, which executes when the boolean

expression is false.

Syntax:

The syntax of an if...else statement in C programming language is:

if(boolean_expression)

{

Page 95: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

95

/* statement(s) will execute if the boolean expression is true */

}

else

{

/* statement(s) will execute if the boolean expression is false */

}

If the boolean expression evaluates to true then the if block of code will be executed otherwise

else block of code will be executed.

C programming language assumes any non-zero and non-null values as true and if it is either

zero or null then it is assumed as false value.

Flow Diagram:

Example:

#include <stdio.h>

int main ()

{

int a = 100; /* local variable definition */

if( a < 20 ) /* check the boolean condition */

{

printf("a is less than 20\n" ); /* if condition is true then print the following */

}

else

{

printf("a is not less than 20\n" ); /* if condition is false then print the following */

}

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

return 0;

}

Output:

a is not less than 20;

value of a is : 100

Page 96: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

96

The if...else if...else Statement An if statement can be followed by an optional else if...else statement, which is very useful to test

various conditions using single if...else if statement.

When using if, else if , else statements there are few points to keep in mind.

An if can have zero or one else's and it must come after any else if's.

An if can have zero to many else if's and they must come before the else.

Once an else if succeeds, none of the remaining else if's or else's will be tested.

Syntax:

The syntax of an if...else if...else statement in C programming language is:

if(boolean_expression 1)

{

/* Executes when the boolean expression 1 is true */

}

else if( boolean_expression 2)

{

/* Executes when the boolean expression 2 is true */

}

else if( boolean_expression 3)

{

/* Executes when the boolean expression 3 is true */

}

else

{

/* executes when the none of the above condition is true */

}

Example:

#include <stdio.h>

int main ()

{

int a = 100; /* local variable definition */

if( a == 10 ) /* check the boolean condition */

{

printf("Value of a is 10\n" ); /* if condition is true then print the following */

}

else if( a == 20 )

{

printf("Value of a is 20\n" ); /* if else if condition is true */

}

else if( a == 30 )

{

printf("Value of a is 30\n" ); /* if else if condition is true */

}

else

{

Page 97: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

97

printf("None of the values is matching\n" ); /* if none of the conditions is true */

}

printf("Exact value of a is: %d\n", a );

return 0;

}

Output

None of the values is matching

Exact value of a is: 100

nested if statements It is always legal in C programming to nest if-else statements, which means you can use one if or

else if statement inside another if or else if statement(s).

Syntax:

The syntax for a nested if statement is as follows: if( boolean_expression 1)

{

/* Executes when the boolean expression 1 is true */

if(boolean_expression 2)

{

/* Executes when the boolean expression 2 is true */

}

}

You can nest else if...else in the similar way as you have nested if statement.

Example:

#include <stdio.h>

int main ()

{

int a = 100; /* local variable definition */

int b = 200; /* local variable definition */

if( a == 100 ) /* check the boolean condition */

{

if( b == 200 ) /* if condition is true then check the following */

{

printf("Value of a is 100 and b is 200\n" ); /* if condition is true then print the following */

}

}

printf("Exact value of a is : %d\n", a );

printf("Exact value of b is : %d\n", b );

return 0;

}

Output

Page 98: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

98

Value of a is 100 and b is 200

Exact value of a is : 100

Exact value of b is : 200

switch statement A switch statement allows a variable to be tested for equality against a list of values. Each value

is called a case, and the variable being switched on is checked for each switch case.

Syntax:

The syntax for a switch statement in C programming language is as follows: switch(expression){

case constant-expression :

statement(s);

break; /* optional */

case constant-expression :

statement(s);

break; /* optional */

/* you can have any number of case statements */

default : /* Optional */

statement(s);

}

The following rules apply to a switch statement:

The expression used in a switch statement must have an integral or enumerated type, or be of a

class type in which the class has a single conversion function to an integral or enumerated type.

You can have any number of case statements within a switch. Each case is followed by the value

to be compared to and a colon.

The constant-expression for a case must be the same data type as the variable in the switch, and

it must be a constant or a literal.

When the variable being switched on is equal to a case, the statements following that case will

execute until a break statement is reached.

When a break statement is reached, the switch terminates, and the flow of control jumps to the

next line following the switch statement.

Not every case needs to contain a break. If no break appears, the flow of control will fall

through to subsequent cases until a break is reached.

A switch statement can have an optional default case, which must appear at the end of the

switch. The default case can be used for performing a task when none of the cases is true. No

break is needed in the default case.

Page 99: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

99

Flow Diagram:

Example:

#include <stdio.h>

int main ()

{

char grade = 'B'; /* local variable definition */

switch(grade)

{

case 'A' :

printf("Excellent!\n" );

break;

case 'B' :

printf("Well done\n" );

break;

case 'C' :

printf("You passed\n" );

break;

case 'D' :

printf("Better try again\n" );

break;

default :

printf("Invalid grade\n" );

}

printf("Your grade is %c\n", grade );

return 0;

}

Output Well done

Your grade is B

Page 100: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

100

nested switch statements It is possible to have a switch as part of the statement sequence of an outer switch. Even if the

case constants of the inner and outer switch contain common values, no conflicts will arise.

Syntax:

The syntax for a nested switch statement is as follows: switch(ch1) {

case 'A':

printf("This A is part of outer switch" );

switch(ch2) {

case 'A':

printf("This A is part of inner switch" );

break;

case 'B': /* case code */

}

break;

case 'B': /* case code */

}

Example:

#include <stdio.h>

int main ()

{

int a = 100; /* local variable definition */

int b = 200;

switch(a)

{

case 100:

printf("This is part of outer switch\n", a );

switch(b)

{

case 200:

printf("This is part of inner switch\n", a );

}

}

printf("Exact value of a is : %d\n", a );

printf("Exact value of b is : %d\n", b );

return 0;

}

Output This is part of outer switch

This is part of inner switch

Exact value of a is : 100

Exact value of b is : 200

Page 101: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

101

Loops

There may be a situation when you need to execute a block of code several number of times. In

general statements are executed sequentially: The first statement in a function is executed first, followed

by the second, and so on.

Programming languages provide various control structures that allow for more complicated

execution paths.

A loop statement allows us to execute a statement or group of statements multiple times and

following is the general from of a loop statement in most of the programming languages:

C programming language provides following types of loop to handle looping requirements.

Loop Type Description

while loop Repeats a statement or group of statements while a given condition is true. It tests the condition

before executing the loop body.

for loop Execute a sequence of statements multiple times and abbreviates the code that manages the loop

variable.

do...while loop Like a while statement, except that it tests the condition at the end of the loop body

nested loops You can use one or more loop inside any another while, for or do..while loop.

Loop Control Statements:

Loop control statements change execution from its normal sequence. When execution leaves a

scope, all automatic objects that were created in that scope are destroyed.

C supports the following control statements.

Control Statement Description

break statement Terminates the loop or switch statement and transfers execution to the

statement immediately following the loop or switch.

Page 102: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

102

continue statement Causes the loop to skip the remainder of its body and immediately retest its

condition prior to reiterating.

goto statement Transfers control to the labeled statement. Though it is not advised to use goto

statement in your program.

The Infinite Loop:

A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally

used for this purpose. Since none of the three expressions that form the for loop are required, you can

make an endless loop by leaving the conditional expression empty.

#include <stdio.h>

int main ()

{

for( ; ; )

{

printf("This loop will run forever.\n");

}

return 0;

}

When the conditional expression is absent, it is assumed to be true. You may have an

initialization and increment expression, but C programmers more commonly use the for(;;) construct to

signify an infinite loop.

NOTE: You can terminate an infinite loop by pressing Ctrl + C keys.

while loop

A while loop statement in C programming language repeatedly executes a target statement as

long as a given condition is true.

Syntax:

The syntax of a while loop in C programming language is: while(condition)

{

statement(s);

}

Here statement(s) may be a single statement or a block of statements. The condition may be any

expression, and true is any nonzero value. The loop iterates while the condition is true.

When the condition becomes false, program control passes to the line immediately following the

loop.

Page 103: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

103

Flow Diagram:

Here key point of the while loop is that the loop might not ever run. When the condition is tested

and the result is false, the loop body will be skipped and the first statement after the while loop will be

executed.

Example:

#include <stdio.h>

int main ()

{

int a = 10; /* local variable definition */

while( a < 20 ) /* while loop execution */

{

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

a++;

}

return 0;

}

Output value of a: 10

value of a: 11

value of a: 12

value of a: 13

value of a: 14

value of a: 15

value of a: 16

value of a: 17

value of a: 18

value of a: 19

Page 104: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

104

for loop

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to

execute a specific number of times.

Syntax:

The syntax of a for loop in C programming language is: for ( init; condition; increment )

{

statement(s);

}

Here is the flow of control in a for loop:

1. The init step is executed first, and only once. This step allows you to declare and initialize any

loop control variables. You are not required to put a statement here, as long as a semicolon

appears.

2. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the

body of the loop does not execute and flow of control jumps to the next statement just after the

for loop.

3. After the body of the for loop executes, the flow of control jumps back up to the increment

statement. This statement allows you to update any loop control variables. This statement can be

left blank, as long as a semicolon appears after the condition.

4. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself

(body of loop, then increment step, and then again condition). After the condition becomes false,

the for loop terminates.

Flow Diagram:

Page 105: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

105

Example:

#include <stdio.h>

int main ()

{

for( int a = 10; a < 20; a = a + 1 ) /* for loop execution */

{

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

}

return 0;

}

Output value of a: 10

value of a: 11

value of a: 12

value of a: 13

value of a: 14

value of a: 15

value of a: 16

value of a: 17

value of a: 18

value of a: 19

do...while

Unlike for and while loops, which test the loop condition at the top of the loop, the do...while

loop in C programming language checks its condition at the bottom of the loop.

A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute

at least one time.

Syntax:

The syntax of a do...while loop in C programming language is: do

{

statement(s);

}while( condition );

Notice that the conditional expression appears at the end of the loop, so the statement(s) in the

loop execute once before the condition is tested.

If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop

execute again. This process repeats until the given condition becomes false.

Page 106: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

106

Flow Diagram:

Example:

#include <stdio.h>

int main ()

{

int a = 10; /* local variable definition */

do /* do loop execution */

{

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

a = a + 1;

}while( a < 20 );

return 0;

}

Output: value of a: 10

value of a: 11

value of a: 12

value of a: 13

value of a: 14

value of a: 15

value of a: 16

value of a: 17

value of a: 18

value of a: 19

nested loops

C programming language allows to use one loop inside another loop. Following section shows

few examples to illustrate the concept.

Syntax:

The syntax for a nested for loop statement in C is as follows: for ( init; condition; increment )

{

for ( init; condition; increment )

{

statement(s);

}

Page 107: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

107

statement(s);

}

The syntax for a nested while loop statement in C programming language is as follows: while(condition)

{

while(condition)

{

statement(s);

}

statement(s);

}

The syntax for a nested do...while loop statement in C programming language is as follows: do

{

statement(s);

do

{

statement(s);

}while( condition );

}while( condition );

A final note on loop nesting is that you can put any type of loop inside of any other type of loop.

For example a for loop can be inside a while loop or vice versa.

Example:

The following program uses a nested for loop to find the prime numbers from 2 to 100: #include <stdio.h>

int main ()

{

int i, j; /* local variable definition */

for(i=2; i<100; i++) {

for(j=2; j <= (i/j); j++)

if(!(i%j)) break; // if factor found, not prime

if(j > (i/j)) printf("%d is prime\n", i);

}

return 0;

}

Output: 2 is prime

3 is prime

5 is prime

7 is prime

11 is prime

13 is prime

17 is prime

19 is prime

23 is prime

29 is prime

31 is prime

Page 108: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

108

37 is prime

41 is prime

43 is prime

47 is prime

53 is prime

59 is prime

61 is prime

67 is prime

71 is prime

73 is prime

79 is prime

83 is prime

89 is prime

97 is prime

break statement

The break statement in C programming language has following two usage:

1. When the break statement is encountered inside a loop, the loop is immediately

terminated and program control resumes at the next statement following the loop.

2. It can be used to terminate a case in the switch statement (covered in the next

chapter).

If you are using nested loops ( ie. one loop inside another loop), the break statement will stop the

execution of the innermost loop and start executing the next line of code after the block.

Syntax:

The syntax for a break statement in C is as follows: break;

Flow Diagram:

Example:

#include <stdio.h>

int main ()

{

int a = 10; /* local variable definition */

while( a < 20 ) /* while loop execution */

{

Page 109: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

109

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

a++;

if( a > 15)

{

break; /* terminate the loop using break statement */

}

}

return 0;

}

Output: value of a: 10

value of a: 11

value of a: 12

value of a: 13

value of a: 14

value of a: 15

continue statement

The continue statement in C programming language works somewhat like the break statement.

Instead of forcing termination, however, continue forces the next iteration of the loop to take place,

skipping any code in between.

For the for loop, continue statement causes the conditional test and increment portions of the

loop to execute. For the while and do...while loops, continue statement causes the program control

passes to the conditional tests.

Syntax:

The syntax for a continue statement in C is as follows: continue;

Flow Diagram:

Example:

#include <stdio.h>

int main ()

{

int a = 10; /* local variable definition */

Page 110: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

110

do /* do loop execution */

{

if( a == 15)

{

a = a + 1; /* skip the iteration */

continue;

}

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

a++;

}while( a < 20 );

return 0;

}

Output: value of a: 10

value of a: 11

value of a: 12

value of a: 13

value of a: 14

value of a: 16

value of a: 17

value of a: 18

value of a: 19

goto statement

A goto statement in C programming language provides an unconditional jump from the goto to a

labeled statement in the same function.

NOTE: Use of goto statement is highly discouraged in any programming language because it makes

difficult to trace the control flow of a program, making the program hard to understand and hard to

modify. Any program that uses a goto can be rewritten so that it doesn't need the goto.

Syntax:

The syntax for a goto statement in C is as follows: goto label;

..

.

label: statement;

Here label can be any plain text except C keyword and it can be set anywhere in the C program

above or below to goto statement.

Page 111: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

111

Flow Diagram:

Example:

#include <stdio.h>

int main ()

{

int a = 10; /* local variable definition */

LOOP:do /* do loop execution */

{

if( a == 15)

{

a = a + 1; /* skip the iteration */

goto LOOP;

}

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

a++;

}while( a < 20 );

return 0;

}

Output: value of a: 10

value of a: 11

value of a: 12

value of a: 13

value of a: 14

value of a: 16

value of a: 17

value of a: 18

value of a: 19

2.11 Solving simple scientific and statistical problems

Page 112: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

112

Program to evaluate Sine Series, Cosine Series and Exponential Series?

Sine series : sin x = x - ((x^3)/3!) + ((x^5)/5!) - …………..

Cosine Series : cos x = 1 - ((x^2)/2!) + ((x^4)/4!) -…………...

Exponential Series : e^x = 1 + (x/1!) + ((x^2)/2!) + ((x^3)/3!)+…….

#include<stdio.h>

#include<conio.h>

void main()

{

int i,n,j,ch;

float x,t,s,r;

char c='y';

clrscr();

do

{

printf("\n1.Sine Series");

printf("\n2.Cosine Series");

printf("\n3.Exponential Series");

printf("\n Enter The Choice");

scanf("%d",&ch);

switch(ch)

{

case 1:

printf("\n Enter The Limit");

scanf("%d",&n);

printf("\n Enter The Value Of x:");

scanf("%f",&x);

r=((x*3.1415)/180);

t=r;

s=r;

i=2;

for(j=2;j<=n;j++)

{

t=(t*(-1)*r*r)/(i*(i+1));

s=s+t;

i=i+2;

}

printf("\n Sum Of The Given Sine Series Is %4f",s);

break;

case 2:

printf("\n Enter The Limit ");

scanf("%d",&n);

printf("\n Enter The Value Of x:");

scanf("%f",&x);

r=((x*3.14)/180);

t=1;

s=1;

i=1;

for(j=2;j<=n;j++)

{

Page 113: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

113

t=((-1)*t*r*r)/(i*(i+1));

s=s+t;

i=i+2;

}

printf("\n Sum Of The Cosine Series Is %f",s);

break;

case 3:

printf("\n Enter The Limit");

scanf("%d",&n);

printf("\n Enter The Value Of x:");

scanf("%f",&x);

t=1;

s=1;

for(i=1;i<n;i++)

{

t=(t*x)/i;

s=s+t;

}

printf("\n Sum Of Exponential Series Is %f",s);

break;

default:

printf("\n Wrong Choice");

}

printf("\n Do U Want To Continue Y/N");

scanf("%c",&c);

}

while(c=='y');

getch();

}

Output

1.Sine Series

2.Cosine Series

3.Exponential Series

Enter The Choice 1

Enter The Limit 2

Enter The Value Of x:60

Sum Of The Given Sine Series Is 0.855787

Do U Want To Continue Y/N y

1.Sine Series

2.Cosine Series

3.Exponential Series

Enter The Choice 2

Enter The Limit 2

Enter The Value Of x:60

Page 114: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

114

Sum Of The Cosine Series Is 0.452245

Do U Want To Continue Y/N y

1.Sine Series

2.Cosine Series

3.Exponential Series

Enter The Choice 3

Enter The Limit 2

Enter The Value Of x:3

Sum Of Exponential Series Is 4.000000

Do U Want To Continue Y/N n

Program to generate,first n number of elements in the Fibonacci series

#include<stdio.h>

#include<conio.h>

void main()

{

int n,i=0,j=1,temp,k;

clrscr();

printf("Enter the limit: ");

scanf("%d",&n);

printf("Fibonacci series\n");

if(n==1)

{

printf("%d\n%d\n",i,j);

}

else

{

printf("%d\n%d\n",i,j);

for(k=2;k<n;k++)

{

temp=i+j;

printf("%d\n",temp);

i=j;

j=temp;

}

}

getch();

}

Output

Page 115: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

115

Enter the limit:13

Fibonacci series

0

1

1

2

3

5

8

13

21

34

55

89

144

Program to generate Armstrong number within a limit

Armstrong number: 153=13+5

3+3

3

#include<stdio.h>

#include<conio.h>

void main()

{

int i,r,n,sum=0,temp;

clrscr();

printf("Enter the limit :");

scanf("%d",&n);

for(i=1;i<n;i++)

{

temp=i;

sum=0;

while(temp!=0)

{

r=temp%10;

sum=sum+(r*r*r);

temp=temp/10;

}

if(i==sum)

{

Page 116: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

116

printf("\n%d",i);

}

getch();

}

Output:

Enter the limit :500

1

153

370

371

407

Program to print Floyd's Triangle

1

2 3

4 5 6

7 8 9 10

#include <stdio.h>

int main()

{

int n, i, c, a = 1;

printf("Enter the number of rows of Floyd's triangle to print\n");

scanf("%d", &n);

for (i = 1; i <= n; i++)

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

{

printf("%d ",a);

a++;

}

printf("\n");

}

return 0;

}

Output

Enter the limit :4

1

2 3

Page 117: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

117

4 5 6

7 8 9 10

Program to calculate roots of a quadratic equation #include<stdio.h>

#include<math.h>

int main(){

float a,b,c;

float d,root1,root2;

printf("Enter a, b and c of quadratic equation: ");

scanf("%f%f%f",&a,&b,&c);

d = b * b - 4 * a * c;

if(d < 0){

printf("Roots are complex number.\n");

printf("Roots of quadratic equation are: ");

printf("%.3f%+.3fi",-b/(2*a),sqrt(-d)/(2*a));

printf(", %.3f%+.3fi",-b/(2*a),-sqrt(-d)/(2*a));

return 0;

}

else if(d==0){

printf("Both roots are equal.\n");

root1 = -b /(2* a);

printf("Root of quadratic equation is: %.3f ",root1);

return 0;

}

else{

printf("Roots are real numbers.\n");

root1 = ( -b + sqrt(d)) / (2* a);

root2 = ( -b - sqrt(d)) / (2* a);

printf("Roots of quadratic equation are: %.3f , %.3f",root1,root2);

}

return 0;

}

Output:

Enter a, b and c of quadratic equation: 2 4 1

Roots are real numbers.

Roots of quadratic equation are: -0.293, -1.707

Page 118: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

118

Program to compute the value of a given position in Pascal's Triangle

#include <stdio.h>

int main()

{

int n, x, y, c, q;

printf("Pascal Triangle Program\n");

printf("Enter the number of rows: ");

scanf("%d",&n);

for (y = 0; y < n; y++)

{

c = 1;

for(q = 0; q < n - y; q++)

{

printf("%3s", " ");

}

for (x = 0; x <= y; x++)

{

printf(" %3d ",c);

c = c * (y - x) / (x + 1);

}

printf("\n");

}

printf("\n");

return 0;

}

Output: Pascal Triangle Program

Enter the number of rows: 11

1

1 1

1 2 1

1 3 3 1

1 4 6 4 1

1 5 10 10 5 1

1 6 15 20 15 6 1

1 7 21 35 35 21 7 1

1 8 28 56 70 56 28 8 1

1 9 36 84 126 126 84 36 9 1

1 10 45 120 210 252 210 120 45 10 1

Page 119: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

119

Program to compute the sum of 1 + 2 + …. + n series #include<stdio.h>

#include<conio.h>

void main()

{

int n,i;

int sum=0;

clrscr();

printf("Enter the value of n i.e. max values of series: ");

scanf("%d",&n);

sum = (n * (n + 1)) / 2;

printf("Sum of the series: ");

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

if (i!=n)

printf("%d + ",i);

else

printf("%d = %d \n ",i,sum);

}

getch();

}

Output: Enter the n i.e. max values of series: 5

Sum of the series: 1 + 2 + 3 + 4 + 5 = 15

Program to compute the sum of series 1+X+ X^2 + X^3+. . . +X^N

#include<stdio.h>

#include<conio.h>

void main()

{

int x,n,t;

long sum=1;

clrscr();

printf("Enter the value of 'x': ");

scanf("%d",&x);

printf("\nEnter the value of 'n': ");

Page 120: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

120

scanf("%d",&n);

t=x;

while(n>0)

{

sum=sum+t;

t=t*x;

n--;

}

printf("\n Sum of the series=%ld",sum);

getch();

}

Output:

Enter the value of 'x': 5

Enter the value of 'n': 6

Sum of the series= 19531

Program to calculate the following Sum: Sum=1-x2/2! +x4/4!-x6/6!+x8/8!-x10/10!

#include <stdio.h>

#include<conio.h>

#include <math.h>

void main()

{

int counter,f_coun;

float sum=0,x,power,fact;

clrscr();

printf("Program For Sum Of Series");

printf("\n Equation Series : 1-X^2/2! + X^4/4!-X^6/6! + X^8/8!-X^10/10!");

printf("\n Enter Value Of X : ");

scanf("%f",&x);

for(counter=0, power=0; power<=10; counter++,power=power+2)

{

fact=1;

//CALC FACTORIAL OF POWER VALUE

for(f_coun=power; f_coun>=1; f_coun--)

fact *= f_coun;

//EQ. FOR SUM SERIES

sum=sum+(pow(-1,counter)*(pow(x,power)/fact));

}

printf("Sum : %f",sum);

getch();

}

Output:

Page 121: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

121

Program For Sum Of Series

Equation Series : 1-X^2/2! + X^4/4!-X^6/6! + X^8/8!-X^10/10!

Enter Value Of X : 6

Sum : -2.805714

Program to find the Sum of Series X-X3/3!+X5/5!-X7/7!+...

#include<stdio.h>

#include<conio.h>

void main()

{

longint x,i,j,k,n,sq,cnt;

double fact,sum=0;

clrscr();

printf("\n ENTER THE VALUE OF N: ");

scanf("%ld",&n);

printf("\n ENTER THE VALUE OF X: ");

scanf("%ld",&x);

for(i=1,cnt=1;i<=n;i=i+2,cnt++)

{

for(j=1,sq=1;j<=i;j++)

sq=sq*x;

printf("\n SQ = %ld",sq);

for(k=1,fact=1;k<=i;k++)

fact=fact*k;

printf("\n fact = %7.2lf",fact);

if(cnt%2==1)

sum=sum+(sq/fact);

else

sum=sum-(sq/fact);

printf("\n THE SUM OF THIS SERIES IS %7.2lf\n",sum);

}

getch();

}

Output:

ENTER THE VALUE OF N: 5

ENTER THE VALUE OF X: 2

SQ = 2

fact = 1.00

THE SUM OF THIS SERIES IS 2.00

SQ = 8

Page 122: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

122

fact = 6.00

THE SUM OF THIS SERIES IS 0.67

SQ = 32

fact = 120.00

THE SUM OF THIS SERIES IS 0.93

Program to find answer of the following series. Sum=E1+E2+E3+...

#include<stdio.h>

#include<conio.h>

#include<math.h>

void main()

{

longint i,n;

double sum=0;

clrscr();

printf("\n Enter The Value Of N: ");

scanf("%ld",&n);

for(i=1;i<=n;i++)

sum=sum+exp(i);

textcolor(RED);

printf("\n");

cprintf(" The Sum Of This Series Is %7.2lf\n",sum);

getch();

}

Output:

Enter The Value Of N: 5

The Sum Of This Series Is 233.20

GE6151 – COMPUTER PROGRAMMING

UNIT II C PROGRAMMING BASICS

Problem formulation – Problem Solving - Introduction to „ C‟ programming –fundamentals – structure of

a „C‟ program – compilation and linking processes – Constants, Variables – Data Types – Expressions

using operators in „C‟ – Managing Input and Output operations – Decision Making and Branching –

Looping statements – solving simple scientific and statistical problems.

2.1 Problem Formulation

Before attempting to solve a problem, we need to first formulate or define the problem.

It is important to precisely define the problem you intend to solve.

Page 123: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

123

The more difficult it is to define the problem, the harder you have to try.

Why?

A problem formulation is/can be a question or something you are wondering about.

The problem should be something you can solve/give answers to.

A conclusion in an analysis is always the answer to the problem formulation.

Different types of problem formulation:

"What” - descriptive

"Why” - explanatory

"How” - normative

Case

A company has trouble integrating new employees.

What

is what you call a descriptive problem formulation - it describes a problem!

Example: What kind of problems appear for the company and the employee in the

beginning of the employment?

Why

is the explanatory problem formulation - it wants to explain a problem!

Example: Why does it seems that the employees have trouble adapting the culture in the

organisation?

How

is the normative problem formulation - it tries to solve a problem!

Example: How can the company make sure that the new employees get all the support

they need?

Hypothesis

A problem formulation can be in the form of a hypothesis.

The company is hiring the wrong kind of people.

2.2 Problem Solving

A systematic approach to defining the problem (question or situation that presents uncertainty,

perplexity or difficulty) and creating a vast number of possible solutions without judging these solutions.

Problem solving is the mental process you follow when you have a goal but can‟t immediately

understand how to achieve it. It‟s a process that depends on you – how you perceive a problem, what you

know about it, and the end-state you want to reach.

Solving a problem involves a number of cognitive activities:

ascertaining what the problem really is

identifying the true causes of your problem and the opportunities for reaching your goal

generating creative solutions to the problem

evaluating and choosing the best solution, and

implementing the best solution, then monitoring your actions and their results to ensure the

problem is solved successfully

Clearly, problem solving isn‟t a one-step process. Your success will depend on whether you

approach and implement each of the stages effectively. The best way to do this is to use a well-

established, systematic problem-solving model.

Page 124: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

124

2.2.1 The six steps of problem solving

Problems vary widely, and so do their solutions. Sometimes a problem and its solution are clear,

but you don‟t know how to get from point A to point B. At other times, you may find it hard to define

what‟s wrong or how to fix it. Regardless of what a problem is, you can use a six-step problem-solving

model to address it. This model is highly flexible and can be adapted to suit various types of problems. It

also comes with a flexible set of tools to use at each step. The model is designed to be followed one step

at a time, but you may find that some stages don‟t require as much attention as others. This will depend

on your unique situation.

The steps in the problem-solving model are as follows:

7. Define the problem –

Clearly state the problem

Identify what circumstances lead to the cause of the problem.

Write a clear definition of the problem and the barriers encountered.

8. Analyze the problem –

Decide what type of problem it is.

Dig to the root causes of the problem, and detail the nature of the gap between where you

are and where you want to be.

The five-why analysis is a tool that‟ll help you get to the heart of the problem.

1. Ask “Why?” a number of times to dig through each layer of symptoms and so to

arrive at the problem‟s root cause.

2. You can get to the root of a more complicated problem using a cause-and-effect

diagram.

3. A cause is something that produces an effect, result, or consequence – or what

contributed to the current state of affairs.

4. Categories of causes include people, time, and the environment.

9. Identify as many potential solutions as you can –

1. Brainstorm creatively – ask lots of questions about who, what, where, when, and how of

the causes to point to various possibilities.

2. Don‟t limit yourself by considering practicalities at this stage;

3. Simply record your ideas.

10. Choose the best solution –

1. In evaluating your ideas, more options could present themselves.

2. You could do this by rating each possible solution you came up with in step 3 according

to criteria such as

1. how effective it will be,

2. how much time or effort it will take,

3. its cost, and

4. How likely it is to satisfy stakeholders.

11. Plan of action – 1. During this step, you determine what steps must be taken, designating tasks where

necessary.

2. And you decide on deadlines for completing the actions and estimate the costs of

implementing them.

3. You also create a contingency plan in case of unforeseen circumstances so that if

anything goes wrong with your plan, you have a “plan B” in place.

Page 125: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

125

4. Typically, this stage involves narrowing down the possible ways to implement the

solution you‟ve chosen, based on any constraints that apply.

5. You also should draw up an action plan.

6. The complexity of the plan will depend on the situation, but it should include the who,

what, and when of your proposed solution.

12. Implement the solution –

1. This is an ongoing process.

2. You need to ensure the required resources remain available and monitor progress in

solving the problem; otherwise, all the work you‟ve done might be for nothing.

This model is highly adaptable. Although you shouldn‟t skip any of the six steps, you can tailor

the amount of time you spend on each stage based on the demands of your unique situation.

The six-step problem-solving model, and the tools it provides, is an effective, systematic

approach to problem solving. By following each step consciously, you can ensure that generating

solutions is a fact-driven, objective, and reliable process. It encourages you to dig deeper to the root

cause, allows you to get input from others, to be creative when finding solutions, and to monitor your

solutions to make sure they‟re working. So by following this model you‟re more likely to come up with

good, original, lasting solutions.

To solve problems effectively, you need to use a good problem-solving model. The six-step

model is a tried-and-tested approach. Its steps include defining a problem, analyzing the problem,

identifying possible solutions, choosing the best solution, planning your course of action, and finally

implementing the solution while monitoring its effectiveness.

2.3 Introduction to C

What is a programming language?

--Human beings need language to communicate between them. Similarly to communicate

with computers we need a programming language. All the events in life can be communicated to

computers with the help of programming language. C is the basic of all programming language. Before

the introduction of C we had only Machine level languages. C is just like any other communication

Language.

2.3.1 History of C

C language is a structure oriented programming language, was developed at Bell Laboratories in

1972 by Dennis Ritchie

C features were derived from earlier language called “B” (BCPL language)

C was invented for implementing UNIX operating system

In 1978, Dennis Ritchie and Brian Kernighan published the first edition “The C Programming

Language” and commanly known as K&R C

In 1983, the American National Standards Institute (ANSI) established a committee to provide a

modern, comprehensive definition of C. The resulting definition, the ANSI standard, or “ANSI

C”, was completed late 1988.

C standards

C89/C90 standard – First standardized specification for C language was developed by American

National Standards Institute in 1989. C89 and C90 standards refer to the same programming

language.

Page 126: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

126

C99 standard – Next revision was published in 1999 that introduced new futures like advanced

data types and other changes.

2.3.2 Features of C

Low Level Features :

­ C Programming provides low level features that are generally provided by the Lower

level languages. C is closely related to Lower level Language such as “Assembly

Language“.

­ It is easier to write assembly language codes in C programming.

Portability :

­ C Programs are portable i.e. they can be run on any Compiler with little or no

modification

­ Compiler and Preprocessor make it Possible for C Program to run it on different PC

Powerful

­ Provides Wide variety of „Data Types„

­ Provides Wide variety of „Functions‟

­ Provides useful Control & Loop Control Statements

Bit Manipulation

­ C Programs can be manipulated using bits. We can perform different operations at bit

level. We can manage memory representation at bit level. [Eg. We can use Structure to

manage Memory at Bit Level]

­ It provides wide verity of bit manipulation Operators. We have bitwise operators to

manage data at bit level.

High Level Features

­ It is more User friendly as compare to previous languages. Previous languages such as

BCPL, Pascal and other programming languages never provide such great features to

manage data.

­ Previous languages have their pros and cons but C Programming collected all useful

features of previous languages thus C become more effective language.

Modular Programming

­ Modular programming is a software design technique that increases the extent to which

software is composed of separate parts, called modules.

­ C Program Consist of Different Modules that are integrated together to form complete

program

Efficient Use of Pointers

­ Pointers have direct access to memory.

­ C Supports efficient use of pointer.

More Efficient

2.3.3 Application of C Programming

Page 127: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

127

Application of C Programming are listed below -

C language is used for creating computer applications.

Used in writing Embedded softwares.

Firmware for various electronics, industrial and communications products which use micro-

controllers.

It is also used in developing verification software, test code,simulators etc. for various

applications and hardware products.

For Creating Compiles of different Languages which can take input from other language and

convert it into lower level machine dependent language.

C is used to implement different Operating System Operations.

UNIX kernel is completely developed in C Language.

2.3.4 Language Level

Which level the C language belonging to?

S.no High Level Middle Level Low Level

1

High level languages

provides almost everything

that the programmer might

need to do as already built

into the language

Middle level languages don‟t

provide all the built-in functions

found in high level languages,

but provides all building blocks

that we need to produce the

result we want

Low level

languages provides

nothing other than

access to the

machines basic

instruction set

2

Examples:Ada, BASIC,

COBOL,

FORTRAN, Modula-2

C, C++, JAVA,

FORTH, Macro-Assembler Assembler

C is categorized as middle as well as higher level language.

C is called as middle level language because :

­ It allows the manipulation of bits, bytes and address directly.

­ It allows assembly language programs.

­ It performs almost no run-time error checking.

­ It is not strongly typed language; it permits almost all type conversion.

­ It has only 32 keywords.

C is called as higher level language because :

­ It allows human readable source code (English) while writing the programs.

Page 128: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

128

C is a structured language

S.no Structure oriented Object oriented Non structure

1

In this type of language, large programs

are divided into small programs called

functions

In this type of language, programs are

divided into objects

There is no specific structure

for programming this language

2 Prime focus is on functions and

procedures that operate on data

Prime focus is on the data that is

being operated and not the functions

or procedures

N/A

3 Data moves freely around the systems

from one function to another

Data is hidden and cannot be

accessed by external functions N/A

4 Program structure follows “Top Down

Approach”

Program structure follows “Bottom

UP Approach” N/A

5 Examples: BASIC, COBOL,

FORTRAN C, C++, JAVA, Ada, Pascal Assembler

Key points to remember:

5. C is structured, middle level programming language developed by Dennis Ritchie

6. Operating system programs such as Windows, Unix, Linux are wriiten by C language

7. C89/C90 and C99 are two standardized editions of C

8. C has been written in assembly language

Page 129: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

129

2.4 Basic Structure of C Program

The basic structure of C is defined by set of rules called protocol, to be followed by

programmer while writing C program. Below is the C basic structure.

The documentations section

Consists of comment lines giving the name of the program, the author and other

details which the programmer would like to use later.

These comments beginning with the two Characters “\*” and ending with the

characters “*\” for a multi line comment and “\\” for a single line comment

Comments are helpful in identifying the program features

Not executable

The Preprocessor Section

o The link section Provides to the compiler the link functions from the system library

For Example: #include<stdio.h>

o The definition section Defines all symbolic constants.

To define macros, for example #define A 10

To define conditional inclusions, for example #ifdef

Global declaration section There are some variables that are used in one or more functions throughout the program, such

variables are called global variables and are declared in the global declaration section that is outside of

all the functions before main().

A 'C' program can be viewed as a group of building blocks called functions. A function is a sub-

routine that may include one or more statements designed to perform a specific task. To write a 'C'

program we first create functions and then put them together. A 'C' program may contain a one or more

sections as given below.

Main function section //Must

{

Declaration part

Executable part.

}

Documentation Section //optional

Link section //optional

Defining section //optional

Global declaration section //optional

Page 130: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

130

Sub program section //optional

Function 1

Function 2

…… Function n

Every C program must have one main () function section.

This section can contain two parts:

Declaration part

The declaration part declares all the variables used in the executable part.

Execution part

There is at least one statement in the executable part which contains instructions to

perform certain task.

The declaration and executable part must appear between the opening and closing braces. The

program execution begins at the opening braces and ends at the closing braces. The closing brace of

the function section is the logical end of the program.

All statements in the declaration and executable parts end with a semicolon.

The sub program section contains all the user defined functions that are called in the main ()

function. User defined functions are generally placed immediately after the main function.

Example:

1. /*Documentation Section : Program to find the area of circle */

2. #include<stdio.h> /* link section */

3. #include<conio.h> /* link section */

4. #define PI 3.14 /* definition section */

5. float area; /* global declaration section */

6. void main()

7. {

8. float r; /* declaration part */

9. clrscr();

10. printf(“Enter the radius of the circle \n”); /*executable part starts here */

11. scanf(“%f”,&r);

12. area=PI*r*r;

13. printf(“Area of the circle = %f”,area);

14. getch();

15. }

2.4.1 Writing First C Program

C Programming Introduction: Tips

Every C Program should have exactly one main function.

C Program Execution Always Starts from main.

Execution of C Program begins at Opening brace of function and ends at closing brace

of the function.

Generally all statements in c are written in Lowercase Letters.

Uppercase Letters are used for Symbolic names, output strings and messages.

Page 131: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

131

Every C statement must ends with semicolon.

All variables must be declared with respective data types before using.

C is free form-Language.

Comments can be inserted anywhere in C Program, but nested comments are not

supported by C.

Braces are Generally Used for the Grouping of statements

Key points to remember:

3. Execution of every C program starts from main() function.

4. Protocol is set of rules to be followed by a programmer to write a program.

2.5 Compiling and Linking

Preprocessing:

The program is first given to a preprocessor, which obeys commands that begin with #

(known as directives).

#include <stdio.h> (include the info in <stdio.h> before compiling)

Compiling:

The modified program now goes to a compiler, which translates it into machine

instructions (object code).

Linking:

A linker combines the object code produced by the compiler with any additional code

needed to yield a complete executable program.

test.c --> (compiled) --> test.obj (linked) --> executable file

Step By Step Execution : C Program

Step 1 : Edit

This is First Step i.e. Creating and Editing Program.

First Write C Program using Text Editor , such as [ *Borland C/C++ 3.0* ,

Notepad++,Notepad ]

Save Program by using [.C] Extension.

File Saved with [.C] extension is called “Source Program”.

Step 2: Compiling

Compiling C Program: C Source code with [.C] Extension is given as input to

compiler and compiler converts it into Equivalent Machine Instruction.

In Borland C/C++ 3.0 program can be compiled using key [Alt + F9 ].

Compiler Checks for errors. If source code is error-free then code is converted

into Object File [.Obj ].

Step 3: Checking Errors

During Compilation Compiler will check for error, if compiler finds any error

then it will report it.

Users have to re-edit the program.

After re-editing program, Compiler again check for any error.

If program is error-free then program is linked with appropriate libraries.

Page 132: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

132

Step 4 : Linking Libraries

Program is linked with included header files.

Program is linked with other libraries.

This process is executed by Linker.

Step 5 : Error Checking

If run time error occurs then “Run-time” errors are reported to user.

Again programmer have to review code and check for the solution.

2.6 Tokens

C Tokens: These are the basic buildings blocks in C language which are constructed together to

write a C program.

Page 133: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

133

Each and every smallest individual unit in a C program is known as C Tokens.

C Tokens are of six types.

Keywords (eg: int, while),

Identifiers (eg: main, total),

Constants (eg: 10, 20),

Strings (eg: “total”, “hello”),

Special symbols (eg: (), {}),

Operators (eg: +, /,-,*)

2.6.1 Character set

Character set are the set of alphabets, letters and some special characters that are valid in C

language.

Alphabets:

Uppercase: A B C.................................... X Y Z

Lowercase: a b c...................................... x y z

Digits:

0 1 2 3 4 5 6 7 8 9

Special Characters:

Special Characters in C language

, < > . _ ( ) ; $ : % [ ] # ?

' & { } " ^ ! * / | - \ ~ +

White space Characters:

Blank space, new line, horizontal tab, carriage return and form feed

2.6.2 Keywords

Keywords are the reserved words used in programming. Each keywords has fixed meaning and

that cannot be changed by user. For example: int money;

Here, int is a keyword that indicates, 'money' is of type integer.

As C programming is case sensitive, all keywords must be written in lowercase.

Keywords in C Language

auto double int struct

break else long switch

case enum register typedef

char extern return union

Page 134: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

134

continue for signed void

do if static while

default goto sizeof volatile

const float short unsigned

2.6.3 Identifiers

Each program elements in a C program are given a name called identifiers.

Names given to identify Variables, functions and arrays are examples for identifiers For example:

int money;

int mango_tree;

Here, money is a identifier which denotes a variable of type integer. Similarly,

mango_tree is another identifier, which denotes another variable of type integer.

Rules for constructing identifier name:

First character should be an alphabet or underscore. But, it is discouraged to start an identifier

name with an underscore though it is legal. It is because, identifier that starts with underscore can

conflict with system names. In such cases, compiler will complain about it. Some system names

that start with underscore are _fileno, _iob, _wfopen etc.

Succeeding characters might be digits or letter.

Punctuations and special characters aren‟t allowed except underscore.

Identifiers should not be keywords.

There is no rule for the length of an identifier. However, the first 31 characters of an identifier

are discriminated by the compiler. So, the first 31 letters of two identifiers in a program should be

different.

Declaring & initializing C variable:

Variables should be declared in the C program before to use.

Memory space is not allocated for a variable while declaration. It happens only on variable

definition.

Variable initialization means assigning a value to the variable.

S.No Type Syntax Example

1 Variable declaration data_type variable_name; int x, y, z; char flat, ch;

2 Variable initialization data_type variable_name = value; int x = 50, y = 30; char flag = „x‟, ch=‟l‟;

There are three types of variables in C program,

4. Local variable

The scope of local variables will be within the function only. These variables are

declared within the function and can‟t be accessed outside the function.

5. Global variable

The scope of global variables will be throughout the program. These variables can be

accessed from anywhere in the program. This variable is defined outside the main function. So

that, this variable is visible to main function and all other sub functions.

Page 135: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

135

6. Environment variable

Environment variable is a variable that will be available for all applications and programs

in a compiler.

We can access these variables from anywhere in a C program without declaring and

initializing in an application or C program.

The inbuilt functions which are used to access modify and set these environment

variables are called environment functions.

Do you know difference between variable declaration & definition?

S.no Variable declaration Variable definition

1 Declaration tells the compiler about data type and

size of the variable. Definition allocates memory for the variable.

2 Variable can be declared many times in a

program.

It can happen only one time for a variable in a

program.

3 The assignment of properties and identification to

a variable. Assignments of storage space to a variable.

2.6.4 Constant

C Constants are also like normal variables except their values cannot be modified by the program

once they are defined. They refer to fixed values. They are also called as literals

They may be belonging to any of the data type. Please see below table for constants with respect

to their data type.

Types of C constant:

6. Integer constants

7. Real or Floating point constants

8. Character constants

9. String constants

10. Backslash character constants

S.no Constant type data type Example

1 Integer constants

int

unsigned int

long int

long long int

53 , 762 , -478 , etc

5000u , 1000U , etc

1000L , -300L , etc

5555555LL

2 Real or Floating point constants float, doule

111.22F , 2.22e-2f

111.22 , 4.0 ,

-0.34565

5 character constants char „A‟ , „B‟, „C‟

6 string constants char “ABCD” , “Hai”

Rules for constructing C constant:

Integer Constants

Page 136: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

136

7. It must not have a decimal point.

8. It can either be positive or negative.

9. No commas or blanks are allowed within an integer constant.

10. An integer constant must have at least one digit.

11. If no sign precedes an integer constant, it is assumed to be positive.

12. The allowable range for integer constants is -32768 to 32767

Real Constants

6. A real constant must have at least one digit

7. It must have a decimal point

8. It could be either positive or negative

9. If no sign precedes an integer constant, it is assumed to be positive.

10. No commas or blanks are allowed within a real constant.

Character constants

4. A character constant is a single alphabet, a single digit or a single special symbol enclosed

within single inverted commas. Both the inverted commas should point to left.

5. For example, ‟C‟ is a valid character constant whereas „C‟ is not.

6. The maximum length of a character constant is 1 character

Backslash Character Constants:

There are some characters which have special meaning in C language. They should be

preceded by back slash symbol to make use of special function of them. Given below is the list of

special characters and their purpose.

Character Meaning

\b Backspace

\f Form feed

\n New line

\r Carriage return

\t Horizontal tab

\” Double quote

\‟ Single quote

\\ Backslash

\v Vertical tab

\a Alert or bell

\? Question mark

\N Octal constant (N is an octal constant)

\XN Hexadecimal constant (N – hex.dcml cnst)

Page 137: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

137

How to use constants in a C program?

We can define constants in a C program in the following ways.

3. By “const” keyword

4. By “#define” preprocessor directive

2.7 Data Types

4. C data types are defined as the data storage format that a variable can store a data to perform a

specific operation.

5. Data types are used to define a variable before to use in a program.

6. Size of variable, constant and array are determined by data types.

There are four data types in C language. They are,

S.no Types Data Types

1 Basic data types int, char, float, double

2 Enumeration data type enum

3 Derived data type pointer, array, structure, union

4 Void data type void

1. Basic data types

Integer data type:

This data type allows a variable to store numeric values.

int keyword is used to refer integer data type.

The storage size of int data type is 2 or 4 or 8 byte.

It varies depend upon the processor in the CPU that we use.

If we are using 16 bit processor, 2 byte (16 bit) of memory will be allocated for

int data type.

int(2 byte) can store values from -32,768 to +32,767

int(4 byte) can store values from -2,147,483,648 to +2,147,483,647.

If you want to use the integer value that crosses the above limit, you can go for

long int and long long int for which the limits are very high.

Note:

You can‟t store decimal values using int data type.

If you use decimal values, those would be truncated and you will get only whole number.

Character data type:

This data type allows a variable to store only one character.

storage size of char data type is 1.

We can store only one character using char data type.

Page 138: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

138

char keyword is used to refer character data type. For example, „A‟ can be stored using char datatype.

Floating point data type:

Floating point data type consists of 2 types. They are:

float:

Float data type allows a variable to store decimal values.

storage size of float data type is 4.

This also varies depend upon the processor in the CPU.

We can use upto 6 digits after decimal using float data type. For example, 10.456789 can be stored in a variable using float data type.

double:

Double data type is also same as float data type which allows upto 10 digits after

decimal.

The range is from 1E–37 to 1E+37.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

#include <stdio.h>

#include <limits.h>

int main()

{

int a = 30;

char b = 'A';

float c = 20.456;

double d = 5500000;

printf("Value of int a : %d \n",a);

printf("Value of char b : %c \n",b);

printf("Value of float c : %f \n",c);

printf("Value of double d : %lf \n",d);

return 0;

}

Output: Value of int a : 30

Value of char b : A

Value of float c : 20.455999

Page 139: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

139

Value of double d : 5500000.000000

2. Enumeration data type:

Enumeration data type consists of named integer constants as a list.

It start with 0(zero) by default and value is incremented by 1 for the sequential identifiers.

Enum syntax in C:

enum identifier [optional{ enumerator-list }]

Example: enum month { Jan, Feb, Mar };

/* Jan, Feb and Mar variables will be assigned to 0, 1 and 2 respectively by default */

or enum month { Jan = 1, Feb, Mar };

/* Feb and Mar variables will be assigned to 2 and 3 respectively by default */

enum month { Jan = 20, Feb, Mar };

/* Jan, Feb and Mar variables will be assigned to 20, 21 and 22 respectively by default */

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

#include <stdio.h>

int main()

{

enum MONTH { Jan = 0, Feb, Mar };

enum MONTH month = Mar;

if(month == 0)

printf("Value of Jan");

else if(month == 1)

printf("Month is Feb");

if(month == 2)

printf("Month is Mar");

}

Output: Month is March

3. Derived data type:

Array, pointer, structure and union are called derived data type.

4. Void data type:

Void is an empty data type that has no value. This can be used in functions and pointers.

2.7.1 Modifiers

The amount of memory space to be allocated for a variable is derived by modifiers. Modifiers are

prefixed with basic data types to modify (either increase or decrease) the amount of storage space

allocated to a variable.

Page 140: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

140

For example, storage space for int data type is 4 byte for 32 bit processor. We can increase the range by using long int which is 8 byte.

We can decrease the range by using short int which is 2 byte. There are 5 modifiers available in C language. They are,

6. short

7. long

8. signed

9. unsigned

10. long long

Below table gives the detail about the storage size of each C basic data type in 16 bit processor.

The storage size and range for int and float will vary depend on the CPU processor (8,16, 32 and

64 bit)

S.No C Data types storage Size Range

1 char 1 –127 to 127

2 int 2 –32,767 to 32,767

3 float 4 1E–37 to 1E+37 with six digits of precision

4 double 8 1E–37 to 1E+37 with ten digits of precision

5 long double 10 1E–37 to 1E+37 with ten digits of precision

6 long int 4 –2,147,483,647 to 2,147,483,647

7 short int 2 –32,767 to 32,767

8 unsigned short int 2 0 to 65,535

9 signed short int 2 –32,767 to 32,767

10 long long int 8 –(2power(63) –1) to 2(power)63 –1

11 signed long int 4 –2,147,483,647 to 2,147,483,647

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

13 unsigned long long int 8 2(power)64 –1

sizeof () operator is used to find the memory space allocated for each C data types.

1

2

3

4

5

6

7

8

9

10

11

#include <stdio.h>

#include <limits.h>

int main()

{

int a;

char b;

float c;

double d;

printf("Storage size for int data type:%d \n",sizeof(a));

Page 141: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

141

12

13

14

15

16

printf("Storage size for char data type:%d \n",sizeof(b));

printf("Storage size for float data type:%d \n",sizeof(c));

printf("Storage size for double data type:%d \n",sizeof(d));

return 0;

}

Output: Storage size for int data type:4

Storage size for char data type:1

Storage size for float data type:4

Storage size for double data type:8

Key points to remember:

5. Data types define a variable in a C program. int, char, float, double and void are C basic data

types

6. int data type returns a value from function call.

7. void data type does not return any value from function call. It has no size.

8. sizeof () operator is used to find the memory space allocated for each data type

2.8 Operators and Expressions

The symbols which are used to perform logical and mathematical operations are called C

operators.

These C operators join individual constants and variables to form expressions. Operators,

functions, constants and variables are combined together to form expressions. Example: A + B * 5

where,

+, * - operators

A, B - variables

5 – constant

A + B * 5 - expression

Types of C operators:

C language offers many types of operators. They are,

9. Arithmetic operators

10. Assignment operators

11. Relational operators

12. Logical operators

13. Bit wise operators

14. Conditional operators (ternary operators)

15. Increment/decrement operators

16. Special operators

1. Arithmetic Operators:

These operators are used to perform mathematical calculations like addition, subtraction,

multiplication, division and modulus.

Page 142: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

142

S.no Operator Operation

1 + Addition

2 - Subtraction

3 * multiplication

4 / Division

5 % Modulus

Example program for C arithmetic operators:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

# include <stdio.h>

int main()

{

int a=40,b=20, add,sub,mul,div,mod;

add = a+b;

sub = a-b;

mul = a*b;

div = a/b;

mod = a%b;

printf("Addition of a, b is : %d\n", add);

printf("Subtraction of a, b is : %d\n", sub);

printf("Multiplication of a, b is : %d\n", mul);

printf("Division of a, b is : %d\n", div);

printf("Modulus of a, b is : %d\n", mod);

}

Output:

Addition of a, b is : 60

Subtraction of a, b is : 20

Multiplication of a, b is : 800

Division of a, b is : 2

Modulus of a, b is : 0

2. Assignment operators:

The values for the variables are assigned using assignment operators.

For example, if the value 10 is to be assigned for the variable sum, it can be done like below.

sum = 10;

Below are some of other assignment operators:

Operator Example Explanation

Simple operator

= sum = 10 Value 10 is assigned to variable sum

Page 143: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

143

Compound assignment operator

+= sum+=10 This is same as sum = sum+10

-= sum – = 10 This is same as sum = sum – 10

*= sum*=10 This is same as sum = sum*10

/+ sum/=10 This is same as sum = sum/10

%= sum%=10 This is same as sum = sum%10

&= sum&=10 This is same as sum = sum&10

^= sum^=10 This is same as sum = sum^10

Example program for assignment operators:

1

2

3

4

5

6

7

8

9

10

# include <stdio.h>

int main()

{

int Total=0,i;

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

{

Total+=i; // This is same as Total = Toatal+i

}

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

Output

Total = 45

3. Relational operators:

These operators are used to find the relation between two variables. That is, used to compare the

value of two variables.

Operator Example

> x > y

< x < y

>= x >= y

<= x <= y

== x == y

!= x != y

Example program for relational operators:

1

2

3

4

5

6

7

8

9

10

#include <stdio.h>

int main()

{

int m=40,n=20;

if (m == n) {

printf("m and n are equal");

}

else {

printf("m and n are not equal");

}

Page 144: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

144

11 }

Output:

m and n are not equal

4. Logical operators:

These operators are used to perform logical operations on the given two variables.

Operator Example

&& x && y

|| x || y

! x (x || y), !(x && y)

Example program for logical operators:

1

2

3

4

5

6

7

8

#include <stdio.h>

int main()

{

int m=40,n=20;

if (m>n && m !=0) {

printf("m is greater than n and not equal to 0");

}

}

Output:

m is greater than n and not equal to 0

5. Bit wise operators:

These operators are used to perform bit operations on given two variables.

Truth table for bitwise operation: Bitwise operators:

x y x/y x & y x ^ y Operator Explanation

0 0 0 0 0 & Bitwise AND

0 1 1 0 1 | Bitwise OR

1 0 1 0 1 ~ Bitwise NOT

1 1 1 1 0 ^ XOR

<< Left Shift

>> Right Shift

Example program for bitwise operators:

1

2

3

#include <stdio.h>

int main()

{

Page 145: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

145

4

5

6

7

8

9

10

11

12

int m=40,n=20,AND_opr,OR_opr,XOR_opr ;

AND_opr = (m&n);

OR_opr = (m|n);

XOR_opr = (m^n);

printf("AND_opr value = %d\n",AND_opr );

printf("XOR_opr value = %d\n",XOR_opr );

printf("OR_opr value = %d\n",OR_opr );

}

Output:

AND_opr value = 0

XOR_opr value = 60

OR_opr value = 60

6. Conditional operators:

Conditional operators return one value if condition is true and returns other value is condition is

false. This operator is also called as ternary operator.

Syntax :

Example: (A > 100? 0: 1);

Here, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if else conditional

statements.

Example program for conditional/ternary operators:

1

2

3

4

5

6

7

8

#include <stdio.h>

int main()

{

int x=1, y ;

y = ( x ==1 ? 2 : 0 ) ;

printf("x value is %d\n", x);

printf("y value is %d", y);

}

Output:

x value is 1

y value is 2

7. Increment and decrement operators:

These operators are used to either increase or decrease the value of the variable by one.

Syntax :

++var_name; (or)

var_name++; (or)

- - var_name; (or)

var_name- -;

(Condition? true_value: false_value);

Page 146: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

146

Example : ++i, i++, - -i, i- -

Example program for increment operators:

1

2

3

4

5

6

7

8

9

10

11

12

//Example for increment operators

#include <stdio.h>

int main()

{

int i=1;

while(i<10)

{

printf("%d\n",i);

i++;

}

}

Output:

1

2

3

4

5

6

7

8

9

Example program for decrement operators:

1

2

3

4

5

6

7

8

9

10

11

12

//Example for decrement operators

#include <stdio.h>

int main()

{

int i=20;

while(i>10)

{

printf("%d\n",i);

i--;

}

}

Output:

20

19

18

17

16

15

14

13

Page 147: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

147

12

11

8. Special Operators:

Below are some of special operators that the C language offers.

S.no Operators Description

1 & This is used to get the address of the variable.

Example:&a will give address of a.

2 * This is used as pointer to a variable.

Example: * a where, * is pointer to the variable a.

3 Size of () This gives the size of the variable.

Example: size of (char) will give us 1.

4 ternary This is ternary operator and act exactly as if … else statement.

5 Type cast Type cast is the concept of modifying variable from one data type to other.

Do you know difference between pre/post increment and pre/post decrement operators?

S.no Operator Description

1 while(i++ < 5) The value of i is compared with 5, before incrementing i value by 1.

2 while(++i < 5) The value of i is incremented by 1, before comparing with 5.

3 while(i – - < 5) The value of i is compared with 5, before decrementing i value by 1.

4 while(- - i < 5) The value of i is decremented by 1, before comparing with 5.

Example program for pre – increment operators:

1

2

3

4

5

6

7

8

9

10

11

12

//Example for increment operators

#include <stdio.h>

int main()

{

int i=0;

while(++i < 5 )

{

printf("%d\n",i);

}

return 0;

}

Output

1

2

3

4

Example program for post – increment operators:

1

2

3

4

5

#include <stdio.h>

int main()

{

int i=0;

while(i++ < 5 )

Page 148: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

148

6

7

8

9

10

{

printf("%d\n",i);

}

return 0;

}

Output:

1

2

3

4

5

Example program for pre - decrement operators:

1

2

3

4

5

6

7

8

9

10

#include <stdio.h>

int main()

{

int i=10;

while(--i > 5 )

{

printf("%d\n",i);

}

return 0;

}

Output:

9

8

7

6

Example program for post - decrement operators:

1

2

3

4

5

6

7

8

9

10

#include <stdio.h>

int main()

{

int i=10;

while(i-- > 5 )

{

printf("%d\n",i);

}

return 0;

}

Output:

9

8

7

Page 149: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

149

6

5

Arithmetic Expressions

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

syntax of C language. In C every expression evaluates to a value i.e., every expression results in some

value of a certain type that can be assigned to a variable. Some examples of C expressions are shown in

the table given below.

Algebraic

Expression

C Expression

a x b – c a * b – c

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

(ab / c) a * b / c

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

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

Evaluation of Expressions

Expressions are evaluated using an assignment statement of the form Variable = expression;

Variable is any valid C variable name. When the statement is encountered, the expression is

evaluated first and then replaces the previous value of the variable on the left hand side. All variables

used in the expression must be assigned values before evaluation is attempted.

Example of evaluation statements are x = a * b – c

y = b / c * a

z = a – b / c + d;

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

void main ()

{

float a, b, c x, y, z;

a = 9;

b = 12;

c = 3;

x = a – b / 3 + c * 2 – 1;

y = a – b / (3 + c) * (2 – 1);

z = a – ( b / (3 + c) * 2) – 1;

printf (“x = %fn”,x);

printf (“y = %fn”,y);

printf (“z = %fn”,z);

}

Output

Page 150: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

150

x = 10.00

y = 7.00

z = 4.00

Precedence in Arithmetic Operators

An arithmetic expression without parenthesis will be evaluated from left to right using the rules

of precedence of operators. There are two distinct priority levels of arithmetic operators in C.

High priority * / %

Low priority + -

Rules for evaluation of expression

First parenthesized sub expression left to right are evaluated.

If parentheses are nested, the evaluation begins with the innermost sub expression.

The precedence rule is applied in determining the order of application of operators in evaluating

sub expressions.

The associability rule is applied when two or more operators of the same precedence level appear

in the sub expression.

Arithmetic expressions are evaluated from left to right using the rules of precedence.

When Parenthesis is used, the expressions within parenthesis assume highest priority.

Type conversions in expressions

Implicit type conversion

C permits mixing of constants and variables of different types in an expression.

C automatically converts any intermediate values to the proper type so that the expression

can be evaluated without losing any significance.

This automatic type conversion is known as implicit type conversion

During evaluation it adheres to very strict rules and type conversion.

If the operands are of different types the lower type is automatically converted to the

higher type before the operation proceeds.

The result is of higher type.

The following rules apply during evaluating expressions

All short and char are automatically converted to int then

If one operand is long double, the other will be converted to long double and result

will be long double.

If one operand is double, the other will be converted to double and result will be double.

If one operand is float, the other will be converted to float and result will be float.

If one of the operand is unsigned long int, the other will be converted into unsigned

long int and result will be unsigned long int.

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

.....a. If unsigned int can be converted to long int, then unsigned int operand will be

converted as such and the result will be long int.

.....b. Else both operands will be converted to unsigned long int and the result will be

unsigned long int.

If one of the operand is long int, the other will be converted to long int and the result will

be long int

Page 151: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

151

If one operand is unsigned int the other will be converted to unsigned int and the result

will be unsigned int.

Explicit Conversion

Many times there may arise a situation where we want to force a type conversion in a way that is

different from automatic conversion.

Consider for example the calculation of number of female and male students in a class

female_students

Ratio = -------------------

male_students

Since if female_students and male_students are declared as integers, the decimal part will be rounded off

and its ratio will represent a wrong figure.

This problem can be solved by converting locally one of the variables to the floating point as shown below.

Ratio = (float) female_students / male_students

The operator float converts the female_students to floating point for the purpose of evaluation of the

expression. Then using the rule of automatic conversion, the division is performed by floating point mode, thus

retaining the fractional part of the result.

The process of such a local conversion is known as explicit conversion or casting a value.

The general form is (type_name) expression

Operators Precedence in C

Operator precedence determines the grouping of terms in an expression.

This affects how an expression is evaluated.

Certain operators have higher precedence than others;

for example, the multiplication operator has higher precedence than the addition operator: For example x = 7 + 3 * 2;

Here x is assigned 13, not 20

because operator * has higher precedence than +

so it first get multiplied with 3*2 and then adds into 7.

Here operators with the highest precedence appear at the top of the table, those with the lowest

appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative * / % Left to right

Additive + - Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Page 152: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

152

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

2.9 MANAGING INPUT AND OUTPUT OPERATIONS :

The input and output functions are used to provide input to the program and display the result to

the user respectively. These functions are available in the header file.

There are two types of input/output functions. They are:

1. Formatted Input/Output Functions

2. Unformatted Input/Output Functions

Formatted Input/Output Functions:

The value to these functions has to be given in a particular order. They are classified as follows:

Input Output

scanf() printf()

fscanf() fprintf()

Page 153: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

153

scanf() Function:

scanf() function is used to read a character, string, numeric data from keyboard.

The general syntax for the scanf() function is as follows:

Scanf(“control string”, address of the variable)

Example:

int a;

Scanf(”%d”,&a);

where & - address of operator which fetches the address of the variable a.

Rules to be followed:

5. The control string must be given within double quotation.

6. The variables can be separated by using comma.

7. It should be terminated by a semi colon.

8. No empty space should be given between two control strings.

printf() Function:

The printf() function is used to print the character, string, float, integer, octal and

hexadecimal values onto the output screen.

The general syntax is as follows:

Example;

int a=10;

printf(“%d”,a);

Rules for writing printf() function:

4. The variable and the control string should match.

5. The control string must be given in double quotation.

6. Any number of values can be displayed. The variables must be separated by comma.

Sample Program using scanf() and printf() functions:

printf(“control string”, variable name);

Page 154: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

154

#include<stdio.h>

void main()

{

int a;

printf(“\nEnter the value for a‟);

scanf(“%d”,&a);

printf(“\n The value entered is %d”,a);

}

Output:

Enter the value for a 7

The value entered is 7

fscanf() Function: This function is used to read the data from a file.

fprintf() Function: This function is used to write data into a file.

Unformatted Input and Output Functions:

Some of the unformatted input and output functions are given below:

Single Character Input Function:

Page 155: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

155

getc(): It is used to get a single character from the standard input to a character variable. The getc()

function is often used in file processing.

Syntax:

character variable = getc();

Example :

char c;

c = getc();

getchar() : It reads a single character from the standard input device. This function does not require any

arguments, through a pair of empty parentheses.

Syntax:

character variable = getchar();

Example :

char x;

x= getchar();

Single Character Output Function:

putc(): It is used to display a single character in a character variable to standard output device. The putc()

function is often used in file processing.

Syntax:

putc(character variable);

Example :

char c;

putc(c);

putchar() : It display one character at a time on the standard output device. This function does the reverse

operation of the single character input function.

Syntax:

putchar( character variable);

Page 156: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

156

Example :

char x;

putchar(x);

Sample program for single input & output function getchar() & putchar():

#include<stdio.h>

void main()

{

char x;

printf(“Enter any alphabet either in Lower or Uppercase….”);

x=getchar();

if(islower(x))

putchar(toupper(x));

else

putchar(tolower(x));

}

Output:

1. Enter any alphabet either in Lower or Uppercase……s

S

2. Enter any alphabet either in Lower or Uppercase……M

m

String Function gets() and puts():

gets(): It is used to read the string (string is a group of character) from the standard input device.

Syntax:

Page 157: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

157

gets(char type of array variable);

Example :

char c[10];

gets(c);

puts() : It display the string to the standard output device.

Syntax:

puts(char type array variable);

Example :

char c[];

puts(c);

Sample program for gets() & puts() functions:

#include<stdio.h>

void main()

{

char x[40];

puts(“Enter String….”);

gets(x);

puts(“Print the name….”);

puts(x);

}

Output:

Enter String…… Hello

Page 158: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

158

Print the name……Hello

Specifier Meaning

%c – Print a character

%d – Print a Integer

%i – Print a Integer

%e – Print float value in exponential form.

%f – Print float value

%g – Print using %e or %f whichever is smaller

%o – Print actual value

%s – Print a string

%x – Print a hexadecimal integer (Unsigned) using lower case a – F

%X – Print a hexadecimal integer (Unsigned) using upper case A – F

%a – Print a unsigned integer.

%p – Print a pointer value

%hx – hex short

%lo – octal long

%ld – long

2.10 Control Structures in C: Normally statements in C program are executed sequentially i.e. in the order in which they are

written. This is called sequential execution. We can transfer the control point to a desired location is

possible with control structures. C allows many kinds of control statements.

I. Conditional (decision) control structures

if

if –else

if-elseif – else

nested if

II. Jumping (branching) control structures

goto

break

return

continue

III. Loop (iterative) control structures

for loop

while loop

do - while loop

IV. Multi way conditional (case) control structures

switch- case

Decision Making

Decision making structures require that the programmer specify one or more conditions to be

evaluated or tested by the program, along with a statement or statements to be executed if the condition is

determined to be true, and optionally, other statements to be executed if the condition is determined to be

false.

Following is the general from of a typical decision making structure found in most of the

programming languages:

Page 159: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

159

C programming language assumes any non-zero and non-null values as true and if it is either

zero or null then it is assumed as false value.

C programming language provides following types of decision making statements

Statement Description

if statement An if statement consists of a boolean expression followed by one or more statements.

if...else statement An if statement can be followed by an optional else statement, which executes when the

boolean expression is false.

nested if statements You can use one if or else if statement inside another if or else if statement(s).

switch statement A switch statement allows a variable to be tested for equality against a list of values.

nested switch

statements You can use one swicth statement inside another switch statement(s).

if statement An if statement consists of a boolean expression followed by one or more statements.

Syntax:

The syntax of an if statement in C programming language is:

if(boolean_expression)

{

/* statement(s) will execute if the boolean expression is true */

}

If the boolean expression evaluates to true then the block of code inside the if statement will be

executed. If boolean expression evaluates to false then the first set of code after the end of the if statement

(after the closing curly brace) will be executed.

C programming language assumes any non-zero and non-null values as true and if it is either

zero or null then it is assumed as false value.

Page 160: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

160

Flow Diagram:

Example:

#include <stdio.h>

int main ()

{

int a = 10; /* local variable definition */

if( a < 20 ) /* check the boolean condition using if statement */

{

printf("a is less than 20\n" ); /* if condition is true then print the following */

}

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

return 0;

}

Output

a is less than 20;

value of a is : 10

if...else statement An if statement can be followed by an optional else statement, which executes when the boolean

expression is false.

Syntax:

The syntax of an if...else statement in C programming language is:

if(boolean_expression)

{

Page 161: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

161

/* statement(s) will execute if the boolean expression is true */

}

else

{

/* statement(s) will execute if the boolean expression is false */

}

If the boolean expression evaluates to true then the if block of code will be executed otherwise

else block of code will be executed.

C programming language assumes any non-zero and non-null values as true and if it is either

zero or null then it is assumed as false value.

Flow Diagram:

Example:

#include <stdio.h>

int main ()

{

int a = 100; /* local variable definition */

if( a < 20 ) /* check the boolean condition */

{

printf("a is less than 20\n" ); /* if condition is true then print the following */

}

else

{

printf("a is not less than 20\n" ); /* if condition is false then print the following */

}

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

return 0;

}

Output:

a is not less than 20;

value of a is : 100

Page 162: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

162

The if...else if...else Statement An if statement can be followed by an optional else if...else statement, which is very useful to test

various conditions using single if...else if statement.

When using if, else if , else statements there are few points to keep in mind.

An if can have zero or one else's and it must come after any else if's.

An if can have zero to many else if's and they must come before the else.

Once an else if succeeds, none of the remaining else if's or else's will be tested.

Syntax:

The syntax of an if...else if...else statement in C programming language is:

if(boolean_expression 1)

{

/* Executes when the boolean expression 1 is true */

}

else if( boolean_expression 2)

{

/* Executes when the boolean expression 2 is true */

}

else if( boolean_expression 3)

{

/* Executes when the boolean expression 3 is true */

}

else

{

/* executes when the none of the above condition is true */

}

Example:

#include <stdio.h>

int main ()

{

int a = 100; /* local variable definition */

if( a == 10 ) /* check the boolean condition */

{

printf("Value of a is 10\n" ); /* if condition is true then print the following */

}

else if( a == 20 )

{

printf("Value of a is 20\n" ); /* if else if condition is true */

}

else if( a == 30 )

{

printf("Value of a is 30\n" ); /* if else if condition is true */

}

else

{

Page 163: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

163

printf("None of the values is matching\n" ); /* if none of the conditions is true */

}

printf("Exact value of a is: %d\n", a );

return 0;

}

Output

None of the values is matching

Exact value of a is: 100

nested if statements It is always legal in C programming to nest if-else statements, which means you can use one if or

else if statement inside another if or else if statement(s).

Syntax:

The syntax for a nested if statement is as follows: if( boolean_expression 1)

{

/* Executes when the boolean expression 1 is true */

if(boolean_expression 2)

{

/* Executes when the boolean expression 2 is true */

}

}

You can nest else if...else in the similar way as you have nested if statement.

Example:

#include <stdio.h>

int main ()

{

int a = 100; /* local variable definition */

int b = 200; /* local variable definition */

if( a == 100 ) /* check the boolean condition */

{

if( b == 200 ) /* if condition is true then check the following */

{

printf("Value of a is 100 and b is 200\n" ); /* if condition is true then print the following */

}

}

printf("Exact value of a is : %d\n", a );

printf("Exact value of b is : %d\n", b );

return 0;

}

Page 164: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

164

Output

Value of a is 100 and b is 200

Exact value of a is : 100

Exact value of b is : 200

switch statement A switch statement allows a variable to be tested for equality against a list of values. Each value

is called a case, and the variable being switched on is checked for each switch case.

Syntax:

The syntax for a switch statement in C programming language is as follows: switch(expression){

case constant-expression :

statement(s);

break; /* optional */

case constant-expression :

statement(s);

break; /* optional */

/* you can have any number of case statements */

default : /* Optional */

statement(s);

}

The following rules apply to a switch statement:

The expression used in a switch statement must have an integral or enumerated type, or be of a

class type in which the class has a single conversion function to an integral or enumerated type.

You can have any number of case statements within a switch. Each case is followed by the value

to be compared to and a colon.

The constant-expression for a case must be the same data type as the variable in the switch, and

it must be a constant or a literal.

When the variable being switched on is equal to a case, the statements following that case will

execute until a break statement is reached.

When a break statement is reached, the switch terminates, and the flow of control jumps to the

next line following the switch statement.

Not every case needs to contain a break. If no break appears, the flow of control will fall

through to subsequent cases until a break is reached.

A switch statement can have an optional default case, which must appear at the end of the

switch. The default case can be used for performing a task when none of the cases is true. No

break is needed in the default case.

Page 165: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

165

Flow Diagram:

Example:

#include <stdio.h>

int main ()

{

char grade = 'B'; /* local variable definition */

switch(grade)

{

case 'A' :

printf("Excellent!\n" );

break;

case 'B' :

printf("Well done\n" );

break;

case 'C' :

printf("You passed\n" );

break;

case 'D' :

printf("Better try again\n" );

break;

default :

printf("Invalid grade\n" );

}

printf("Your grade is %c\n", grade );

return 0;

}

Output Well done

Your grade is B

Page 166: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

166

nested switch statements It is possible to have a switch as part of the statement sequence of an outer switch. Even if the

case constants of the inner and outer switch contain common values, no conflicts will arise.

Syntax:

The syntax for a nested switch statement is as follows: switch(ch1) {

case 'A':

printf("This A is part of outer switch" );

switch(ch2) {

case 'A':

printf("This A is part of inner switch" );

break;

case 'B': /* case code */

}

break;

case 'B': /* case code */

}

Example:

#include <stdio.h>

int main ()

{

int a = 100; /* local variable definition */

int b = 200;

switch(a)

{

case 100:

printf("This is part of outer switch\n", a );

switch(b)

{

case 200:

printf("This is part of inner switch\n", a );

}

}

printf("Exact value of a is : %d\n", a );

printf("Exact value of b is : %d\n", b );

return 0;

}

Output This is part of outer switch

This is part of inner switch

Exact value of a is : 100

Exact value of b is : 200

Page 167: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

167

Loops

There may be a situation when you need to execute a block of code several number of times. In

general statements are executed sequentially: The first statement in a function is executed first, followed

by the second, and so on.

Programming languages provide various control structures that allow for more complicated

execution paths.

A loop statement allows us to execute a statement or group of statements multiple times and

following is the general from of a loop statement in most of the programming languages:

C programming language provides following types of loop to handle looping requirements.

Loop Type Description

while loop Repeats a statement or group of statements while a given condition is true. It tests the condition

before executing the loop body.

for loop Execute a sequence of statements multiple times and abbreviates the code that manages the loop

variable.

do...while loop Like a while statement, except that it tests the condition at the end of the loop body

nested loops You can use one or more loop inside any another while, for or do..while loop.

Loop Control Statements:

Loop control statements change execution from its normal sequence. When execution leaves a

scope, all automatic objects that were created in that scope are destroyed.

C supports the following control statements.

Control Statement Description

break statement Terminates the loop or switch statement and transfers execution to the

statement immediately following the loop or switch.

Page 168: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

168

continue statement Causes the loop to skip the remainder of its body and immediately retest its

condition prior to reiterating.

goto statement Transfers control to the labeled statement. Though it is not advised to use goto

statement in your program.

The Infinite Loop:

A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally

used for this purpose. Since none of the three expressions that form the for loop are required, you can

make an endless loop by leaving the conditional expression empty.

#include <stdio.h>

int main ()

{

for( ; ; )

{

printf("This loop will run forever.\n");

}

return 0;

}

When the conditional expression is absent, it is assumed to be true. You may have an

initialization and increment expression, but C programmers more commonly use the for(;;) construct to

signify an infinite loop.

NOTE: You can terminate an infinite loop by pressing Ctrl + C keys.

while loop

A while loop statement in C programming language repeatedly executes a target statement as

long as a given condition is true.

Syntax:

The syntax of a while loop in C programming language is: while(condition)

{

statement(s);

}

Here statement(s) may be a single statement or a block of statements. The condition may be any

expression, and true is any nonzero value. The loop iterates while the condition is true.

When the condition becomes false, program control passes to the line immediately following the

loop.

Page 169: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

169

Flow Diagram:

Here key point of the while loop is that the loop might not ever run. When the condition is tested

and the result is false, the loop body will be skipped and the first statement after the while loop will be

executed.

Example:

#include <stdio.h>

int main ()

{

int a = 10; /* local variable definition */

while( a < 20 ) /* while loop execution */

{

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

a++;

}

return 0;

}

Output value of a: 10

value of a: 11

value of a: 12

value of a: 13

value of a: 14

value of a: 15

value of a: 16

value of a: 17

value of a: 18

value of a: 19

Page 170: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

170

for loop

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to

execute a specific number of times.

Syntax:

The syntax of a for loop in C programming language is: for ( init; condition; increment )

{

statement(s);

}

Here is the flow of control in a for loop:

5. The init step is executed first, and only once. This step allows you to declare and initialize any

loop control variables. You are not required to put a statement here, as long as a semicolon

appears.

6. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the

body of the loop does not execute and flow of control jumps to the next statement just after the

for loop.

7. After the body of the for loop executes, the flow of control jumps back up to the increment

statement. This statement allows you to update any loop control variables. This statement can be

left blank, as long as a semicolon appears after the condition.

8. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself

(body of loop, then increment step, and then again condition). After the condition becomes false,

the for loop terminates.

Flow Diagram:

Page 171: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

171

Example:

#include <stdio.h>

int main ()

{

for( int a = 10; a < 20; a = a + 1 ) /* for loop execution */

{

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

}

return 0;

}

Output value of a: 10

value of a: 11

value of a: 12

value of a: 13

value of a: 14

value of a: 15

value of a: 16

value of a: 17

value of a: 18

value of a: 19

do...while

Unlike for and while loops, which test the loop condition at the top of the loop, the do...while

loop in C programming language checks its condition at the bottom of the loop.

A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute

at least one time.

Syntax:

The syntax of a do...while loop in C programming language is: do

{

statement(s);

}while( condition );

Notice that the conditional expression appears at the end of the loop, so the statement(s) in the

loop execute once before the condition is tested.

If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop

execute again. This process repeats until the given condition becomes false.

Page 172: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

172

Flow Diagram:

Example:

#include <stdio.h>

int main ()

{

int a = 10; /* local variable definition */

do /* do loop execution */

{

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

a = a + 1;

}while( a < 20 );

return 0;

}

Output: value of a: 10

value of a: 11

value of a: 12

value of a: 13

value of a: 14

value of a: 15

value of a: 16

value of a: 17

value of a: 18

value of a: 19

nested loops

C programming language allows to use one loop inside another loop. Following section shows

few examples to illustrate the concept.

Syntax:

The syntax for a nested for loop statement in C is as follows: for ( init; condition; increment )

{

for ( init; condition; increment )

{

statement(s);

}

Page 173: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

173

statement(s);

}

The syntax for a nested while loop statement in C programming language is as follows: while(condition)

{

while(condition)

{

statement(s);

}

statement(s);

}

The syntax for a nested do...while loop statement in C programming language is as follows: do

{

statement(s);

do

{

statement(s);

}while( condition );

}while( condition );

A final note on loop nesting is that you can put any type of loop inside of any other type of loop.

For example a for loop can be inside a while loop or vice versa.

Example:

The following program uses a nested for loop to find the prime numbers from 2 to 100: #include <stdio.h>

int main ()

{

int i, j; /* local variable definition */

for(i=2; i<100; i++) {

for(j=2; j <= (i/j); j++)

if(!(i%j)) break; // if factor found, not prime

if(j > (i/j)) printf("%d is prime\n", i);

}

return 0;

}

Output: 2 is prime

3 is prime

5 is prime

7 is prime

11 is prime

13 is prime

17 is prime

19 is prime

23 is prime

29 is prime

31 is prime

Page 174: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

174

37 is prime

41 is prime

43 is prime

47 is prime

53 is prime

59 is prime

61 is prime

67 is prime

71 is prime

73 is prime

79 is prime

83 is prime

89 is prime

97 is prime

break statement

The break statement in C programming language has following two usage:

3. When the break statement is encountered inside a loop, the loop is immediately terminated

and program control resumes at the next statement following the loop.

4. It can be used to terminate a case in the switch statement (covered in the next chapter).

If you are using nested loops ( ie. one loop inside another loop), the break statement will stop the

execution of the innermost loop and start executing the next line of code after the block.

Syntax:

The syntax for a break statement in C is as follows: break;

Flow Diagram:

Example:

#include <stdio.h>

int main ()

{

int a = 10; /* local variable definition */

while( a < 20 ) /* while loop execution */

{

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

Page 175: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

175

a++;

if( a > 15)

{

break; /* terminate the loop using break statement */

}

}

return 0;

}

Output: value of a: 10

value of a: 11

value of a: 12

value of a: 13

value of a: 14

value of a: 15

continue statement

The continue statement in C programming language works somewhat like the break statement.

Instead of forcing termination, however, continue forces the next iteration of the loop to take place,

skipping any code in between.

For the for loop, continue statement causes the conditional test and increment portions of the

loop to execute. For the while and do...while loops, continue statement causes the program control

passes to the conditional tests.

Syntax:

The syntax for a continue statement in C is as follows: continue;

Flow Diagram:

Example:

#include <stdio.h>

int main ()

{

int a = 10; /* local variable definition */

do /* do loop execution */

Page 176: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

176

{

if( a == 15)

{

a = a + 1; /* skip the iteration */

continue;

}

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

a++;

}while( a < 20 );

return 0;

}

Output: value of a: 10

value of a: 11

value of a: 12

value of a: 13

value of a: 14

value of a: 16

value of a: 17

value of a: 18

value of a: 19

goto statement

A goto statement in C programming language provides an unconditional jump from the goto to a

labeled statement in the same function.

NOTE: Use of goto statement is highly discouraged in any programming language because it makes

difficult to trace the control flow of a program, making the program hard to understand and hard to

modify. Any program that uses a goto can be rewritten so that it doesn't need the goto.

Syntax:

The syntax for a goto statement in C is as follows: goto label;

..

.

label: statement;

Here label can be any plain text except C keyword and it can be set anywhere in the C program

above or below to goto statement.

Page 177: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

177

Flow Diagram:

Example:

#include <stdio.h>

int main ()

{

int a = 10; /* local variable definition */

LOOP:do /* do loop execution */

{

if( a == 15)

{

a = a + 1; /* skip the iteration */

goto LOOP;

}

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

a++;

}while( a < 20 );

return 0;

}

Output: value of a: 10

value of a: 11

value of a: 12

value of a: 13

value of a: 14

value of a: 16

value of a: 17

value of a: 18

value of a: 19

2.11 Solving simple scientific and statistical problems

Page 178: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

178

Program to evaluate Sine Series, Cosine Series and Exponential Series?

Sine series : sin x = x - ((x^3)/3!) + ((x^5)/5!) - …………..

Cosine Series : cos x = 1 - ((x^2)/2!) + ((x^4)/4!) -…………...

Exponential Series : e^x = 1 + (x/1!) + ((x^2)/2!) + ((x^3)/3!)+…….

#include<stdio.h>

#include<conio.h>

void main()

{

int i,n,j,ch;

float x,t,s,r;

char c='y';

clrscr();

do

{

printf("\n1.Sine Series");

printf("\n2.Cosine Series");

printf("\n3.Exponential Series");

printf("\n Enter The Choice");

scanf("%d",&ch);

switch(ch)

{

case 1:

printf("\n Enter The Limit");

scanf("%d",&n);

printf("\n Enter The Value Of x:");

scanf("%f",&x);

Page 179: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

179

r=((x*3.1415)/180);

t=r;

s=r;

i=2;

for(j=2;j<=n;j++)

{

t=(t*(-1)*r*r)/(i*(i+1));

s=s+t;

i=i+2;

}

printf("\n Sum Of The Given Sine Series Is %4f",s);

break;

case 2:

printf("\n Enter The Limit ");

scanf("%d",&n);

printf("\n Enter The Value Of x:");

scanf("%f",&x);

r=((x*3.14)/180);

t=1;

s=1;

i=1;

for(j=2;j<=n;j++)

{

t=((-1)*t*r*r)/(i*(i+1));

s=s+t;

i=i+2;

Page 180: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

180

}

printf("\n Sum Of The Cosine Series Is %f",s);

break;

case 3:

printf("\n Enter The Limit");

scanf("%d",&n);

printf("\n Enter The Value Of x:");

scanf("%f",&x);

t=1;

s=1;

for(i=1;i<n;i++)

{

t=(t*x)/i;

s=s+t;

}

printf("\n Sum Of Exponential Series Is %f",s);

break;

default:

printf("\n Wrong Choice");

}

printf("\n Do U Want To Continue Y/N");

scanf("%c",&c);

}

while(c=='y');

getch();

}

Page 181: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

181

Output

1.Sine Series

2.Cosine Series

3.Exponential Series

Enter The Choice 1

Enter The Limit 2

Enter The Value Of x:60

Sum Of The Given Sine Series Is 0.855787

Do U Want To Continue Y/N y

1.Sine Series

2.Cosine Series

3.Exponential Series

Enter The Choice 2

Enter The Limit 2

Enter The Value Of x:60

Sum Of The Cosine Series Is 0.452245

Do U Want To Continue Y/N y

Page 182: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

182

1.Sine Series

2.Cosine Series

3.Exponential Series

Enter The Choice 3

Enter The Limit 2

Enter The Value Of x:3

Sum Of Exponential Series Is 4.000000

Do U Want To Continue Y/N n

Program to generate,first n number of elements in the Fibonacci series

#include<stdio.h>

#include<conio.h>

void main()

{

int n,i=0,j=1,temp,k;

clrscr();

printf("Enter the limit: ");

scanf("%d",&n);

printf("Fibonacci series\n");

if(n==1)

{

printf("%d\n%d\n",i,j);

Page 183: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

183

}

else

{

printf("%d\n%d\n",i,j);

for(k=2;k<n;k++)

{

temp=i+j;

printf("%d\n",temp);

i=j;

j=temp;

}

}

getch();

}

Output

Enter the limit:13

Fibonacci series

0

1

1

2

3

5

8

Page 184: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

184

13

21

34

55

89

144

Program to generate Armstrong number within a limit

Armstrong number: 153=13+5

3+3

3

#include<stdio.h>

#include<conio.h>

void main()

{

int i,r,n,sum=0,temp;

clrscr();

printf("Enter the limit :");

scanf("%d",&n);

for(i=1;i<n;i++)

{

temp=i;

sum=0;

while(temp!=0)

{

r=temp%10;

Page 185: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

185

sum=sum+(r*r*r);

temp=temp/10;

}

if(i==sum)

{

printf("\n%d",i);

}

getch();

}

Output:

Enter the limit :500

1

153

370

371

407

Program to print Floyd's Triangle

1

2 3

4 5 6

7 8 9 10

#include <stdio.h>

int main()

{

int n, i, c, a = 1;

printf("Enter the number of rows of Floyd's triangle to print\n");

Page 186: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

186

scanf("%d", &n);

for (i = 1; i <= n; i++)

{

for (c = 1; c <= i; c++)

{

printf("%d ",a);

a++;

}

printf("\n");

}

return 0;

}

Output

Enter the limit :4

1

2 3

4 5 6

7 8 9 10

Program to calculate roots of a quadratic equation #include<stdio.h>

#include<math.h>

int main(){

float a,b,c;

float d,root1,root2;

Page 187: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

187

printf("Enter a, b and c of quadratic equation: ");

scanf("%f%f%f",&a,&b,&c);

d = b * b - 4 * a * c;

if(d < 0){

printf("Roots are complex number.\n");

printf("Roots of quadratic equation are: ");

printf("%.3f%+.3fi",-b/(2*a),sqrt(-d)/(2*a));

printf(", %.3f%+.3fi",-b/(2*a),-sqrt(-d)/(2*a));

return 0;

}

else if(d==0){

printf("Both roots are equal.\n");

root1 = -b /(2* a);

printf("Root of quadratic equation is: %.3f ",root1);

return 0;

}

else{

printf("Roots are real numbers.\n");

root1 = ( -b + sqrt(d)) / (2* a);

Page 188: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

188

root2 = ( -b - sqrt(d)) / (2* a);

printf("Roots of quadratic equation are: %.3f , %.3f",root1,root2);

}

return 0;

}

Output:

Enter a, b and c of quadratic equation: 2 4 1

Roots are real numbers.

Roots of quadratic equation are: -0.293, -1.707

Program to compute the value of a given position in Pascal's Triangle

#include <stdio.h>

int main()

{

int n, x, y, c, q;

printf("Pascal Triangle Program\n");

printf("Enter the number of rows: ");

scanf("%d",&n);

Page 189: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

189

for (y = 0; y < n; y++)

{

c = 1;

for(q = 0; q < n - y; q++)

{

printf("%3s", " ");

}

for (x = 0; x <= y; x++)

{

printf(" %3d ",c);

c = c * (y - x) / (x + 1);

}

printf("\n");

}

printf("\n");

return 0;

}

Output: Pascal Triangle Program

Enter the number of rows: 11

1

1 1

1 2 1

1 3 3 1

Page 190: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

190

1 4 6 4 1

1 5 10 10 5 1

1 6 15 20 15 6 1

1 7 21 35 35 21 7 1

1 8 28 56 70 56 28 8 1

1 9 36 84 126 126 84 36 9 1

1 10 45 120 210 252 210 120 45 10 1

Program to compute the sum of 1 + 2 + …. + n series #include<stdio.h>

#include<conio.h>

void main()

{

int n,i;

int sum=0;

clrscr();

printf("Enter the value of n i.e. max values of series: ");

scanf("%d",&n);

sum = (n * (n + 1)) / 2;

printf("Sum of the series: ");

Page 191: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

191

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

if (i!=n)

printf("%d + ",i);

else

printf("%d = %d \n ",i,sum);

}

getch();

}

Output: Enter the n i.e. max values of series: 5

Sum of the series: 1 + 2 + 3 + 4 + 5 = 15

Program to compute the sum of series 1+X+ X^2 + X^3+. . . +X^N

#include<stdio.h>

#include<conio.h>

void main()

{

int x,n,t;

long sum=1;

clrscr();

printf("Enter the value of 'x': ");

Page 192: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

192

scanf("%d",&x);

printf("\nEnter the value of 'n': ");

scanf("%d",&n);

t=x;

while(n>0)

{

sum=sum+t;

t=t*x;

n--;

}

printf("\n Sum of the series=%ld",sum);

getch();

}

Output:

Enter the value of 'x': 5

Enter the value of 'n': 6

Sum of the series= 19531

Program to calculate the following Sum: Sum=1-x2/2! +x4/4!-x6/6!+x8/8!-x10/10!

#include <stdio.h>

#include<conio.h>

#include <math.h>

void main()

{

int counter,f_coun;

float sum=0,x,power,fact;

clrscr();

printf("Program For Sum Of Series");

printf("\n Equation Series : 1-X^2/2! + X^4/4!-X^6/6! + X^8/8!-X^10/10!");

Page 193: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

193

printf("\n Enter Value Of X : ");

scanf("%f",&x);

for(counter=0, power=0; power<=10; counter++,power=power+2)

{

fact=1;

//CALC FACTORIAL OF POWER VALUE

for(f_coun=power; f_coun>=1; f_coun--)

fact *= f_coun;

//EQ. FOR SUM SERIES

sum=sum+(pow(-1,counter)*(pow(x,power)/fact));

}

printf("Sum : %f",sum);

getch();

}

Output:

Program For Sum Of Series

Equation Series : 1-X^2/2! + X^4/4!-X^6/6! + X^8/8!-X^10/10!

Enter Value Of X : 6

Sum : -2.805714

Program to find the Sum of Series X-X3/3!+X5/5!-X7/7!+...

#include<stdio.h>

#include<conio.h>

void main()

{

longint x,i,j,k,n,sq,cnt;

double fact,sum=0;

clrscr();

printf("\n ENTER THE VALUE OF N: ");

scanf("%ld",&n);

printf("\n ENTER THE VALUE OF X: ");

scanf("%ld",&x);

for(i=1,cnt=1;i<=n;i=i+2,cnt++)

{

for(j=1,sq=1;j<=i;j++)

sq=sq*x;

printf("\n SQ = %ld",sq);

for(k=1,fact=1;k<=i;k++)

fact=fact*k;

printf("\n fact = %7.2lf",fact);

if(cnt%2==1)

sum=sum+(sq/fact);

else

sum=sum-(sq/fact);

printf("\n THE SUM OF THIS SERIES IS %7.2lf\n",sum);

Page 194: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

194

}

getch();

}

Output:

ENTER THE VALUE OF N: 5

ENTER THE VALUE OF X: 2

SQ = 2

fact = 1.00

THE SUM OF THIS SERIES IS 2.00

SQ = 8

fact = 6.00

THE SUM OF THIS SERIES IS 0.67

SQ = 32

fact = 120.00

THE SUM OF THIS SERIES IS 0.93

Program to find answer of the following series. Sum=E1+E2+E3+...

#include<stdio.h>

#include<conio.h>

#include<math.h>

void main()

{

longint i,n;

double sum=0;

clrscr();

printf("\n Enter The Value Of N: ");

scanf("%ld",&n);

for(i=1;i<=n;i++)

sum=sum+exp(i);

textcolor(RED);

printf("\n");

cprintf(" The Sum Of This Series Is %7.2lf\n",sum);

getch();

}

Output:

Enter The Value Of N: 5

The Sum Of This Series Is 233.20

UNIT – III

Page 195: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

195

ARRAYS AND STRINGS

Arrays - Initialization - Declaration - One dimensional and Two dimensional

arrays. String - String operations - String arrays. Simple programs - sorting -

searching - matrix operations.

3.1.ARRAYS

An array is a collection of similar data type that is stored under a common name in which

each element is located in separate memory locations.

SYNTAX:

Eg: char ar[6]={„A‟,‟R‟,‟R‟,‟A‟,‟Y‟};

CHARACTERISTICS OF ARRAY

1. All the elements of an array share a common name, and they are distinguished from

one another with the help of an element number (subscript value).

2. Array elements are stored in continuous memory locations.

3. The amount of storage required for holding elements of the array depends on its type

and size.

4. Memory space required by an array can be computed as

Eg: int a[10];

data-type array-variable[size of array-variable];

Total bytes = sizeof(data-type)× size of array-element

1000 1001 1002 1003 1004 1005

A R R A Y \0

[0] [1] [2] [3] [4] [5]

Element Subscript or indices

Page 196: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

196

Total bytes occupied by integer is 2×10=20 (i.e. Torttal bytes =sizeof (int)×10 )

FEATURES OF ARRAYS

1. Array is a derived data type.

2. String array always terminates with null character ('\0').

3. Array elements are countered from 0 to n-1.

4. Array elements can be accessed with base address (index) and subscripts define the

position of the element.

5. In array the elements are stored in continuous memory locations.

3.2.CLASSIFICATIONS OF ARRAY

Array can be classified into

1. Single / One- Dimensional Array

2. Two – Dimensional Array

3. Multi – Dimensional Array

3.2.1. SINGLE / ONE- DIMENSIONAL ARRAY

The collection of data items can be stored under a one variable name using only

one subscript; such a variable is called the one-dimensional array.

3.2.1.1. ARRAY DECLARATION

Arrays are declared in the same manner as an ordinary variable except array name must

have the size of the array i.e., number of elements accommodated in the array.

SYNTAX:

data-type array-variable[size / subscript of the array];

Eg: int X[4];

Address Element

1000 X[0]

1002 X[1]

1004 X[2]

1006 X[3]

Page 197: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

197

3.2.1.2. ARRAY INITIALIZATION

The values can be initialized to an array when they are declared like ordinary variables,

otherwise they hold garbage values.

SYNTAX:

Eg: int num[7]={2,4,1,17,49,5,11};

RULES FOR INTIALIZATION OF ARRAY

1. Values should be initialization by separating with comma and it should be enclosing with

pair of braces.

2. The list of values should be less than or equal to the size of the array variable.

3. If list of values is less than the size of the array variable then by default array location

get initialized to ‘0’ for integer variable, ‘0.0’ for float variable and ‘/0’ for character

variable.

4. If the list of values is not same as the element type of an array, implicit type casting will

be done.

5. One array variable cannot be assigned to or initialized with another array variable

(i.e. int a[3], b[3]={1,2,3}; a=b).

Eg. 1. Program to demonstrate one dimensional array

#include<stdio.h>

#include<conio.h>

data-type array-variable[size]={list of values};

ONE – DIMENSIONAL ARRAY MEMORY ARRANGEMENT

NAME num[0] num[1] num[2] num[3] num[4] num[5] num[6]

ELEMENT 2 4 1 17 49 5 11

ADDRESS 1000 1002 1004 1006 1008 1010 1012

Page 198: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

198

void main()

{

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

float c[]={'A','B','C','D'};

printf("Integer value in a[2] position : %d ",a[2]);

printf("\nFloat : %f %f %f %f ",c[0],c[1],c[2],c[3]);

getch();

}

E.g.2. To print bytes reserved for various data types

#include<stdio.h>

#include<conio.h>

void main()

{

int i[5];

char c[10];

long l[6];

printf("\nNo of Bytes reserved by Integer : %d",sizeof(i));

printf("\nNo of Bytes reserved by Character : %d",sizeof(c));

printf("\nNo of Bytes reserved by Long : %d",sizeof(l));

getch();

}

OUTPUT

Integer value in a[2] position : 3

Float : 65.000000 66.000000 67.000000 68.000000

OUTPUT

No of Bytes reserved by Integer : 10

No of Bytes reserved by Character : 10

No of Bytes reserved by Long : 24

Page 199: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

199

3.2.2. TWO – DIMENSIONAL ARRAY

1. Two-dimensional array are indexed by two subscripts, one for the row and another

for the column.

2. Array elements stored in the form of rows and columns is termed as two-

dimensional array

3. Two-dimensional array are used in situation where a table of values need to be

stores in an array.

3.2.2.1. ARRAY DECLARATION:

Two pairs of square brackets required for two dimensional array and three pairs

required for three-dimensional array and so on.

The row and column size specifier should be greater than zero.

SYNTAX:

Eg: int P[3][4];

3.2.2.2. INITIALISING A TWO-DIMENSIONAL ARRAY:

data-type array-variable[row size][column size];

TWO – DIMENSIONAL ARRAY MEMORY ARRANGEMENT

COLUMN 0 COLUMN 1 COLUMN 2 COLUMN 3

ROW 0 A[0][0] A[0][1] A[0][2] A[0][3]

ROW 1 A[1][0] A[1][1] A[1][2] A[1][3]

ROW 2 A[2][0] A[2][1] A[2][2] A[2][3]

Page 200: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

200

Like one dimensional array, the values can be initialized to the two dimensional arrays at

the time of declaration

SYNTAX:

Eg.1: int n[3][4] = {

{59,6,7,38},

{22,78,9,56},

{67,8,90,68}

};

Where “n” is the array name and it reserves 3 rows and 4 columns of memory as shown above.

Eg.2: int s[4][7]={10,12},{14,46,5};

RULES FOR INTIALIZATION OF ARRAY

1. The list of values should be less than or equal to the size of (i.e. row × column) the

array variable.

2. If list of values is less than the size of (i.e. row × column) the array variable then

by default array location get initialized to ‘0’ for integer variable, ‘0.0’ for float

variable and ‘/0’ for character variable.

data-type array-variable[row size][column size]={list of values};

0 1 2 3

0 59 6 7 38

1 22 78 9 56

2 67 8 90 68

10 12 0 0 0 0 0

14 46 5 0 0 0 0

0 0 0 0 0 0 0

0 0 0 0 0 0 0

Page 201: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

201

Eg: Program for Two-Dimensional Array

#include<stdio.h>

#include<conio.h>

void main()

{

int i,j;

int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};

clrscr();

printf("Elements of an array \n");

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

{

for (j=0;j<3;j++)

printf("%d",a[i][j]);

printf("\n");

}

getch();

}

3.2.3. MULTI – DIMENSIONAL ARRAY

If the dimension with three or more called as multidimensional array.

Multidimensional arrays are slower than the single dimensional array

OUTPUT

Elements of an array

123

456

789

0 1 2

0 1 2 3

1 4 5 6

2 7 8 9

Page 202: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

202

3.2.3.1. ARRAY DECLARATION:

The general form of a multi-dimensional array is

SYNTAX:

E.g: float b[4][4][4]4[4];

3.2.3.2. INITIALISING A MULTI-DIMENSIONAL ARRAY:

The three dimensional array can be initialized as

SYNTAX:

Eg: int m[3][3][3] = {

{{11,12,13},{14,15,16},{17,18,19}},

{{21,22,23},{24,25,26},{27,28,29}},

{{31,32,33},{34,35,36},{37,38,39}}};

Eg: Program for Multidimensional array

#include<stdio.h>

#include<conio.h>

void main()

{

int i,j,k;

data-type array-variable[size 1][size 2]. . . . . . . . [size n];

data-type array-variable[size 1][size 2]. . . . . . . . [size n]={list of values};

Page 203: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

203

int a[3][3][3]={{{1,2,3},{4,5,6},{7,8,9}},

{{1,4,7},{2,5,8},{3,6,9}},

{{1,4,4},{2,4,7},{6,6,3}}};

clrscr();

printf("Elements of an array \n");

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

{

for (j=0;j<3;j++)

{

for(k=0;k<3;k++)

printf("%d\t",a[i][j][k]);

printf("\n");

}

printf("\n");

}

getch();

}

OUTPUT

Elements of array

1 2 3

4 5 6

7 8 9

1 4 7

2 5 8

3 6 9

1 4 4

2 4 7

6 6 3

Page 204: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

204

3.3. CHARACTER ARRAY

The data elements stored in the array belong to character data type, so it is termed as

character array.

The terminating null character should be include explicitly will initializing character

array where as in string literal it is not necessary.

The size specification is optional if a string variable is explicitly initialized.

The string variable or character array can be initialized in two different ways

1. By using string literal constant E.g. char s[6]=”string”;

2. By using initialization list E.g. char s[6]={„s‟,‟t‟,‟r‟,‟i‟,‟n‟,‟g‟,‟\0‟};

E.g. To display character array & their addresses

#include <stdio.h>

void main()

{

char a[]={'H','E','L','P'};

int i;

clrscr();

for(i=0;a[i]!='\0';i++)

{

printf("\nThe array elements are : %c",a[i]);

printf("\nThe memory location is %u",&a[i]);

}

getch();

}

OUTPUT

The array elements are : H

The memory location is 65234

The array elements are : E

The memory location is 65235

The array elements are : L

Page 205: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

205

3.4. STRING

String literals are enclosed within double quotes (Eg. char x[]= ”A”; is a string),

whereas character literal are enclosed within single quotes (Eg. char x[]= {„A‟}; is a

character constant ).

The string is always declared as character arrays, In other words, character arrays are

called as strings.

String literal automatically terminated by the NULL (‘\0’) character.

The number of bytes required to store string literal constant is one more than the

number of character present in it.(i.e. Additional byte is to store terminating null

character)

Eg. char edu[ ]={„C‟,‟O‟,‟L‟,‟L‟,‟E‟,‟G‟,‟E‟,„\0‟};

The memory required to store the following string “COLLEGE” is 3 bytes

MEMORY ALLOCATION OF THE ABOVE STRING

While find out the length of a string it determines only the number of characters

present. The terminating null character is not counted.

Eg. strlen(“xyz”); will return 3 as it‟s character length.

C O L L E G E \0

2001 2002 2003 2004 2005 2006 2007 2008

Page 206: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

206

3.4.1. DECLARATION AND INTIALIZATION OF STRING

The string can be initialized as follows

char name[] =”INDIA”;

The character of the string is enclosed with in pair of double quotes. The C compiler inserts the

NULL (\0) character automatically at the end of the string.

3.4.2. DISPLAY OF STRING WITH DIFFERERNT FORMATS

The printf() function with %s format specifier is used to display the string on the screen.

Various formats is shown below

Eg ; char a[15]="STRINGHANDLING";

VARIOUS FORMATES OF DISPLAYING STRING LITERAL

S.No STATEMENT OUTPUT DESCRIPTION

1. printf("\n %s",a); STRINGHANDLING It display entire string

2. printf("\n %.5s",a); STRIN It displays first 5 characters from left

side.

3. printf("\n %.8s",a); STRINGHA

It displays first 8 characters from left

side.

4. printf("\n %-10.4s",a); STRI It displays first 4 characters from left

side.

Eg: Program to display string in different formats.

Page 207: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

207

#include <stdio.h>

#include<string.h>

void main()

{

char a[15]="STRINGHANDLING";

clrscr();

printf("\n %s",a);

printf("\n %.5s",a);

printf("\n %.8s",a);

printf("\n %-10.4s",a);

getch();

}

3.4.3. STRING OPERATIONS / STRING HANDLING FUNCTIONS

Every C compiler supports a large number of strings handling library functions. Some of

the strings handling functions are listed below.

S.NO FUNCTION PURPOSE SYNTAX

1. strlen() To find length of the string. var = strlen(string);

2. strcpy() To copy one string to another. strcpy(string1,string2);

3. strcat() To combine two strings strcat(string1,string2);

OUTPUT

STRINGHANDLING

STRIN

STRINGHA

STRI

Page 208: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

208

4. strcmp() To compare character of two string strcmp(string1,string2);

5. strrev() Used to reverse a string strrev(string);

6. strlwr() Used to convert upper case string into

lower case

strlwr(string);

7. strupr() Used to convert lower case string into

upper case

strupr(string);

8. strdup() Used to duplicate a string var = strdup(string);

3.4.3.1. strlen()

This function is used to count and return the number of characters present in a given

string and terminating null character is not counted while determining the length of the string.

SYNTAX:

Example:

#include<stdio.h>

#include<string.h>

#include<conio.h>

main()

{

char name[ ] = "MALAR";

int length;

length = strlen(name);

printf("\n STRLEN()\n=========\n");

printf("Length of the String = %d",length);

getch(); }

var = strlen(string);

Page 209: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

209

Explanation

In the above program, strlen() function is called and it counts the string length without

the NULL character.

3.4.3.2. strcpy()

This function is used to copy the contents from source string to destination string and

it almost works like string assignment operator.

SYNTAX:

Example:

#include<stdio.h>

#include<string.h>

#include<conio.h>

main()

{

char descstr[20];

char srcstr[20] = "FLOWERS";

strcpy(descstr,srcstr);

printf("\n STRCPY()\n=========\n");

printf("The Copied String is %s",descstr);

getch();

}

strcpy(destination string, source string);

OUTPUT

STRLEN()

=========

Length of the String = 5

Page 210: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

210

Explanation

In the above example, they have declared two array variables descstr and srcstr[20]. The

function strcpy copies the character of srcstr[20]to descstr[20].That is it copies character one by

one from the source string srcstr[20] to the destination string descstr[20].

3.4.3.3. strcat()

The strcat() function is used to concatenate or combine two strings together and forms

a new concatenated string.

SYNTAX:

Here the content of string2 is combined with string1 and it removes the null character (\0) of

string1 and places string2 from there.

Example:

#include<stdio.h>

#include<string.h>

#include<conio.h>

main()

{

char str1[30]="ABDUL";

char str2[30]=" KALAM";

strcat(str1,str2);

OUTPUT

STRCPY()

=========

The Copied String is FLOWERS

strcat(string1,string2);

Page 211: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

211

printf("\n STRCAT()\n=========\n");

printf("\nConcatenated String 1 :: %s",str1);

printf("\nContent in String 2 :: %s",str2);

getch();

}

Explanation

In the above example program, two strings are entered in character array str1[30] and

str2[30]. The strcat() function concatenates both the strings , i.e. second string is appended (or)

combined to the first string. By using printf() function it displays the content of the str1[30] with

concatenation of the two strings.

3.4.3.4. strcmp()

This function is used to compare two strings to find out whether they are same or

different. The two strings are compared character by character until the end of the string is

reached.

SYNTAX:

The function strcmp() compares str1 and str2, then returns:

RETURN VALUE EXPLANATION

OUTPUT

STRCAT()

=========

Concatenated String 1 :: ABDUL KALAM

Content in String 2 :: KALAM

strcmp(string1,string2);

Page 212: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

212

< 0 str1 is less than str2

= 0 str1 is equal to str2

> 0 str1 is greater than str2

Example:

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

{

int i,j,k,l;

char str1[25] = "KALAI";

char str2[25] = "MALAI";

clrscr();

i=strcmp(str1,str2);

j=strcmp(str1,"KALAI");

k=strcmp(str1,"KA");

l=strcmp(str1,"Kma");

printf("The Return Value is");

printf("\nI = %d\nJ = %d\nK = %d\nL = %d",i,j,k,l);

getch();

}

OUTPUT

The Return Value is

I = -2

J = 0

K = 76

L = -44

Page 213: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

213

Explanation

In the above program,

The first strcmp() between the two strings found to be mismatch, So the

difference between the two strings is found using the ASCII values. (ie The

ASCII value of K and M is 75 and 77, So the difference between K and M is -2

and also the ASCII value of K is less than M , So the return value should be < 0).

The second strcmp() between the two string found to be same, So it returns zero

value.

In the third strcmp() string1 is greater than string2 and the third character of

string1 found to be mismatch, So it return the mismatched character ASCII value

of L = 76 and also return value should be >0.

In the fourth strcmp() this the difference between the string1 and sting2 is -44 (ie

A=65, m=109 -> 65-109=-44)

3.4.3.5. strrev()

This function is used to reverse a string. In this function takes only one argument and

return one argument.

SYNTAX:

Example:

#include<stdio.h>

#include<conio.h>

#include<string.h>

var = strrev(string);

Page 214: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

214

main()

{

char str1[25] = "ENGINEERING";

puts("\n The Given String is :”);

gets(str1);

printf("\n Reversed String is : %s \n", strrev(str1));

getch(); }

Explanation

In the above program, it prints reverse string that is received by character array str1[25]

by using strrev() function.

3.4.3.6. strlwr()

This function can be used to onvert any string to a lower case. By passing any upper

case string to this function it converts to lower case.

SYNTAX:

Example:

#include<stdio.h>

#include<conio.h>

#include<string.h>

main()

{

char str1[25] = "ENGINEERING";

OUTPUT

The Given String is :Hello

Reversed String is : olleH

var = strlwr(upper_case_string);

Page 215: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

215

puts("\n Enter a string in uppercase : ");

gets(str1);

printf("\nConverted String is : %s ",strlwr(str1));

getch();

}

Explanation

In the above program, string is entered in capital letter. The string is passed to the

function strlwr(). This function converts the string to a lower case characters.

3.4.3.7. strupr()

This function is the same as strlwr( ) but the difference is that strupr( ) converts lower

case strings into upper case.

SYNTAX:

Example:

#include<stdio.h>

#include<conio.h>

#include<string.h>

main()

{

char str1[20];

puts("\n Enter a string in Lowercase : ");

gets(str1);

OUTPUT

Enter a string in uppercase : ENGINEERING

Converted String is : engineering

var = strupr(lower_case_string);

Page 216: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

216

printf("\n Converted String is : %s",strupr(str1));

getch();

}

Explanation

In the above program, string is entered in lower case. The string is passed to the function

strupr(). This function converts the string to a upper case.

3.4.3.8. strdup()

This function is used for duplicating a given string at the allocated memory which is

pointed by a pointer variable.

SYNTAX:

Example:

#include<stdio.h>

#include<conio.h>

#include<string.h>

main()

{

char str1[20],*str2;

puts("Enter string : ");

gets(str1);

str2=strdup(str1);

printf("\n Original String : %s \n Duplicated String : %s ",str1,str2);

getch();

OUTPUT

Enter a string in Lowercase : string handling

Converted String is : STRING HANDLING

string2=strdup(string1);

Page 217: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

217

}

Explanation

In the above program, character array str1[20] and pointer variable *str2 are declared.

String is entered in character array str1[20]. The strdup() function copies contents of str1[20]

array to pointer variable *str2. The printf() function displays the contents of both the variables

which are same.

3.4.4. ADDITIONAL STRING HANDLING FUNCTIONS

The many string handling library functions which are listed below.

S.NO FUNCTIONS SYNTAX DESCRIPTION

1. strncpy() strncpy(destination,source,n);

Where

n is the argument.

Copies characters of a string to another

string up to the specified length i.e.

specified length is based on the value

assigned to variable „n‟.

2. stricmp() stricmp (string, string);

Compares two strings (No difference

between small and upper case letters)

3. strncmp() strncmp(source,

target,argument);

Where

Argument – no of characters up to

which the comparison is to be

done.

Compares the first „n‟ characters of two

strings for equality.

4. strnicmp() strnicmp (string1, string2,

length);

Compares the first n characters of two

strings without regarding the case.

OUTPUT Enter string :Good Day

Original String : Good Day

Duplicated String : Good Day

Page 218: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

218

Where

Length - The maximum length of

the comparison.

5. strchr() strchr (string, char_as_string);

These functions search a string for an

individual character and return the first

or last occurrence of that character

within the string. The characters within

a string are numbered starting at zero.

6. strrchr() strrchr (string, char_as_string);

Determines last occurrence of a given

character in a string.

7. strstr() strstr (string1, string2);

Determines first occurrence of a given

string in another string.

8. strncat() strncat(dest-string1,source-

string2,n);

Where

n – number of character to append.

Appends source string to destination

string up to specified length

9. strset() strset(string,symbol); This function replaces every character

of a string with the symbol given by the

programmer, i.e. the elements of the

strings are replaced with the arguments

given by the programmer.

10. strnset() strnset(string,symbol,n);

Where

n – No of character to be replaced

Sets specified number of character of

string with a given argument or

symbol.

11. strspn() strspn(string1,string2); This function returns the position of the

string from where the source array does

not match with the target one.

12. strpbrk() strpbrk(text1, text2); Searches the first occurrence of the

character in a given string and then it

Page 219: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

219

displays the string starting from that

character.

Example

#include<stdio.h>

#include<conio.h>

#include<string.h>

char str1[15]="wonderful",str2[15]="beautiful";

int i;

char string[20] = "computer programs",*stnset;

char symbol = 'C',str3[40];

char *ptr,*ptr1,x='t',u='s';

main()

{

void sincpy(),sncat();

void sicmp(),sncmp(),snicmp();

void schr(), srrchr();

void sstr();

void sset(), snset();

void sspn(),spbrk();

getch();

return 0;

}

void sINcpy()

{

//CPY N characters from str1 to str2

printf("\nstrINcpy()\n__________\n\n");

printf("Before Copying String1 = %s & String2 = %s\n",str1,str2);

printf("strcpy() = %s\n",strncpy(str2,str1,6));

Page 220: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

220

printf("After Copying String1 = %s String2 = %s\n",str1,str2);

}

void sncat()

{

//Append 4 character from source string to destination string

printf("\nstrNcat()\n__________\n");

printf("strncat() = %s\n",strncat("MAY I ","COME IN",4));

}

void sicmp()

{

//Cmp is Not case sensitive

printf("\nstrIcmp()\n__________\n\n");

//ASCII VALUE P=80 & D=68 (80-68=12)

printf("stricmp() = %d\n",stricmp ("HELP", "hELD"));

//ASCII VALUE p=112 & Space=32 (112-32=80)

printf("UnMatched stricmp() = %d\n", stricmp("Apple","ap"));

}

void sncmp()

{

//CMP is Case sensitive

printf("\nstrNcmp()\n__________\n");

//ASCII VALUE l=108 & i=105 (108-105=3)

printf("strncmp() = %d\n",strncmp("Hello","helicopter",4));

}

void snicmp()

{

//CMP is Not case sensitive

printf("\nstrNIcmp()\n_________________\n\n");

Page 221: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

221

//ASCII VALUE l=108 &l=108(108-108=0)(if n is 4 thenl=108&p=112(108-

112=-4))

printf("strnicmp() = %d\n",strnicmp("Hello","help", 3));

}

void schr()

{

//Find out the first occurence position of given character

printf("\nstrCHR()\n__________\n\n");

strcpy(str3,"This is a string");

ptr=strchr(str3,x);

if(ptr)

printf("The character %c is at position: %d\n",x,ptr-str3);

}

void srrchr()

{

//Find out the last occurence position of given character

printf("\nstrRCHR()\n__________\n\n");

strcpy(str3,"This is a string");

ptr1=strrchr(str3,u);

if(ptr1)

printf("The character %c is at position: %d\n",u,ptr1-str3);

}

void sstr()

{

//Finds the 1st occurrence of a substring in another string

printf("\nstrSTR()\n__________\n");

printf("strstr() = %s\n",strstr("Borland International","nation"));

printf("strstr2() = %s\n",strstr("Borland International","l"));

}

Page 222: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

222

void sset()

{

//Replace every character of a string with another character or symbol

printf("\nstrSET\n__________\n\n");

printf("Before strset(): %s\n", string);

strset(string, symbol);

printf("After strset(): %s\n", string);

}

void snset()

{

//Replace N no of character of a string with another character or symbol

printf("\nstrNSET()\n__________\n\n");

printf("string before strnset: %s\n", string);

stnset=strnset(string,symbol,9);

printf("string after strnset: %s\n", stnset);

}

void sspn()

{

//Returns the positionof the string from where there is a mismatch

printf("\nstrSPN()\n__________\n\n");

printf("strspn() = %d\n",strspn("GOOD MORNING","GOOD BYE"));

}

void spbrk()

{

//Display the first occurence of the given character from the string

printf("\nstrPBRK()\n__________\n\n");

printf("strpbrk() = %s",strpbrk("INDIA IS GREAT","G"));

getch();

}

Page 223: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

223

OUTPUT

strINcpy() Before Copying String1 = wonderful &

String2 = beautiful strcpy() = wonderful After Copying String1 = wonderful

String2 = wonderful

strIcmp() stricmp() = 12 UnMatched stricmp() = 80

strNcmp() strncmp() = -32

strNIcmp()

strnicmp() = 0 strCHR()

The character t is at position: 11

strRCHR() The character s is at position: 10

strSTR() strstr() = national

strstr2() = land International strNcat()

strncat() = MAY I COME

strSET Before strset(): computer programs After strset(): CCCCCCCCCCCCCCCCC

strNSET() string before strnset:CCCCCCCCCCCCCCCCC

string after strnset:CCCCCCCCCCCCCCCCC

strSPN() strspn() = 5

strPBRK() strpbrk() = GREAT

3.4.5. STRING ARRAYS

A string is a collection of characters. A string constant is a one dimensional array of

characters terminated by a null („\0‟) character.

Eg: char name[] = {„A‟,‟S‟,‟W‟,‟I‟,‟N‟,‟\0‟};

Where

‘\0’- It is a null character and specifies end of the string.

Terminating the string with null „\0‟ is important, because it is the only way the functions

that work with a string can know where the string ends.

A S W I N \0

Page 224: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

224

The last character is called ‘\0’ null character, it looks like two characters but it is actually one

character. Each character in the array occupies one byte memory and the last character is always

„\0‟.

C also provides a shortcut method for initializing strings.

Eg: char name[]=”ASWIN”;

Note that in the above declaration ‘\0’ is not necessary. „C‟ insert „\0‟ automatically at the end of

the string.

Eg: Program to print the character string from the array

#include<stdio.h>

main()

{

char name[]=”ASWIN”;

puts(name);}

#include<stdio.h>

main()

{

char name[]=”ASWIN”;

int i=0;

while (name[i]!=’\0’)

{

printf(“%c”,name[i]);

i++;

}}

EXPLANATION:

Here every character in an array is checked whether it is a null character is not. If it is a

null character then, the control is transferred to the outside of the loop, which is the end of the

program.

OUTPUT

ASWIN

Page 225: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

225

3.4.6. SIMPLE PROGRAMS

3.4.6.1 SORTING

(a) INSERTION SORT

In this type of sorting takes place by inserting a particular element at the appropriate

position, that‟s why the name- insertion sorting. In the First iteration, second element A[1] is

compared with the first element A[0]. In the second iteration third element is compared with first

and second element. In general, in every iteration an element is compared with all the elements

before it. While comparing if it is found that the element can be inserted at a suitable position,

then space is created for it by shifting the other elements one position up and inserts the desired

element at the suitable position.

//PROGRAM FOR INSERTION SORT

#include<stdio.h>

void main()

{

int A[20], N, Temp, i, j;

clrscr();

printf("\n\n\t ENTER THE NUMBER OF TERMS...: ");

scanf("%d", &N);

printf("\n\t ENTER THE ELEMENTS OF THE ARRAY...:");

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

{

gotoxy(25,11+i);

scanf("\n\t\t%d", &A[i]);

}

for(i=1; i<N; i++)

{

Page 226: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

226

Temp = A[i];

j = i-1;

while(Temp<A[j] && j>=0)

{

A[j+1] = A[j];

j = j-1;

}

A[j+1] = Temp;

}

printf("\n\tTHE ASCENDING ORDER LIST IS...:\n");

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

printf("\n\t\t\t%d", A[i]);

getch();

}

(b) SELECTION SORT

To sort the data in ascending order, the first element A[0] is compared with all the other

elements till the end of the array. If it is greater than any other the elements then they are

interchanged. So after the first iteration of the outer for loop smallest element will be placed at

the first position.

OUTPUT

ENTER THE NUMBER OF TERMS...: 5

ENTER THE ELEMENTS OF THE ARRAY...:

12 4 124 67 1

THE ASCENDING ORDER LIST IS...:

1

4

12

67

124

Page 227: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

227

SELECTION SORT IMPLEMENTATION USING ARRAY

#include<stdio.h>

int main()

{

int s,i,j,temp,a[20];

printf("Enter total elements: ");

scanf("%d",&s);

printf("Enter %d elements: ",s);

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

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

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

{

for(j=i+1;j<s;j++)

{

if(a[i]>a[j])

{

temp=a[i];

a[i]=a[j];

a[j]=temp;

} } }

printf("After sorting is: ");

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

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

return 0;

Page 228: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

228

}

(c) BUBBLE SORT

The entered integers are stored in the array. Here, to sort the data in ascending order, any

number is compared with the next numbers for orderliness. i.e. first element A[0] is compared

with the second element A[1]. If forth is greater than the prior element then swapping them, else

no change. Then second element is compared with third element, and procedure is continued.

Hence, after the first iteration of the outer for loop, largest element is placed at the end of the

array. In the second iteration, the comparisons are made till the last but one position and now

second largest element is placed at the last but one position.

BUBBLE SORT IMPLEMENTATION USING ARRAY

#include<stdio.h>

int main()

{

int s,temp,i,j,a[20];

printf("Enter total numbers of elements: ");

scanf("%d",&s);

printf("Enter %d elements: ",s);

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

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

OUTPUT

Enter total elements: 6

Enter 6 elements: 12 4 62 78 24 3

After sorting is: 3 4 12 24 62 78

Page 229: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

229

//Bubble sorting algorithm

for(i=s-2;i>=0;i--)

{

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

{

if(a[j]>a[j+1])

{

temp=a[j];

a[j]=a[j+1];

a[j+1]=temp;

} } }

printf("After sorting: ");

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

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

return 0;

}

(d) QUICK SORT

Quick sort is a divide and conquer algorithm. Quick sort first divides a large list into two smaller

sub-lists: the low elements and the high elements. Quick sort can then recursively sort the sub-

lists.

The steps are:

1. Select an element, called a pivot, from the list.

OUTPUT

Enter total numbers of elements: 7

Enter 7 elements: 12 5 75 34 23 2 35

After sorting: 2 5 12 23 34 35 75

Page 230: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

230

2. Reorder the list so that all elements with values less than the pivot come before the pivot,

while all elements with values greater than the pivot come after it (equal values can go

either way). After this partitioning, the pivot is in its final position. This is called the

partition operation.

3. Recursively apply the above steps to the sub-list of elements with smaller values and

separately the sub-list of elements with greater values.

QUICK SORT USING ARRAY

#include<stdio.h>

void quicksort(int [10],int,int);

int main()

{

int x[20],size,i;

printf("Enter size of the array: ");

scanf("%d",&size);

printf("Enter %d elements: ",size);

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

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

quicksort(x,0,size-1);

printf("Sorted elements: ");

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

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

return 0;

}

Page 231: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

231

void quicksort(int x[10],int first,int last)

{

int pivot,j,temp,i;

if(first<last)

{

pivot=first;

i=first;

j=last;

while(i<j)

{

while(x[i]<=x[pivot]&&i<last)

i++;

while(x[j]>x[pivot])

j--;

if(i<j)

{

temp=x[i];

x[i]=x[j];

x[j]=temp;

}

}

temp=x[pivot];

x[pivot]=x[j];

x[j]=temp;

quicksort(x,first,j-1);

Page 232: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

232

quicksort(x,j+1,last);

}

}

3.4.6.2. SEARCHING

(a) BINARY SEARCH

#include<stdio.h>

int main()

{

int a[10],i,n,m,c=0,l,u,mid;

printf("Enter the size of an array: ");

scanf("%d",&n);

printf("Enter the elements in ascending order: ");

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

{

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

}

printf("Enter the number to be search: ");

scanf("%d",&m);

OUTPUT

Enter size of the array: 5

Enter 5 elements: 3 8 0 1 2

Sorted elements: 0 1 2 3 8

Page 233: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

233

l=0,u=n-1;

while(l<=u)

{

mid=(l+u)/2;

if(m==a[mid])

{

c=1;

break;

}

else if(m<a[mid])

{

u=mid-1;

}

else

l=mid+1;

}

if(c==0)

printf("The number is not found.");

else

printf("The number is found.");

return 0;

}

OUTPUT

Enter the size of an array: 5

Enter the elements in ascending order: 4 7 8 11 21

Enter the number to be search: 11

The number is found.

Page 234: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

234

(b)BINARY SEARCH USING FUNCTION RECURSION

#include<stdio.h>

int main()

{

int a[10],i,n,m,c,l,u;

printf("Enter the size of an array: ");

scanf("%d",&n);

printf("Enter the elements of the array: " );

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

{

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

}

printf("Enter the number to be search: ");

scanf("%d",&m);

l=0,u=n-1;

c=binary(a,n,m,l,u);

if(c==0)

printf("Number is not found.");

else

printf("Number is found.");

return 0;

}

Page 235: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

235

int binary(int a[],int n,int m,int l,int u)

{

int mid,c=0;

if(l<=u)

{

mid=(l+u)/2;

if(m==a[mid])

{

c=1;

}

else if(m<a[mid])

{

return binary(a,n,m,l,mid-1);

}

else

return binary(a,n,m,mid+1,u);

}

else

return c;

}

OUTPUT

Enter the size of an array: 5

Enter the elements of the array: 8 9 10 11 12

Enter the number to be search: 8

Number is found.

Page 236: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

236

3.4.6.3 MATRIX OPERATIONS

(a) PROGRAM FOR MULTI DIMENSIONAL ARRAY

#include<stdio.h>

#include<conio.h>

main()

{

int a,b,c,d,arr[3][3][3][3];

printf("MULTI DIMENSIONAL ARRAY\n---------------\n");

for(a=0;a<3;a++)

for(b=0;b<3;b++)

for(c=0;c<3;c++)

for(d=0;d<3;d++)

arr[a][b][c][d]=a+b+c+d;

for(a=0;a<3;a++)

{

printf("\n");

for(b=0;b<3;b++)

{

for(c=0;c<3;c++)

{

for(d=0;d<3;d++)

printf("%d",arr[a][b][c][d]);

printf("\n");

} } } getch(); }

OUTPUT

MULTI DIMENSIONAL ARRAY

-------------------------------------------

0 1 2 1 2 3 2 3 4

1 2 3 2 3 4 3 4 5

2 3 4 3 4 5 4 5 6

1 2 3 2 3 4 3 4 5

2 3 4 3 4 5 4 5 6

3 4 5 4 5 6 5 6 7

2 3 4 3 4 5 4 5 6

3 4 5 4 5 6 5 6 7

4 5 6 5 6 7 6 7 8

Page 237: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

237

(b) MATRIX ADDITION

#include<stdio.h>

#include<conio.h>

main()

{

int a[5][5],b[5][5],c[5][5],r1,c1,r2,c2,i,j;

printf("MATRIX ADDITION \n------------------\n");

printf("Enter rows and columns of A:");

scanf("%d%d",&r1,&c1);

printf("Enter row and columns of B:");

scanf("%d%d",&r2,&c2);

printf("Enter values of matrix a:\n");

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

{

for(j=0;j<c1;j++)

{

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

}

}

printf("Enter the values of B matrix:\n");

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

{

for(j=0;j<c2;j++)

Page 238: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

238

{

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

}

}

if((r1==r2)&&(c1==c2))

{

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

{

for(j=0;j<c1;j++)

{

c[i][j]=a[i][j]+b[i][j];

}

}

}

else

printf("Can't do addition.");

printf("Addition of matrices A and B:\n");

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

{

for(j=0;j<c1;j++)

{

printf("\t%d",c[i][j]);

}

printf("\n");

}

getch();

}

OUTPUT

MATRIX ADDITION

------------------

Enter rows and columns of A: 2 2

Enter row and columns of B: 2 2

Enter values of matrix a:

2 4 6 2

Enter the values of B matrix:

Page 239: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

239

(c) MATRIX MULTIPLICATION

#include<stdio.h>

#include<conio.h>

main()

{

int a[25][25],b[25][25],c[25][25],i,j,k,r,s;

int m,n;

printf("MATRIX MULTIPLICATION \n------------------\n");

printf("\n ENTER THE ROWS AND COLUMNS OF A MATRIX...");

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

printf("\n ENTER THE ROWS AND COLUMNS OF B MATRIX...");

scanf("%d%d",&r,&s);

if(m!=r)

printf("\n THE NUMBERS CANNOT BE MULTIPLIED\n");

else

{

printf("\n ENTER THE ELEMENTS OF A MATRIX:\n");

Page 240: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

240

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

{

for(j=0;j<n;j++)

scanf("\t%d",&a[i][j]);

}

printf("\n ENTER THE ELEMENTS OF B MATRIX:\n");

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

{

for(j=0;j<n;j++)

scanf("\t%d",&b[i][j]);

}

printf("\nTHE ELEMENTS OF A MATRIX");

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

{

printf("\n");

for(j=0;j<n;j++)

printf("\t%d",a[i][j]);

}

printf("\nTHE ELEMENTS OF B MATRIX");

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

{

printf("\n");

for(j=0;j<n;j++)

printf("\t%d",b[i][j]);

}

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

{

Page 241: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

241

printf("\n");

for(j=0;j<n;j++)

{

c[i][j]=0;

for(k=0;k<m;k++)

c[i][j]=c[i][j]+a[i][k]*b[k][j];

}

}

}

printf("THE MULTIPLICATION OF TWO MATRIXES");

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

{

printf("\n");

for(j=0;j<n;j++)

printf("\t%d",c[i][j]);

}

getch();

}

OUTPUT

MATRIX MULTIPLICATION

--------------------------------------

ENTER THE ROWS AND COLUMNS OF A MATRIX...2 2

ENTER THE ROWS AND COLUMNS OF B MATRIX...2 2

ENTER THE ELEMENTS OF A MATRIX:

2 3 6 8

ENTER THE ELEMENTS OF B MATRIX:

4 1 6 5

THE ELEMENTS OF A MATRIX

2 3

6 8

THE ELEMENTS OF B MATRIX

4 1

6 5

THE MULTIPLICATION OF TWO MATRIXES

Page 242: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

242

(d) TRANSPOSE MATRIX

#include <stdio.h>

#include<conio.h>

main()

{

int a[10][10],b[10][10],i,j,m,n;

printf("MATRIX TRANSPOSE\n----------------\n");

printf("Enter number of Row and Column of matrix : ");

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

printf("Enter the element of matrix \n");

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

for(j=0;j<m;++j)

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

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

for(j=0;j<m;++j)

b[i][j]=a[j][i];

printf("\n Transpose of the matrix is : \n");

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

{

Page 243: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

243

for(j=0;j<m;++j)

printf("%d",b[i][j]);

printf("\n");

}

getch();

}

UNIT - IV

FUNCTIONS

Definition

A function is a self-contained block or a sub-program of one or more statements that

performs a special task when performed.

A function is a set of instructions that are used to perform specified tasks which repeatedly

occurs in the main program.

A C program is nothing but a combination of one or more functions. Every C program starts with a user defined function main().

OUTPUT

MATRIX TRANSPOSE

---------------------------

Enter number of Row and Column of matrix : 3 3

Enter the element of matrix

1 2 3

3 2 5

2 6 4

Transpose of the matrix is :

132

226

354

Page 244: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

244

The C language supports two types of functions. They are:

1. Library Functions.

2. User defined functions

Library functions

The C standard library consists of wide variety of header files which can be

included into a programmer’s project with a single directive.

Each header file contains one or more function declarations, data type definitions and macros.

The library provides a basic set of mathematical, string manipulation, type conversions, file and console-based I/O functions.

Use of library functions

The main advantage of the standard library is that it provides an easy working environment than other languages and consequently porting C to a new platform is relatively easy.

C language provides built-in functions or intrinsic functions called Library Functions. The compiler itself evaluates these functions.

List of Library functions

Page 245: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

245

User

Defined

Functions

The functions defined by the users according to their requirements are called user-defined functions. The users can modify the function according to their requirement.

The user

has full

scope to

implement

their own

ideas in the

function.

They are written by the programmer to perform a particular task that is repeatedly used in main program.

These functions are helpful to break down a large program in to a number of smaller functions.

Need for user defined functions

When a complex program is written under the main() function then it leads

to number of problems like,

o The program becomes too large and complex.

o The users can not go through at a glance.

o The task of debugging, testing and maintenance becomes difficult.

S.No

Functions / Syntax

Meaning

Example 1 sqrt(x) √x sqrt(25)

2 log(x) logex log(7.5)

3 abs(x) | x | abs(-75)

4 fabs(x) | x | fabs(4.65)

5 exp(x) ex exp(5.3)

6 pow(x, y) xy pow(3, 2)

7

ceil(x) Rounding x to the next integer

value

ceil(5, 6)

8 fmod(x, y) Returns the remainder of x/y fmod(7, 3)

9

rand( ) Generates a positive random

number

rand( )

10

srand(v) To initialize the random

number generator

srand(8)

11 sin(x) sin value of x sin(30)

12 cos(x) cos value of x cos(60)

13 tan(x) tan value of x tan(90)

14

toascii(x) Returns the integer value for

the particular character

toascii(a)

15

tolower(x) To convert the character to

lowercase

tolower(‘Z’)

16

toupper(x) To convert the character to

upper case

toupper(‘a’)

Page 246: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

246

If the program is divided into parts, then each part may be independently

coded and later combined into a single program. These sub-programs are

called functions and much easier to understand, debug and test.

Advantages of user defined functions

The length of the source program can be reduced by dividing in into the smaller

functions.

By using functions it is very easy to locate and debug an error.

The user-defined function can be used in many other source programs

whenever necessary.

Functions avoid coding of repeated rogramming of the similar instructions.

Functions facilitate top-down programming approach.

The general syntax is as follows:

<data type of the return value> function name(argument/parameter list)

{

variable declaration;

statement 1;

statement 2;

return(value);

}

Working of a Function

The working of a function is given below:

void main()

{

Page 247: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

247

-----;

-----;

abc(x,y); -> Function call

x, y are actual arguments

-----

-----

}

abc(int l, int K) Function Definition

{ l, k are formal or dummy arguments

---

----

----

return(); return value

}

1. Actual arguments: The arguments of calling functions are called actual arguments.

2. Formal/Dummy arguments: The arguments of called functions are called formal or

dummy arguments.

3. Function Name: A name given to the function similar to a name given to a variable.

4. Argument/Parameter List: The variable name enclosed within the parenthesis is

the argument list.

5. Function call: A C compiler executes the function when a semi-colon is followed by

function name.

6. Variables: There are two kinds of variables. They are 1. local and 2. global.

7. Local variables: The variables which are declared inside the function definition is

called local variable.

8. Global Variable: Variables which are declared outside the main function is called

global variable.

Page 248: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

248

9. Return value: The result obtained by the function is sent back by the function to the

function call through the return statement. It returns one value per call.

Function prototypes

The Function prototypes are classified into four types. They are:

1. Function with no argument and no return value.

2. Function with no argument and with return value.

3. Function with argument and no return value.

4. Function with argument and with return value.

1. Function with no argument and no return value:

Neither data is passed through the calling function nor the data is sent back from the

called function.

There is no data transfer between calling and the called function.

The function is only executed and nothing is obtained.

The Function acts independently. It reads data values and print result in the same

block.

Example program:

#include<stdio.h>

void add();

void main()

{

clrscr();

add();

getch();

}

void add()

{

int a,b,c;

Page 249: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

249

a=10;

b=5;

c=a+b;

printf("\nThe sum=%d",c);

}

OUTPUT:

The sum=15

2. Function with no argument and with return value

In the above type of function, no arguments are passed through the main

function. But the called function returns the value.

The called function is independent. It reads values from the keyboard and returns

value to the function call.

Here both the called and calling functions partly communicate with each other.

Example program:

#include<stdio.h>

int add();

void main()

{

int a,b,c;

clrscr();

c=add();

printf("\nThe sum=%d",c);

getch();

}

int add()

{

int a,b,c;

a=10;

b=5;

c=a+b;

return(c);

}

Page 250: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

250

OUTPUT:

The sum=15

3. Function with argument and no return value

In the above type of function, arguments are passed through the calling function.

The called function operates on the values. But no result is sent back.

The functions are partly dependent on the calling function. The result obtained is

utilized by the called function.

Example program;

#include<stdio.h>

void add(int,int);

void main()

{

int a,b;

clrscr();

a=10;b=5;

add(a,b);

getch();

}

void add(int a,int b)

{

int c;

c=a+b;

printf("\nThe sum=%d",c);

}

OUTPUT:

The sum=15

4. Function with argument and with return value

Page 251: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

251

In the above type of function, data is transferred between calling and called

function.

Both communicate with each other.

Example Program:

#include<stdio.h>

int add(int,int);

void main()

{

int a,b,c;

clrscr();

a=10;b=5;

c=add(a,b);

printf("\nThe sum=%d",c);

getch();

}

void add(int a,int b)

{

int c;

c=a+b;

return(c);

}

OUTPUT:

The sum=15

PARAMETER PASSING METHODS:

There are two ways by which arguments are passed in the function. They are:

1. Call by value.

2. Call by reference.

Page 252: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

252

1. Call by value:

In this type, values of actual arguments are passed to the formal arguments and the

operation is done on the dummy arguments. Any change made in the formal arguments

does not affect the actual arguments because formal arguments are photocopies of actual

arguments.

Example Program:

#include<stdio.h>

void swap(int,int);

void main()

{

int a,b;

clrscr();

a=10;

b=5;

swap(a,b);

getch();

}

void swap(int a,int b)

{

int c;

c=a;

a=b;

b=c;

printf("\nAfter swapping\n");

Page 253: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

253

printf("\na=%d",a);

printf("\nb=%d",b);

}

OUTPUT:

After swapping

a=5

b=10

2. Call by Reference:

In this type, addresses are passed. Function operates on addresses rather than values.

Here, the formal arguments are pointers to the actual arguments. Here changes are made in

the arguments as permanent.

Example Program:

#include<stdio.h>

void swap(int*,int*);

void main()

{

int a,b;

clrscr();

a=10;b=5;

swap(&a,&b);

printf("\nAfter swapping\n");

printf("\na=%d",a);

printf("\nb=%d",b);

Page 254: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

254

getch();

}

void swap(int *x,int *y)

{

int c;

c=*x;

*x=*y;

*y=c;

}

OUTPUT:

After swapping

a=5

b=10

Recursion

• Recursive Function:– a function that calls itself

• Directly or indirectly

• Each recursive call is made with a new, independent set of arguments

• Previous calls are suspended

• Allows very simple programs for very complex problems

The Nature of Recursion

One or more simple cases of the problem (called the stopping cases) have a simple non-recursive solution.

The other cases of the problem can be reduced (using recursion) to problems that are closer to stopping cases.

Page 255: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

255

Eventually the problem can be reduced to stopping cases only, which are relatively easy to solve.

In general:

if (stopping case)

solve it

else

reduce the problem using recursion

Simplest Example

int factorial(int x)

{

if (x <= 1)

return 1;

else

return x * factorial (x-1);

} // factorial

Recursive definition:

4! = 4 * 3 * 2 * 1 = 4 * 3!

Page 256: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

256

n! = n * (n-1)!

Problem: Solve the Towers of Hanoi for N disks.

Analysis: Solution consists of a printed list of individual disk moves. We need recursion

that can be used to move any number of disks from one tower to another, using the third

tower as a temporary tower.

factorial(4)=

4 * factorial(3)

We can’t evaluate

1! directly – call

factorial(1)

We can’t evaluate

2! Directly, so we

call factorial(2)

We can’t evaluate 3!

directly, so we call

factorial (3)

We must call

factorial(0)

BASE CASE:

factorial(0)= 1

Returns 1

and terminates

Returns 1*1

and terminates

Returns 2*1 =2

and terminates

Returns 3*2 = 6 and

terminates

factorial(3)=

3 * factorial(2)

factorial(1)=

1 * factorial(0)

factorial(2)=

2 * factorial(1)

Page 257: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

257

Inputs: n: integer,

start:’A’, ‘B’, or ‘C’,

finish:’A’, ‘B’, or ‘C’

temp:’A’, ‘B’, or ‘C’

Output: a list of individual disk moves.

Algorithm

if (n == 1) /* stopping case */

move a single disk from start to finish

else

-Move n-1 disks from start to temp using finish as temporary tower.

- Move a single disk from start to finish

- Move n-1 disks from temp to

finish using start as temporary tower

In C:

void tower(int n, char start, char finish, char temp)

{

if (n == 1)

Page 258: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

258

printf(“Move from %c to %c\n”, start, finish);

else {

tower(n-1, start, temp, finish);

printf(“Move from %c to %c \n”, start, finish);

tower(n-1, temp, finish, start);

}

}

Test:

tower(3,„A‟,‟C‟, ‟B‟);

Output:

Move from A to C

Move from A to B

Move from C to B

Move from A to C

Move from B to A

Move from B to C

Move from A to C

Towers of Hanoi: Solution

Page 259: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

259

Page 260: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

260

POINTERS

Definition: A pointer is a memory variable that stores a memory address. Pointers can

have any name that is legal for other variable and it is declared in the same way like any

other variable but it is always denoted by ‘*’ operator.

Features of Pointers:

Pointers save the memory space.

Execution time with pointer is faster because data is manipulated with the address.

The memory is accessed efficiently with the pointers.

Dynamically, memory is allocated.

Pointers are useful for representing two-dimensional and multi-dimensional arrays.

Pointer Declaration:

Pointer variables can be declared as follows:

The syntax is as follows:

int *x;

‘x’ is an integer pointer and it tells to the compiler that it holds the address of any integer

variable.

Page 261: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

261

The ‘*’ operator is called indirection operator or deference operator.

Example:

int a,*b;

a=10;

b=&a;

The primary memory is represented as follows:

a (Variable name) b

10 2012

2012(Memory Address)

Example Program:

#include <stdio.h>

void main()

{

int a,*x;

clrscr();

Page 262: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

262

a=20;

x=&a;

printf("\nThe value of a =%d",a);

printf("\nThe address of a =%u",x);

getch();

}

OUTPUT:

The value of a =20

The address of a =65524

Pointers and Arrays:

Array is a collection of similar data type elements stored under common name. When

we declare an array the consecutive memory locations are located to the array of

elements. The elements of an array can be efficiently accessed by using pointers.

The size of the data type with the pointer variables refers to, depends on the data type

pointed by the pointer.

Page 263: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

263

A pointer when incremented, always points to a location after skipping the number of

bytes required for the data type pointed to by it.

Example:

int a[5] = {10,20,30,40,50};

int *b;

b = a;

a[0] a[1] a[2] a[3] a[4]

10 20 30 40 50

4000 4002 4004 4006 4008

a[5] means the array ‘a’ has 5 elements and of integer data type.

‘b’ is a pointer variable which holds the base address of the array ‘a’.

i.e., b = &a[0].

Example Program:

#include <stdio.h>

Page 264: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

264

void main()

{

int a[10],i,*ptr,n;

clrscr();

printf("\nEnter the size of the array");

scanf("%d",&n);

printf("\nEnter the data into the array one by one");

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

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

ptr=a;

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

{

printf("\nThe value=%d",a[i]);

printf("\nThe address=%u",(ptr+i));

}

getch();

}

Page 265: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

265

OUTPUT:

Enter the size of the array4

Enter the data into the array one by one

1

2

3

4

The value=1

The address=65502

The value=2

The address=65504

The value=3

The address=65506

The value=4

Page 266: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

266

The address=65508

Pointer Arithmetic

Arithmetic operations can be performed on pointers

Increment/decrement pointer (++ or --)

Add an integer to a pointer( + or += , - or -=)

Pointers may be subtracted from each other

Operations meaningless unless performed on an array

5 element int array on machine with 4 byte ints

• vPtr points to first element v[ 0 ]

at location 3000 (vPtr = 3000)

• vPtr += 2; sets vPtr to 3008

vPtr points to v[ 2 ] (incremented by 2), but the machine has 4 byte ints, so

it points to address 3008

Page 267: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

267

Addition pointers

Returns number of elements from one to the other. If

vPtr = v[ 2 ];

vPtr2 = v[ 0 ];

Ptr+ vPtr2 would produce 2

Subtracting pointers

Returns number of elements from one to the other. If

vPtr2 = v[ 2 ];

Page 268: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

268

vPtr = v[ 0 ];

Ptr2 - vPtr would produce 2

Pointer comparison ( <, == , > )

See which pointer points to the higher numbered array element.Also, see if a pointer

points to 0

PANIMALAR INSTITUTE OF TECHNOLOGY (JAISAKTHI

EDUCATIONAL TRUST)

CHENNAI 600 123

Page 269: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

269

DEPARTMENT OF CSE / IT

GE6151 – COMPUTER PROGRAMMING

I YEAR – I SEMESTER

(Common to all the Branches)

LECTURE NOTES

Page 270: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

270

UNIT V – STRUCTURES AND UNIONS

5. STRUCTURES AND UNIONS

Introduction – need for structure data type – structure definition – Structure declaration – Structure within a

structure - Union - Programs using structures and Unions – Storage classes, Pre-processor directives

5.1 INTRODUCTION

As we know that, Array is a collection of elements of same type, but many times we have to store the elements of different data types.

Suppose a student record is to be stored, then for storing the record we have to group together all the information such as roll number, name, marks, grade which may be of different data types. So, we need structure.

Structure is a collection of different variables under single name.

The structure is a convenient way of grouping several pieces of related information together.

5.2 NEED FOR STRUCTURE DATA TYPE

A variable stores a single value of a data type.

Arrays can store many values of similar data type.

In real life, we need to have different data types. Eg) to maintain employees information we should have information such as their name, age, qualification, salary etc.

Here, to maintain the information of employees, dissimilar data types are required.

For tackling such mixed data types, a special data type provided by C called structure is needed.

Page 271: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

271

5.3 STRUCTURE DEFINITION

A structure is a collection of one or more variables of different data types, grouped together under a single name.

Consider the data of student mark analysis: Roll number, name, marks, and average. A structure data type called

student can hold all this information:

struct student

{

char name[20];

int rollno;

int marks[8];

float avg;

};

5.4 STRUCTURE DECLARATION

The structure can be declared with the keyword struct following the name and opening brace with data elements

of different type, and then closing brace with semicolon. Structure can be declared as follows:

Page 272: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

272

struct structure_name

{

Data type variable1;

Data type variable2;

.

.

.

Data type variablen;

};

struct structure_name v1,v2,….,vn;

where v1,v2,….,vn are structure variables.

Example: Declaring a structure for Student record

struct student

{

int rollno;

char name[25];

int marks[8];

float avg;

};

struct student s1,s2,s3;

The structure can be declared with the keyword struct following the name and opening brace with data elements of different type, then closing brace with semicolon.

The individual structure elements are called as members.

members

Page 273: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

273

Name given to structure is called tag. Eg: student

Structure member may be of different data type including user defined data type also.

5.4.1 Rules for declaring a structure:

A structure must end with a semicolon

The structure appears at the top of the source program

Each structure element must be terminated

The structure variable must be accessed with dot(.) operator

5.4.2 Accessing structure elements:

After declaring the structure type, variables, and members, the member of the structure can be accessed by using

the structure variable along with the dot (.) operator.

struct student

{

int rollno;

char name[25];

int marks[8];

float avg;

};

struct student s;

For accessing the structure members for the above example,

Page 274: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

274

s.rollno; s.name; s.marks; s.avg;

where ‘s’ is the structure variable.

5.4.3 Initialization of structure:

Like normal variables, the structure variables can also be initialized, but this initialization can be made at the

compile time. The initialization can be done in 2 ways:

1. struct

{

int rollno;

float avg;

} student = {2, 67.99};

2. struct student

{

int rollno;

float avg;

};

main( )

{

struct student p1={2,67.99};

Page 275: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

275

struct student p2={3,88.12};

}

5.4.4 Rules for initializing structure:

The individual data members of structure cannot be initialized.

The structure variables can be initialized at compile time only.

The order of data members in a structure must match the order of values in enclosed brackets.

We can initialize only some of the data members of the structure. The uninitialized data members can be initialized by default with zero (0) for int and float, ‘\0’ for character and strings.

5.5 STRUCTURE WITHIN A STRUCTURE

If a structure contains more than one structure as its members, it is known as a nested structure ie) structure within a structure.

It is used to increase the readability of the program by reducing the complexity.

struct address

{

char addr1[20];

char addr2[20];

char town[30];

char state[20];

long int pincode;

Page 276: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

276

};

struct employee

{

int code;

char name[20];

struct address addr;

}struct employee emp1;

Since the structure address is inside structure employee, the members of the address structure need to be

accessed as a separate structure variables such as, emp1.addr.addr1, emp1.addr.addr2, emp1.addr.town,

emp1.addr.state, emp1.addr.state, and emp1.addr.pincode.

The syntax for accessing the nested structure members can be given as follows: outer_structure_variable.inner_structure_variable.inner_structure_member

The structure cannot be used as a member within the same structure. struct employee

{

int code;

char name[20];

int age;

struct employee emp1;

}; is not valid.

5.6 UNION

Page 277: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

277

Union is a variable, which is similar to the structure.

It contains a number of members like structure but it holds only one object at a time in a single area of storage.

In the structure, each member has its own memory location, whereas members of unions have same memory locations.

Union is declared using the keyword union.

Union can be declared as follows: union union_name

{

Data type variable1;

Data type variable2;

.

.

.

Data type variablen;

};

union union_variable;

Example: Declaring an union

union result

{

int marks;

float avg;

char grade;

}std;

The above example declares std of type union result. This contains three union members each of different data

type. The storage size needed for the union result is 4 bytes. Fig1. shows the storage size of union members.

Page 278: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

278

However, only one member can be used at a time, since one location is allocated for union variable without

considering its size.

Storage of 4 bytes

2000 2001 2002 2003

grade

marks

avg

Fig1: Storage size of union members

5.7 PROGRAMS USING STRUCTURES AND UNIONS

Program1: Program to print the student number, name, and marks by accessing structure elements

/* Program to print student number, name, and marks using structures*/

#include<stdio.h>

#include<conio.h>

struct student

{

int no;

char name[20];

int mark1;

int mark2;

Page 279: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

279

int mark3;

}s;

void main()

{

int total;

float avg;

clrscr();

printf("Enter student details:\n");

printf("Enter student number, name, mark1,mark2,mark3:");

scanf("%d %s %d %d %d",&s.no,s.name,&s.mark1,&s.mark2,&s.mark3);

total=s.mark1+s.mark2+s.mark3;

avg=total/3;

printf("\nThe total and average of %s,No:%d is %d and %0.2f", s.name,s.no,total,avg);

getch();

}

Output:

Enter student details:

Enter student number, name, mark1, mark2, mark3: 2 Anu 99 98 97

The total and average of Anu, No.2 is 294 and 98.00

Program2: Program to create user-defined data type from structure

Page 280: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

280

/* Program to create user-defined data type from structure*/

#include<stdio.h>

#include<conio.h>

typedef struct

{

int no;

char name[20];

int mark1;

int mark2;

int mark3;

}student;

student s;

void main()

{

int total;

float avg;

clrscr();

printf("Enter student details:\n");

printf("Enter student number, name, mark1,mark2,mark3:");

scanf("%d %s %d %d %d",&s.no,s.name,&s.mark1,&s.mark2,&s.mark3);

total=s.mark1+s.mark2+s.mark3;

avg=total/3;

printf("\nThe total and average of %s,No:%d is %d and %0.2f", s.name,s.no,total,avg);

Page 281: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

281

getch();

}

Output:

Enter student details:

Enter student number, name, mark1, mark2, mark3: 2 Anu 99 98 97

The total and average of Anu, No.2 is 294 and 98.00

Program3: Program to print the employee details using structure

/*Program to print employee pay slip- Assume da=65%and hra=10%*/

#include<stdio.h>

#include<conio.h>

struct employee

{

int empno;

char name[20];

long int basicpay;

long int da,hra;

double grosspay;

}emp[10];

void main()

{

Page 282: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

282

int i,n;

clrscr();

printf("Enter employee details:\n");

printf("Enter total number of employees:");

scanf("%d",&n);

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

{

printf("\nEnter employee%d number, name, and basic pay:",i+1);

scanf("%d %s %ld",&emp[i].empno,emp[i].name,&emp[i].basicpay);

emp[i].da=emp[i].basicpay*65/100;

emp[i].hra=emp[i].basicpay*10/100;

emp[i].grosspay=emp[i].basicpay+emp[i].da+emp[i].hra;

}

printf("\n\n\t\t*****Employees Pay Slip*****");

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

{

printf("\nEmpNumber \tEmpName \tBasic Pay \tDA \tHRA \tGross Pay");

printf("\n%d\t%s\t%ld\t\t%ld\t\t%ld\t\t%0.2lf",emp[i].empno,emp[i].name,

emp[i].basicpay,emp[i].da,emp[i].hra,emp[i].grosspay);

}

getch();

}

Page 283: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

283

Output:

Enter employee details:

Enter total number of employees: 2

Enter employee1 number, name, and basic pay: 101 Anu 10000

Enter employee2 number, name, and basic pay: 102 Banu 20000

*****Employees Pay Slip*****

EmpNumber EmpName Basic Pay DA HRA Gross Pay

101 Anu 10000 6500 1000 17500.00

102 Banu 20000 13000 2000 35000.00

Program4: Program to find size of union and number of bytes reserved for it

/*Program to find the size of union and structure*/

#include<stdio.h>

#include<conio.h>

void main()

{

union result

{

int mark1,mark2,mark3;

char grade;

Page 284: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

284

}perf;

struct res

{

char name[15];

int age;

char sex;

char address;

int pincode;

union result perf;

}data;

clrscr();

printf("Size of union: %d\n",sizeof(perf));

printf("Size of structure: %d\n",sizeof(data));

getch();

}

Output:

Size of union: 2

Size of structure: 23

Program5: Structure within structure

/*Program to demonstrate structure within structure*/

Page 285: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

285

#include<stdio.h>

#include<conio.h>

struct date /*Date structure – Inner structure*/

{

int day;

char month[10];

int year;

};

struct employee /*Employee structure – Outer structure*/

{

int empno;

char name[25];

float salary;

struct date doj;

};

struct employee emp1;

void main()

{

clrscr();

printf("Enter employee number:");

scanf("%d",&emp1.empno);

printf("\nEnter employee name:");

scanf("%s",emp1.name);

Page 286: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

286

printf("\nEnter employee salary:");

scanf("%f",&emp1.salary);

printf("\nEnter date of joining:");

scanf("%d %s %d",&emp1.doj.day,emp1.doj.month,&emp1.doj.year);

printf("\n\n*****Employee Details*****");

printf("\nThe employee number is %d",emp1.empno);

printf("\nThe employee name is %s",emp1.name);

printf("\nThe employee salary is %0.2f",emp1.salary);

printf("\nThe employee DOJ is %d %s %d",emp1.doj.day,emp1.doj.month,emp1.doj.year);

getch();

}

Output:

Enter employee number: 101

Enter employee name: Anu

Enter employee salary: 20000

Enter date of joining: 12 June 2013

*****Employee Details*****

The employee number is 101

The employee name is Anu

The employee salary is 20000

The employee DOJ is 12 June 2013

Page 287: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

287

5.8 STORAGE CLASSES

Every variable in a program has memory associated with it.

Memory requirement of variables is different for different types of variables.

In C, memory is allocated and released at different places.

C supports 4 types of storage classes and these are used to specify the scope of different variables defined within function blocks and programs. Fig2. shows the classification of storage classes.

Fig2. Classification of storage classes

5.8.1 auto:

Storage Classes

auto static extern register

Page 288: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

288

Variables without any storage class specification are considered as automatic variables.

‘auto’ keyword is used to explicitly declare the variable. All the variables declared are of type ‘auto’ by default.

These are called as automatic because their memory space is automatically allocated as the variable is declared.

These variables are given only temporary memory space and after the execution all the variables are disposed. Syntax: storage_class_type data_type var1, var2, ………,varn;

Example: auto int a, b;

Program6: Program to demonstrate auto storage class

/*Program to demonstrate auto storage class*/

#include<stdio.h>

#include<conio.h>

void main()

{

auto num=60;

clrscr();

{

auto num=20;

printf("\nThe number is %d",num);

}

printf("\nThe number is %d",num);

getch();

}

Page 289: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

289

Output:

The number is 20

The number is 60

In the above program, two variables are declared in different blocks, so they are treated as different variables.

5.8.2 static:

Static variables are variables for which the contents of the variables will be retained throughout the program.

These are permanent within the function in which they are declared.

These are capable of retaining their latest values, when the function is invoked again.

Syntax: storage_class_type data_type var1, var2, ………,varn;

Example: static int a, b;

5.8.3 extern:

Extern variables are declared out of the main() function.

The availability of these variables are throughout the program ie) both in main function and inside the user defined functions.

The external declaration of the variables makes the variables available even for the external functions that are called during program execution.

Syntax: storage_class_type data_type var1, var2, ………,varn;

Example: extern int a, b;

Page 290: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

290

Program7: Program to demonstrate extern storage class

/*Program to demonstrate extern storage class*/

#include<stdio.h>

#include<conio.h>

int num=75;

void display();

void main()

{

extern int num;

clrscr();

printf("\nThe number is %d",num);

display();

getch();

}

void display()

{

extern int num;

printf("\nThe number is %d",num);

}

Output:

The number is 75

Page 291: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

291

The number is 75

In the above program, declaration within the function indicates that the function uses external variable. Functions

belonging to same source code, does not require declaration ie) no need to write extern. If the variable is defined

outside the source code, then declaration using extern keyword is required.

5.8.4 register:

Registers are special storage areas within CPU

The actual arithmetic and logical operation that comprise a program are carried out within these registers

Syntax: storage_class_type data_type var1, var2, ………,varn;

Example: register int a, b;

Here, a and b will be stored within the registers of the computer CPU rather than in memory.

Program8: Program to demonstrate register storage class

/*Program to demonstrate register storage class*/

#include<stdio.h>

#include<conio.h>

void main()

{

int a,b;

register int c;

Page 292: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

292

clrscr();

printf("Enter the value of a and b:");

scanf("%d %d",&a,&b);

c=a+b;

printf("\nSum of two numbers is %d",c);

getch();

}

Output:

Enter the value of a and b: 2 3

Sum of two numbers is 5

In the above program, variables a and b are stored in RAM and c is stored in the register of the microprocessor.

5.8.5 Features of storage classes:

Storage class of variable determines the following:

Storage – where the variable is stored Scope of variable Default initial value Lifetime of variable

Table1. explains the features of storage classes.

5.8.5.1 Storage:

Page 293: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

293

Storage class determines the location of variable, and where it is declared

Variables declared with auto storage classes are declared inside main memory whereas variables declared with keyword register are stored inside the CPU register

5.8.5.2 Scope of variable:

Scope of variable tells the compiler about the visibility of variable in the block.

Variable may have block scope, local scope and external scope.

5.8.5.3 Default initial value:

Whenever we declare a variable in C, garbage value is assigned to the variable.

Garbage value may be considered as initial value of the variable.

The different storage classes has different initial values such as global variable have initial value 0 while the local auto variable have default initial garbage value.

5.8.5.4 Lifetime of variable:

Lifetime of the variable is the time from the time of declaration to the time of variable destruction.

Suppose we have declared variable inside the main function, then the variable will be destroyed only when the control comes out of the main ie) end of the program.

Table1. Features of storage classes

Features static auto extern register

Storage Memory Memory Memory CPU register

Scope Local scope Local/Block scope Global/File scope Local to the block

Page 294: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

294

Lifetime Value of the

variable exists

between different

function call

Exists as long as

control remains in the

block

Exists as long as

variable is running

Retains value

within the function

Exists as long as the

control remains

within the block in

which the variable

is defined

Default

value

Zero Garbage Zero Garbage

5.9 PREPROCESSOR DIRECTIVES

Preprocessor comes before compiler, so complete source code will be first processed by the preprocessor and then the output will be given to the compiler. This process is called preprocessing.

Preprocessor directives are placed before the main() function in the source program.

The compiler examines the preprocessor for any preprocessor directives.

If there are any preprocessor directives, the appropriate actions are taken and then the source program is moved for compilation.

Any preprocessor directive starts with #.

They do not end with semicolon.

Fig3. shows the flowchart explaining the processing of preprocessor directives:

Page 295: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

295

Fig3. Processing of preprocessor directives

Example:

C Program

Final source code after preprocessing

In the above example, all the header files are removed. New lines are replaced by spaces and all large spaces are

replaced by single space.

The major preprocessor directives are:

#include<stdio.h>

#include<conio.h>

#define MAX 10

void main()

{

int i=MAX;

printf(“The maximum value is: %d”,MAX);

getch();

}

void main()

{

int i=10;

printf(“The maximum value is: %d”,10);

getch();

}

Page 296: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

296

1. File Inclusion 2. Macro Substitution 3. Conditional Compilation

5.9.1 File Inclusion:

Any external file can be included in the source program which contains functions or some macro

definitions to our source program.

So, we need not rewrite those functions and macros in our source program.

Use the keyword #include followed by the file name.

Syntax: #include”file name”

and

#include<filename>

where ‘file name’ is the name of the file, that can be included in our source program

When ‘filename’ is quoted, it searches for that file in current directory and then in standard directories.

At this stage the entire contents of the files are included in the source program.

When the file is included in angle brackets, the included file is searched only in standard directories.

Example: #include “hello.c”

#include<stdio.h>

5.9.2 Macro Substitution:

Used to define symbolic constants in the source program.

Syntax: #define identifier string/integer

Example: #define PI 3.14

Page 297: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

297

Here, 3.14 is substituted wherever PI is used in the source program.

The preprocessor accomplish the task specified in the ‘#define’ statement.

This statement is also placed before the main() function.

The preprocessor replaces every occurrence of an identifier by the specified string or integer in the source program.

There are three different forms of macros: a) Simple macros b) Argumented macros c) Nested macros

5.9.2.1 Simple macros:

Used to define symbolic constants.

Examples: #define age 20

#define CITY “CHENNAI”

#define A 10

The expression can also be defined in macros.

Examples: #define A 10-5

#define B 20-10

Consider an arithmetic operation: C = (A) + (B) C = (10-5) + (20-10)

The literal text can also be substituted using macros.

Examples: #define exp if(10>5)

Page 298: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

298

#define True printf(“Greater”);

#define False else printf(“Lesser”);

To build the above macro as a statement like

exp True False if(10>5) printf(“Greater”);

else printf(“Lesser”);

Program9: Program to find the area of circle by defining simple macro

/* Program to find the area of circle*/

#define PI 3.14

#include <stdio.h>

void main()

{

int r,a;

clrscr();

printf("\nEnter the radius of a circle:");

scanf("%d",&r);

a=PI*r*r;

printf("\nThe area of a circle is %d",a);

getch();

Page 299: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

299

}

Output:

Enter the radius of a circle: 3

The area of a circle is 28

5.9.2.2 Argumented macros:

Used to define more complex and useful form of replacements in the source program.

Everytime whenever the macro name is encountered, the arguments are replaced by the actual arguments from the program

Macroname having arguments is called argumented macro.

Argumented macro is also called function macro because it looks like calling function.

Arguments are not case sensitive.

Syntax: #define identifier(v1 v2 v3 …vn) string/integer

Program10: Program to print square and cube values using macro substitution

/* Program to print square and cube values using macro substitution*/

#define sq(n) (n*n)

#define cube(n) (n*n*n)

#include<stdio.h>

void main()

Page 300: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

300

{

int a=5,square,cube;

clrscr();

square=sq(a);

cube=cube(a);

printf("Square value of 5 is %d\n",square);

printf("Cube value of 5 is %d",cube);

getch();

}

Output:

Square value of 5 is 25

Cube value of 5 is 125

5.9.2.3 Nested macros:

The macro defined within another macro is called nested macros.

Example: #define A 5

#define B A+2

5.9.3 Conditional Compilation:

Used to control the preprocessor with conditional statements.

Page 301: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

301

Set of commands are included or excluded in source program before compilation with respect to the condition.

Conditional compilation directives are #if, #ifdef, #else, #endif, #ifndef, #undef, and #pragma

#ifdef directive checks whether particular macro is defined or not. If it is defined, If clause statements are included in source file. Otherwise, else clause statements are included in source file for compilation and execution.

#ifndef exactly acts as reverse as #ifdef directive. If particular macro is not defined, If clause statements are included in source file. Otherwise, else clause statements are included in source file for compilation and execution.

#if clause statement is included in source file if given condition is true. Otherwise, else clause statement is included in source file for compilation and execution.

#undef directive undefines existing macro in the program.

Pragma is used to call a function before and after main function in a C program.

Program11: Program to illustrate conditional compilation

/* Program to illustrate #ifdef */

#include <stdio.h>

#include<conio.h>

#define MAX 100

void main()

{

#ifdef MAX

printf("MAX is defined. So, this line will be added in this C file\n");

#else

printf("MAX is not defined\n");

#endif

getch();

}

Output:

MAX is defined. So, this line will be added in this C file

Page 302: LECTURE NOTES UNIT - I - Home | Panimalar Institute of ... ALL UNITS.pdfArtificial Intelligence – Computers cannot think, it just works as per human instructions. Computer Generations

Panimalar Institute of Technology FOC Semester 1

302

5.9.4 Rules for defining preprocessor:

Every preprocessor must start with # symbol.

The preprocessor is always placed before main() function.

The preprocessor cannot have termination with semicolon.

There is no assignment operator in #define statement.

The conditional macro must be terminated.