Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
196 views111 pages

Vtu 18CPSC13/23

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 111

HKBK COLLEGE OF ENGINEERING

(Affiliated to VTU, Belgaum and Approved by AICTE)

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

18CPS13/23 C Programming for Problem Solving


[As per Choice Based Credit System (CBCS) scheme]

Academic Year 2020-21

Prepared by
Dr. Loganathan R
Prof & HOD
Department of Computer Science and Engineering

HKBK COLLEGE OF ENGINEERING


22/1, Nagawara, Bangaluru -560045
www.hkbk.edu.in, info@hkbk.edu.in
HKBK COLLEGE OF ENGINEERING
Department of Computer Science and Engineering

Institute Vision and Mission

Vision

To empower students through wholesome education and enable the students to develop into highly
qualified and trained professionals with ethics and emerge as responsible citizen with broad outlook to
build a vibrant nation.

Mission
 To achieve academic excellence through in-depth knowledge in science, engineering and technology
through dedication to duty, innovation in teaching and faith in human values.
 To enable our students to develop into outstanding professionals with high ethical standards to face
the challenges of the 21st century
 To provide educational opportunities to the deprived and weaker section of the society, to uplift their
socio-economic status.

Department Vision

 To advance the intellectual capacity of the nation and the international community by imparting
knowledge to graduates who are globally recognized as innovators, entrepreneur and competent
professionals.
Mission

 To provide excellent technical knowledge and computing skills to make the graduates globally
competitive with professional ethics.
 To involve in research activities and be committed to lifelong learning to make positive contributions
to the society.

CSE @ HKBKCE 2 2019-20


18CPS13 C Programming for Problem Solving

Program Educational Objectives (PEOs)


PEO-1 To provide students with a strong foundation in engineering fundamentals and in the
computer science and engineering to work in the global scenario.

PEO-2 To provide sound knowledge of programming and computing techniques and good
communication and interpersonal skills so that they will be capable of analysing,
designing and building innovative software systems.

PEO-3 To equip students in the chosen field of engineering and related fields to enable him
to work in multidisciplinary teams.

PEO-4 To inculcate in students professional, personal and ethical attitude to relate


engineering issues to broader social context and become responsible citizen.

PEO-5 To provide students with an environment for life-long learning which allow them to
successfully adapt to the evolving technologies throughout their professional career and face
the global challenges.

Programme Outcomes

a. Engineering Knowledge: Apply knowledge of mathematics, science, engineering


fundamentals and an engineering specialization to the solution of complex engineering
problems.

b. Problem Analysis: Identify, formulate, research literature and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural
sciences and engineering sciences

c. Design/ Development of Solutions: Design solutions for complex engineering problems and
design system components or processes that meet specified needs with appropriate
consideration for public health and safety, cultural, societal and environmental
considerations.

d. Conduct investigations of complex problems using research-based knowledge and research


methods including design of experiments, analysis and interpretation of data and synthesis of
information to provide valid conclusions.

e. Modern Tool Usage: Create, select and apply appropriate techniques, resources and modern
engineering and IT tools including prediction and modeling to complex engineering activities with
an under- standing of the limitations.

f. The Engineer and Society: Apply reasoning informed by contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant
to professional engineering practice.

g. Environment and Sustainability: Understand the impact of professional engineering solutions


in societal and environmental contexts and demonstrate knowledge of and need for
sustainable development.

CSE@HKBKCE 3
18CPS13 C Programming for Problem Solving

h. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of engineering practice.

i. Individual and Team Work: Function effectively as an individual, and as a member or leader
in diverse teams and in multi-disciplinary settings.

j. Communication: Communicate effectively on complex engineering activities with the


engineering community and with society at large, such as being able to comprehend and write
effective reports and design documentation, make effective presentations and give and receive
clear instructions.

k. Life-long Learning: Recognize the need for and have the preparation and ability to engage in
independent and life- long learning in the broadest context of technological change.

l. Project Management and Finance: Demonstrate knowledge and understanding of


engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.

Programme Specific Outcomes

m. Problem-Solving Skills: An ability to investigate and solve a problem by analysis,


interpretation of data, design and implementation through appropriate techniques, tools and
skills.
n. Professional Skills: An ability to apply algorithmic principles, computing skills and computer
science theory in the modeling and design of computer-based systems.
o. Entrepreneurial Ability: An ability to apply design, development principles and management
skills in the construction of software product of varying complexity to become an
entrepreneur

CSE@HKBKCE 4
18CPS13 C Programming for Problem Solving

C PROGRAMMING FOR PROBLEM SOLVING

Semester: I/II CIE Marks: 40


Course Code: 18CPS13/23 SEE Marks: 60
Teaching Hours/week (L: T: P): 2:2:0 Exam Hours: 03
Credits: 03

Course Learning Objectives:

This course will enable students to:

CLO1. To understand the computer fundamentals


CLO2. Familiarize with writing of algorithms, fundamentals of C and philosophy of problem solving.
CLO3. Implement different programming constructs and decomposition of problems into functions.
CLO4. Use and implement data structures like arrays and structures to obtain solutions.
CLO5. Define and use of pointers with simple applications.

MODULE-I

Introduction to computer Hardware and software: Computer generations, computer types, bits, bytes and words, CPU,
Primary memory, Secondary memory, ports and connections, input devices, output devices, Computers in a network,
Network hardware, Software basics, software types. Overview of C: Basic structure of C program, executing a C
program. Constant, variable and data types, Operators and expressions, (RBT Levels: L1 & L2)

MODULE 2

Managing Input and output operations. Conditional Branching and Loops. Example programs, finding roots of a
quadratic equation, computation of binomial coefficients, plotting of Pascal’s triangle. (RBT Levels: L1 & L2)

MODULE 3

Arrays (1-D, 2-D), Character arrays and Strings, Basic Algorithms: Searching and Sorting Algorithms (Linear search,
Binary search, Bubble sort and Selection sort). (RBT Levels: L1, L2 & L3)

MODULE 4

User Defined Functions and Recursion. Example programs, Finding Factorial of a positive integers and Fibonacci
series. (RBT Levels: L1, L2 & L3)

MODULE 5

Structure and Pointers, Preprocessor Directives (RBT Levels: L1, L2 & L3)

Course Outcomes:
The student will be able to:
CO1. To identify the computer hardware, software and Network Topologies
CO2. Illustrate simple algorithms from the different domains such as mathematics, physics, etc.
CO3. Construct a programming solution to the given problem using C.
CO4. Identify and correct the syntax and logical errors in C programs.
CO5. Modularize the given problem using functions and structures.

CSE@HKBKCE 5
18CPS13 C Programming for Problem Solving

Text Books:
1. E. Balaguruswamy, Programming in ANSI C, 7thEdition, Tata McGraw-Hill
2. Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, Prentice Hall of India.

Reference Books:
1. Sumitabha Das, Computer Fundamentals & C Programming, Mc Graw Hill Education.
2. Gary J Bronson, ANSI C Programming, 4th Edition, Ceneage Learning.
3. Vikas Gupta: Computer Concepts and C Programming, Dreamtech Press 2013.
4. R S Bichkar, Programming with C, University Press, 2012.
5. V Rajaraman: Computer Programming in C, PHI, 2013.
6. Basavaraj S. Anami, Shanmukhappa A Angadi, Sunilkumar S. Manvi, Computer Concepts and C
Programming: A Holistic Approach to Learning C, Second edition, PHI India, 2010.

CO to PO and PSO Mapping

PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PSO3
CO1 X X
CO2 X X
CO3 X X
CO4 X X
CO5 X X

CSE@HKBKCE 6
Module 1
1. Introduction to Computer Hardware and Software
Computer Basics
Computer is a device that can automatically perform a set of instructions. The computer takes as input these
instructions as a single unit, uses them to manipulate data and outputs the results in user-specified ways. The processing
is fast and consistent, and is achieved without human intervention.
A computers power is in Central Processing Unit (CPU) which process these instructions. An instruction can do simple
work, like moving a constant to a register or adding one to it. Instructions need data to operate on, and this data can be
made available from multiple sources—keyboard input, for instance.
Data may also occur in the program itself The output could be written to any device—a disk, monitor or printer. A
program containing instructions is held in a file that is stored on the computer's hard disk. To execute, the contents of its
file is loaded into main memory. The data also get loaded, either with the program or when demanded by it. The CPU
executes a single instruction at a time .The instructions are executed in a linear sequence unless an instruction itself
specifies a different execution sequence.
Computers understand only sequences of 0s and 1s, called machine language. All instructions and data must be input
to the CPU in machine language. Because humans are not comfortable using this language, need to use a programming
language like C. The CPU doesn't understand programming languages, so program is translated to its corresponding
machine language code before execution. The program is first saved in a file on the disk, a separate program, compiler
translates or compiles to its equivalent machine code in binary.

Program Transformation before Execution


The Background
Abacus
2000 B.C in Babylonia, the computer made its beginning as a simple calculator, called the abacus, comprised a
number of rings or beads that could be moved along rods enclosed by a wooden frame. This calculator could be used only
for addition and subtraction
Napier, Pascal and Leibniz: The Early Pioneers
In 17th century Napier established that the multiplication and division can be achieved by adding and subtracting the
logarithm of the numbers. Napier’s invention led to the development of the slide rule (analog device), used by engineers
and scientists up to 1960s. Blaise Pascal created gear-based digital mechanical calculator in 17th century, it could perform
only addition and subtraction. Gottfried Leibniz improved Pascal's creation by adding the features of multiplication and
division called the stepped reckoner. Both devices were based on the decimal system, but Leibniz recommended the use
of the binary system, which was to be adopted centuries later.
The Programmable Computer
The concept of using a program to control a sequence of operations was first seen in the Jacquard loom in the
early 19th century. This textile loom used a set of punched cards to weave complex patterns in the cloth. To weave a
different design, one simply had to change the card set. This idea appealed to Charles Babbage who used the concept in
his two conceptual creations—the Difference engine and Analytical engine. However, while the holes in the cards of the
Jacquard loom determined whether a thread would pass through it, Babbage saw an opportunity to use them to encode
instructions and data
CSE @ HKBKCE 7 2019-20
18CPS13 C Programming for Problem Solving

The Programmable Electronic Computer


Because of the difficulty of programming and speed with electronic computers, 1936 Alan Turing reasoned that
computer speed improves if both program and data stored in the same memory, later John von Neumann, introduced
the concept of stored-program computer. 1940s vacuum tube (also called valves) used for performing Computation,
1950s introduction of transistors which were smaller than Transistors too made way for integrated circuits (ICs)
microprocessor on a single chip.

Computer Generations
Vacuum Tubes: The First Generation
Vacuum tubes were used – basic arithmetic operations took few milliseconds, Bulky , Consume more power with
limited performance and high cost. Uses machine level language, Fixed point arithmetic was used. Mercury delay line
memories and Electrostatic memories as primary and magnetic drums as secondary memory
Transistors: The Second Generation
Transistors were used in place of vacuum tubes, Small in size, Less power consumption and better performance , Low
cost. Magnetic ferrite core memories were used as main memory, Magnetic tapes and magnetic disks were used as
secondary memory. Floating point arithmetic operations, High level languages (FORTRAN, COBOL ), Compilers to translate
to machine language.
Integrated Circuits: The Third Generation
ICs were used , Small and Medium Scale Integration use in CPU, Smaller & better performance , Comparatively lesser
cost, Faster processors. Semiconductor memories (RAM & ROM) , pipelining, Operating system, Time-sharing OS Cache
and virtual memories High level languages were standardized by ANSI, introduction of C, C++, Java
The Microprocessor: The Fourth Generation
Microprocessors as CPU, 8086, VLSI design, CRT screen, laser printers, Semiconductor memory, hard disks, Floppy
disks & magnetic tape memory. Less power consumption, High performance, lower cost and very compact. Laptops and
Smartphones, GUI Based OS, TCP/IP technology, LAN, WAN and Internet were developed
Artificial Intelligence: The Fifth Generation:
Artificial intelligence and use of natural languages are the main features, may be capable of producing human-like
behavior. ULSI and nano technology, quantum computers. Extensive parallel processing, multiple pipelines, multiple
processors. Extensively distributed system connected by communication networks. Molecular computing could take
miniaturization to molecular levels.
Computer Generations (Hardware)
Generation Based on Other Features
First Vacuum tubes Magnetic drums for memory
Second Transistors Magnetic cores, disks, punched cards and printouts.
Third Integrated circuits (ICs) Keyboard, monitor and operating system
Fourth Microprocessors Networking
Fifth ULSI and nano technology Mainly unclear

Computer Types
Supercomputers
Huge machines , most powerful and fastest processors, multiple CPUs for parallel data processing. Speeds are
measured in flops (floating point operations per second), fastest supercomputer speed 34 peta flops. Used for transaction
processing, weather forecasting, analysis of geological data, nuclear simulation, space exploration, complex scientific
problems.
Mainframes
Before supercomputers, mainframe computers were the largest computers. Multi user, time sharing Linux, terminal
and keyboard to interact. Multiple programs in a single CPU, speed in mips (million instructions per second). Used to
handle data and applications related to the organization as a whole, online transactions, capability to handle large
amounts of data.

CSE@HKBKCE 8
18CPS13 C Programming for Problem Solving

Minicomputers
Downsized mainframes, serves hundreds of users and small to partially occupy a room. Digital Equipment Corporation
(DEC) introduced in the 1970s, had multiple CPUs. Smaller organizations or a department of a large one, captive machines
of turnkey equipment running specialized software.
Microcomputers
Personal Computer (PC), Apple and IBM, a single-user single-chip microprocessor. Gigabytes of memory and a
terabyte disk storage, standalone mode (at home) and in a network (in office). Desktop, notebook (laptop) or a netbook
(smaller laptop), single CPU with multiple cores. Windows (7, 8 or 10), Mac OS X (Apple) and Linux., word processing,
spreadsheet handling and desktop publishing, Internet browsing, multimedia ready. A variant of Microcomputers is
workstation has powerful processor, a high resolution terminal and high quality graphic capabilities, used for engineering
and scientific applications (CAD/CAM) and software development.
Smartphones and Embedded Computers
The smartphone has a powerful processor with multiple cores gigabytes of main memory, flash memory, operating
system (Android or iOS), and wide range of applications. Keyboard, high-resolution display, operated by touch or a stylus.
Applications are developed using Objective-C for iPhone and Java for Android phones. Embedded computers or micro-
controllers, small circuits containing a CPU, non-volatile memory, and input and output handling facility. Embedded into
machines like cars, washing machines, music players and cameras. It runs a single unmodifiable program

Bits, Bytes and Words


A digit that can have only two states or values is known as a binary digit or bit. All binary numbers are represented by
combining these 0s and Is. The number 13 in decimal is represented as 1101 in the binary system. The name byte was
coined to represent eight bits. The byte is the standard unit of measurement of computer memory, data storage and
transmission speed. A DVD-ROM has a capacity 4.7 gigabytes (4X 10 bytes), and internet speeds of 4 megabits per sec (4X
106).
Unit Equivalent to Remarks
1 kilobyte (KB) 1024 bytes Space used by 10 lines of text
1 megabyte (MB). 1024 kilobytes Memory of the earliest PCs
1 gigabyte (GB) 1024 megabytes Storage capacity of a CD-ROM
1 terabyte (TB) 1024 gigabytes Capacity of today's hard disks.
1 petabyte (PB) 1024 terabytes Space used for rendering of film Avatar.
C handles memory data in words, where a word is usually an even multiple of byte (2 bytes, 4bytes etc.). Most machine
instructions are one word in size, and because a CPU register must be able to hold an instruction.

Inside the Computer


The brain of the computer is the Central Processing Unit (CPU) a single chip on a PC. The CPU carries out every
instruction stored in a program, while interacting with other agencies as and when necessary. Most of the work is done
by the Arithmetic and Logic Unit (ALU), which is an integral part of the CPU.
The CPU needs both fast and slow memory to work with. Fast memory is represented by primary memory, known as
Random Access Memory (RAM). It is divided into a number of contiguously numbered cells. The numbers represent the
addresses of the cells. The CPU accesses a memory location by sending its address to the memory unit. Primary memory
is used for storing instruction and data of the program currently in execution.
The computer supports slower secondary memory or secondary storage or auxiliary memory. This is the hard disk but
it can also be a CD-ROM or DVD-ROM. Secondary memory is used for storing data not required currently. Data in
secondary memory are stored as files having unique names. A program is executed by loading instructions and data from
secondary memory to primary memory.
Users interact with a computer system using input and output devices. Data keyed in through the keyboard are
converted to binary form by the device before they are saved in RAM. After processing, the output data have to undergo
reverse conversion (binary to a human-readable form) before they can be displayed on the monitor or printer
There are three types of data that move between the various components of the computer. The data of a specific type
move along a distinct pathway, called a bus, which is reserved for that type. Program instructions and data move along
the data bus. Memory addresses travel along the address bus. All control signals use the control bus.

CSE@HKBKCE 9
18CPS13 C Programming for Problem Solving

Architecture of a Computer with a Single Processor

The Central Processing Unit (CPU)


The CPU is 5cm square chip that is commonly called the microprocessor or processor. It has the following components:
• Arithmetic and Logic Unit (ALU): a "super calculator” carrying out all arithmetic tasks, it compares two numbers
and performs Boolean operations on them.
• Control Unit (CU): Using signals, the CU controls the way data is moved between the various components of the
computer. Both ALU and CU use the services of a clock for sequencing and synchronizing their operations
• Special Purpose Registers: The CPU uses high-speed registers to store the current instruction and its data. A
register called the program counter, stores the address of the next instruction to be executed. This is incremented
after an instruction is fetched. Instructions are executed using the fetch-decode-execute mechanism. An
instruction is first fetched from primary memory using the address stored in the program counter and it is
immediately incremented to the address of the next instruction. The fetched instruction is decoded to create the
signals needed for the operation. The converted instruction is then executed by the CPU. The output, if any, is
then written to another register. The next cycle can now begin.
• A clock: All of these activities need synchronization by the clock which generates pulses at regular interval
Primary Memory
Primary memory which includes the following types:
1. Random Access Memory (RAM-SRAM and DRAM)
2. Read Only Memory (ROM, PROM, EPROM, EEPROM)
3. Cache Memory (LI, L2 and L3)
4. CPU Registers
Random Access Memory (RAM)
Stores the code and data of the currently running program. On multi-user systems, RAM contains several programs
that run in time-sharing mode. It is currently implemented as a set of densely packed transistorized cells fabricated into
integrate, circuits (ICs). RAM is fast, volatile and more expensive than secondary memory, the access is random hence the
term "random access“. It is divided into 2 types—static and dynamic RAM
• Static RAM (SRAM) uses multiple transistors for each cell to store one bit of information, therefore, takes more
space.
• Dynamic RAM (DRAM) uses one transistor and a leaky capacitor for each cell. Capacitors hold the charge, but
because of inherent leakage, DRAM cells have to be refreshed every two or three milliseconds.
Read Only Memory (ROM)
Permanent memory that can be read but not written that is, contents of a ROM are written at the time of
manufacturing, later enhancements have enabled ROMs to have limited write capabilities. Memory access is faster also
non-volatile, i.e. their contents are retained after power off.

CSE@HKBKCE 10
18CPS13 C Programming for Problem Solving

ROMs are used to store permanent programs or information, for example special program called the BIOS (Basic
Input Output System).Following types of ROM are non-volatile & have the capacity to be written at least once:
• Programmable Read Only Memory (PROM), left blank at the time of manufacture, then subsequently
programmed to contain a program of the customer's choice.
• Erasable Programmable Read Only Memory (EPROM), it can be rewritten once, erased by exposing it to ultra-
violet radiation.
• Electrically Erasable Read Only Memory (EEPROM), erased and rewritten multiple times. A higher than normal
electric voltage is used to erase. The pen drive or SD card is a type of EEPROM.
Cache Memory
Cache is SRAM, holds the portions of a program that are frequently used by the CPU. This fast but small memory as a
buffer between the CPU and RAM. When executing a program, the CPU first looks for the instruction and data in the
cache, if it find in cache (cache hit), access of the slower RAM is avoided.
If the data is not found in the cache (cache miss) system places it in cache. The CPU itself contains level 1 (L1) cache,
which is the smallest and fastest cache, Level 2 (L2) cache located outside the CPU but close to it, Level 3 (L3) cache is
slower than L1 and L2 but faster than RAM. Cache memory is expensive, so they are limited in size.
Registers
The small number of ultra-fast registers in CPU represent the fastest memory. Registers are the workplace where the
CPU does all of its work, has the length of the computer's word size. The computer loads an instruction and its data to
registers before processing them.

Secondary Memory
It exist in both in the machine or external is a non-volatile and long-term storage. These devices are slower than
primary memory but they have larger capacities.Types:
• Hard disk including the portable disk (500 GB to 4 TB)
• Magnetic tape (20 TB)
• CD-ROM (700 MB-Iess than 1 GB)
• DVD-ROM (4.7 GB and 8.5 GB)
• Blu-ray disk (27 GB and 50 GB)
• Flash memory based on the EEPROM (1 GB to 128 GB)
• The obsoleted floppy disk (1.2 MB and 1.44 MB)
The Hard Disk

CSE@HKBKCE 11
18CPS13 C Programming for Problem Solving

Also known as hard drive or fixed disk because it is fixed inside the computer, have very high capacities with the
cheapest cost. It is common for a laptop to have 500 GB of storage and Desktops 1 TB, houses the computer's operating
system along with all programs and data. Every disk contains a spindle that holds one or more platters made of non-
magnetic material.
A platter has 2 surfaces coated with magnetic material and Information is encoded onto these platters by changing
the direction of magnetization using a pair of read-write heads available for each platter surface. Each surface has a
number of concentric and serially numbered tracks, there are as many tracks bearing the same track number as there are
surfaces so.
There will be many cylinders in the disk as there are tracks, each track is broken into sectors or blocks, a block typically
comprises 512 bytes. The disk spins constantly at speeds between 5400 and 7200 rpm, heads move radially from track to
track, and when the head is positioned above a particular track, all of its blocks pass through the head in a very short time.
Example: Heads = 255, Cylinders = 121601, Sectors per track = 63, Bytes per sector = 512, the capacity of this hard
disk is 255 x 121601 x 63 x 512 = 1,000,202,273,280 Bytes or 1TB or 1024GB.
Magnetic Tape
The magnetic tape is made of a plastic film with one side coated with magnetic material. The entire mechanism
comprising two spools and the tape is encapsulated in a small cassette or cartridge. Supports capacities of 1 TB or more.
It is not fully portable because a separate tape drive is requirement.
Data are read from and written to the tape using a read-write head and an erasure head. The write operation is
preceded by the erasing operation. Data access is sequential, to locate a file, the tape has to be rewound before a
sequential search can begin which makes it unsuitable for restoring individual files. Tape backup of archiving data in hard
disk is inexpensive and convenient for restoring lost data.
Optical Disks: The CD-ROM, DVD-ROM and Blu-Ray Disk
CD-ROM and DVD ROM is Nonvolatile memory (ROM Family) can hold large volumes (700MB to 8.5 GB, Blu-ray 50
GB) on inexpensive media, used mostly for backup. A laser beam in their drives controls the read and write operations.
Optical disks are made of carbonate material with a thin layer or two of reflective film. A laser beam is used to construct
pits and lands by burning (writing) selected areas along its tracks and while reading, the beam is reflected from a land (1)
but not from a pit (0). Types(R-Read & RW-ReWritable)
• CD-R, DVD-R—Data can be recorded only once.
• CD-RW, DVD-RW-Data can be recorded multiple times.
Flash Memory
Having no moving parts, is based on EEPROM, available in various forms- Pen drive, Solid State Disk (SSD) and the
Magnetic Card (SD card) are portable , need little power and reliable.
The memory stick or pen drive is the most common type of flash memory, connects to the USB port of the computer
where it is detected as another drive by the operating system.
SSD is a bigger device meant to replace the traditional hard disk, small laptops have the operating system and a set
of programs stored.
SD card is used in cameras, using adapters it can be connected to the USB port. The most popular one is the micro-
SD card, which is available in SDHC and SDXC flavors. The SD card offer high capacities that can go up to 128 GB.
Floppy Diskette
The floppy diskette was once the only form of portable storage. A rectangular plastic case containing a thin magnetic
disk, a read/write head makes contact with disk while it is rotating. The floppy was available in two sizes (5.25" and 3.5"),
offering capacities of 1.2 MB and 1.44 MB respectively.

Ports and Connectors


Devices like Pen drive, printers and scanners connect to a computer through docking points called ports. All ports are
connected to the motherboard but are visible from the outside. They are shaped differently, so it is impossible to use a
wrong connector for a port. Types of Ports:
• Universal Serial Bus (USB): at least four USB ports in a computer to support scanners, printers and mice. A USB
port has four lines, two each for data and power. The current version, USB 3.0, can transfer a 1GB file in 20
seconds. The micro-USB port, is used on portable hard disks and smartphones.
• Serial port: used by the keyboard, terminals, mice and modems, serial ports are offered in 9 and 25-pin
configurations. Data pass through a serial port one bit at a time.
• Parallel port: Printer uses the parallel port which has 25 pins, with parallel data transfer.

CSE@HKBKCE 12
18CPS13 C Programming for Problem Solving

• Video Graphics Array (VGA) port: 15-pin port allows transfer of analog video data to the monitor which is being
replaced with the digital video interface (DVI) which uses digital data that is used by flat LeD panels.
• RJ45 port: used by the Ethernet network to connect both computer and the network
• PS/2 port: Replaced the serial port for connecting the keyboard and mouse, 6 pins but occurs as a pair in two
different colors. The port and connectors for keyboard are purple, and mouse is green.
• High Definition Multimedia Interface (HDMI): industry standard for transferring audio and video data between
computers and HDTVs, projectors and home theaters. A single cable handles both audio and video.

Ports and Connectors


Input Devices
To interact with programs for providing input, OS for editing, copying and deleting files, etc. through input device.
The Keyboard
Every computer supports a keyboard-either a physical one or a touchscreen has QWERTY layout and numerals with
other symbols and function keys (F1-F12). Each letter, numeral or symbol is known as a character, have unique values
assigned called the ASCII value. Example: [Enter] key terminates a line, [Ctrl-c] sequence (two keys) copies selected input,
[Ctrl-c] pastes.
Pointing Devices
Used to control the movement of the cursor on the screen usually mouse in desktop and touch pad in Laptop. Clicking
left button on object selects that object and Double-clicking activates a program. A text selected by dragging the mouse
with the left button pressed. Clicking right button activates a context-sensitive menu that can be used to change the
attributes of the selected object, copying and pasting text and change the properties of the selected object.
The scroll wheel scrolls a document in two ways. The optical mouse uses an infrared laser or LED to track movement
works on any surface. The wireless mouse uses radio frequency technology to communicate with the computer. The
transmitter in the mouse communicates with a USB-connected receiver.
The Scanner
A scanner is a device that creates a digital image of a document by optically scanning it. Flatbed scanner used for
scanning documents not exceeding A4 size, which connects to the USB port and is operated using a software. A shining
light is beamed at the document and the reflected light is captured by a photosensitive array of charged coupled devices
(CCD).
The differing levels of brightness are converted into electronic signals which are then processed to create the digital
image which is saved as a file. Pictures are converted to JPEG files and documents to PDF files. Modern scanners have the
Optical Character Recognition (OCR) by which a document can be scanned in a special mode to extract the text as a stream
of characters through the special software.

Output Devices
The Monitor
Programs use it to display text or graphical output and users need to view the input that they key in.
• CRT Monitor: Cathode Ray Tube (CRT) monitor uses a rarefied tube containing electron guns for the three primary
colors and a screen coated with phosphorescent material. The guns emit electrons to create images on the screen
by selectively lighting up the phosphors. CRT monitors typically have a resolution of 640 X 480 pixels. It is large
and heavy, energy-inefficient and generate a lot of heat.

CSE@HKBKCE 13
18CPS13 C Programming for Problem Solving

• LCD/LED Monitors: An LCD screen has thousands of liquid crystals, which, by themselves, don't generate light but
allow or block the passage of light through them. An image is formed by selectively applying a voltage to these
crystals and using a separate light source for light to pass through them. The backlight is provided either by
fluorescent light (the standard LCD) or by LEDs (hence the term LED monitors
Impact Printers
Printers produce hard copies of output which include text and graphics. Impact technology uses a print head to strike
(impact) a ribbon placed between the print head and paper.
• Dot-matrix Printer: The print head of the dot-matrix printer has either 9 or 24 pins which are fired in multiple
combinations to generate letters, numerals and symbols. The ribbon is soaked with ink, and when the pins fire
against the ribbon, an impression is created on the paper. The speed of a dot-matrix printer up to 300 cps
(characters per second), with 24 pins print quality is 144 dpi.
• Daisy-wheel Printer: Uses a wheel with separate characters distributed along its outer edge to strike the ribbon.
The characters are pre-formed and not generated, the wheel is rotated so that the desired character directly faces
the ribbon. Graphics not supported.
• Line Printer: Used for heavy printing, uses a print chain containing the characters. The chain rotates continuously
in front of the paper, hammers strike the paper, print speed attained are 1200 lpm (lines per minute). Line printers
are used to print low-quality voluminous data.
Non-Impact Printers
Noiseless, fast and produce documents of very high resolution.
• Laser Printer: It works like a photocopier, a laser beam creates an image of the page to be printed on a light-
sensitive drum. The charged areas attract black magnetic powder, called the toner. The image created is then
transferred from the drum to the paper by actual contact. A separate roller heats up the paper to melt the toner
which then gets fused onto the paper. Color laser printers use colored toner.
• Ink-jet Printer: It is an affordable non-impact printer whose print quality better than dot-matrix printer. A print
head sprays tiny drops of ink at high pressure as it moves along the paper. The ink, stored in a replaceable
cartridge, passes through a matrix comprising a number of tiny nozzles. Characters are formed by choosing the
nozzles that have to be activated. Color ink-jet printers either have separate cartridges for each color or use a
multi-chambered cartridge.
Plotters
Used to make line drawings, uses one or more automated pens to complete each line before taking up the next one.,
either the plotter pen moves or the paper moves or both to draw the lines The commands are taken from special files
called vector graphic files and handles large paper sizes, and suitable for creating drawings of buildings and machines.
They are slow and expensive.

Computers in a Network
Computers cooperate with one another by being connected to a network and an authorized user can share their files
with other users. An application run by multiple users can now hosted in a single machine and many network applications
today are designed, enable sharing of the workload by multiple machines in a network.
Network Topology
There are a number of ways or topologies of connecting computers.
• The bus topology uses a single cable as a bus to which all computers are connected. The failure of a single node
doesn't disrupt the communication between the remaining nodes.
• The star topology uses a central hub where all nodes are connected. Since network traffic go through the hub,
the entire network fails if the hub fails, but, new nodes are added without disrupting the service.
• Ring topology are connected in a closed loop and data moves from one node to the next one which examines
each packet to determine whether it should be allowed to move further to the next node. For uni-directional
rings, failure of one node causes the network to shut down.
• Mesh topology connects one to one another, offering a choice of multiple routes for data to travel. When a node
breaks down, the packet simply changes its route. This is the most expensive and is found mainly in corporate
networks.

CSE@HKBKCE 14
18CPS13 C Programming for Problem Solving

Network Types
Networks are also classified based on their size.
• Local Area Network (LAN) are used by small organizations where the area of operation is confined to one building
using Ethernet technology.
• Wireless LAN (WLAN), also known as Wi-Fi, has become a contender to the wired LAN. Standard Ethernet speeds
is 100Mbps and Wi-Fi is 20Mbps.
• Wide Area Network (WAN), extend the range used by LANs to connect a number of cities or establishments in
the same city. Optic fiber cables, leased telephone lines and radio transmission are used to connect WAN nodes,
Internet is the largest WAN in the world.
• Metropolitan Area Network (MAN) is sandwiched between a LAN and a WAN, employed for interconnecting
computers in the same city.
• Campus Area Network (CAN), smaller than MAN and it is used to connect an entire university campus.
• Personal Area Network (PAN), smallest network of all, operates within a range of a few meters. It connects small
devices like cellphones and laptops with infrared or Bluetooth technology.
The Internet and internet
The Internet also called Net is the largest WAN with collection of 50,000 networks that run a special set of network
protocols called TCP/IP. Born in 1983 at US Ministry of Defense, it is today a self-governing network without an owner
which grows continuously without disturbing the existing structure. The hardware technology used by the Internet is same
as any LAN or WAN.
Creating small networks of this type that can replicate Internet services on a smaller scale, runs the same set of
network protocols is called an internet. Depending on the way it is configured, an internet may or may not have access to
the Internet. The addresses used by internet nodes are not valid on the Internet.

Network Hardware
Network Interface Card
Network transmission begins from the Network Interface Card (NIC) or network card that is inside the computer,
because most networks use Ethernet technology, this card is often referred as Ethernet card. The card functionality is
implemented in the following ways:
• Built into the motherboards of laptops and current desktops.
• As a separate card inserted into a slot on the motherboard.
• As a wireless card inserted in the same manner; needs no cables.
• As a USB adapter that runs on the USB port.
Every Ethernet card has a unique MAC (Machine Access Control) address hard-coded into the board by the card
manufacturer. The card is connected to a hub or switch via a cable with RJ45 connector at both ends.
Hub and Switch
Computers in a single network and using the star topology need a central device either a hub or a switch, which
contains a number of RJ45 ports that are connected by cables to the nodes

CSE@HKBKCE 15
18CPS13 C Programming for Problem Solving

A hub accepts network data from a computer and simply broadcasts the data to all nodes, which contain the MAC
address of the destination, only the node having that address will accept the data. The drawback is data have to travel to
all nodes.
A switch is intelligent, which has a table of all MAC addresses of the connected devices. The switch extracts the MAC
address from the data and then looks up the table to determine the node and the packet is sent only to that node. A
switch is efficient and is able to maintain the speed of a network.
Bridge and Router
As electrical signals travel in along a cable, it weaken, so Ethernet has a limit on the maximum size of the cable (100
meters) an only one device is able to transmit at a time, too many nodes lead to network congestion.
A network supporting many nodes must be split into a number of segments, with a bridge connecting them. A bridge
maintains a table of MAC addresses of all machines in the segments connected to it. It connects two networks using the
same protocol (say, Ethernet).
A router connects two similar or dissimilar networks which may be separated by long distances. It is a part of both
networks and thus has two addresses. A router looks up its routing table to determine the path a packet has to travel to
reach its destination. If the destination node is on the same network then the router sends the packet directly to the node.
Otherwise, it sends it to another router that takes it closer to its destination. A router is smarter than a bridge because it
can choose the best route for guiding the packet. This routing principle is used on the Internet.

Software Basics
Software is a collection of code that drives a computer to perform a related group of tasks. It comprises one or more
programs, supported by libraries and configuration files that programs need to access. Programs in software use a
language chosen from C, C++, Java, Python, to name a few.
The source code is created by a programmer using any languages is converted to machine code using compilers,
which is then distributed by software vendors. It is common for software to be developed for multiple platforms
(operating systems). Software developed for Windows 8 may run without modification on Windows 10. but it won't run
on Linux
Software vendors generally retain the rights to their product, which make illegal to copy it. Also they make only the
machine code available but not the source code. It is not possible to retrieve the source code by reverse-engineering the
machine code. These restrictions have led to the development of open source software which are completely free to use,
copy and redistribute including source code.

Software Types
Computer software is divided into two types:
1. System software: Run by the computer to manage the hardware connected to it. Users don't have much control
over its functioning, but their own programs use the services offered by system software whenever required.
2. Application software: Software related to a specific application, say, one that makes hotel bookings or creates
special effects in movies. The majority of programmers are engaged in developing application software.
System Software
To access and manage the CPU, memory, hard disk, monitor and keyboard, a software sits between the application
and the those hardware is known as system software. System software provides the services needed by programs and
users and most them is run by the computer on start-up, first from a ROM and then from the hard disk. The others are
invoked when programs need them, say, for printing a report. System software include but are not restricted to the
following:
1. Basic Input Output System (BIOS): A small program that checks the hardware devices and peripherals at boot
time and then loads the operating system.
2. Operating System (OS): Central system software manages both the hardware and programs running on the
computer. Because all programs need its services, the OS remains in memory as long as the computer is up.
3. Device driver: A special software that knows how to handle a hardware in computer. Programs access a device
driver by making a call to the operating system.
4. Compilers and associated programs: This type of system software is special because it is invoked by users. A
programmer invokes a compiler program to convert the source code written by them to machine code.

CSE@HKBKCE 16
18CPS13 C Programming for Problem Solving

Application Software
Software not directly connected with hardware but related to a specific real-life situation is known as application
software. Application software’s are not machine dependant. Examples:
1. Office software: Office software was one of its first application comprises three separate applications—word
processing, spreadsheet and presentations.
2. Database software: Known as Data Base Management System (DBMS) , allows data having a uniform structure
to be stored in a database. Each line of a database has multiple fields that may be added, modified and queried
using simple instructions. Microsoft Office has a DBMS component Access, but it is Oracle that dominates
3. Communications software: Allows users to communicate with one another. Email had been popular for offline
communication before Skype and Whatsapp moved in as online applications.
4. Entertainment software: Home entertainment on the PC has software for gaming and multimedia. The VideoLAN
(VLC) software for playing most audio and video formats. Gaming software remains extremely popular and
challenging for software developers
5. Antivirus software: A virus is a small program designed by a person with malicious intent, which cause programs
to misbehave or not work at al or wipe out data from the hard disk, Anti-virus software is to have on your
computer to prevent such viruses
6. Special-purpose software: An application software available for desktop publishing, computer-aided design/
manufacturing (CAD/CAM) and distance learning, to name a few.

2. Overview of C
History of C
The root of all modern languages is ALGOL, introduced in the early 1960s, ALGOL was the first computer language
to use a block structure. In 1967, Martin Richards developed a language called BCPL (Basic Combined Programming
Language) primarily for writing system software.
In 1970, Ken Thompson created a language using many features of BCPL and called it simply B. B used to create
early versions of UNIX operating system at Bell Laboratories. Both BCPL and B were "typeless” programming languages.
C was evolved from ALGOL, BCPL and B by Dennis Ritchie at the Bell Laboratories in 1972. C uses many concepts from
these languages and added the concept of data types and other powerful features.
During 1970s, C had evolved into what is now known as "traditional C". The language became more popular after
publication of the book 'The C Programming Language' by Brian Kerninghan and Dennis Ritchie in 1978. The book was
so popular that the language came to be known as “KR C" among the programming community.
In 1983, American National Standards Institute (ANSI) appointed a technical committee to define a standard for C,
which approved a version of C in December 1989 which is now known a ANSI C. It was then approved by the
International Standards Organization (ISO) in 1990 which is referred as version C89.
The standardization committee of C felt that a few features of C++/Java, added to C, would enhance the usefulness
of the language. The result was the 1999 standard for C, referred as C99.

CSE@HKBKCE 17
18CPS13 C Programming for Problem Solving

Importance of C
• C is a robust language whose rich set of built-in functions and operators can be used to write any complex program.
• The C compiler combines the capabilities of an assembly language with the features of a high-level language and
therefore it is well suited for writing both system software and business packages.
• Programs written in C are efficient and fast, due to its variety of data types and powerful operators.
• There are only 32 keywords in ANSI C and its strength lies in its built-in functions.
• Several standard functions are available for developing programs.
• C is highly portable, that is C programs written for one computer can be run on another with little or no
modification.
• C language is well suited for structured programming, thus requiring the user to think of a problem in terms of
function modules or blocks. This modular structure makes program debugging, testing and maintenance easier.
• Important feature of C is its ability to extend itself. A C program is basically a collection of functions that are
supported by the C library. One can continuously add own functions to C library.
Sample Program 1: Printing a Message
A program to print one line text
main( )
{
/*…….printing begins…………*/
printf (“I see, I remember");
/*…….printing ends…………*/
}
This program will produce the following output: I see, I remember. The first line informs the system that the name
of the program is main and the execution begins at this line. The main( ) is a special function used by the C to tell the
computer where the program starts Every program must have exactly one main function. The empty pair of
parentheses after main indicates that the function main has no arguments (or parameters). The opening brace { in the
second line marks the beginning of the function main and the closing brace } in the last line indicates the end of the
function. All the statements between these two braces farm the function body.

Sample Program 2: Adding Two Numbers


A program to performs addition on two numbers and displays the result
main() /* Program ADDITION Written by EBG */
{
int number;
float amount;
number = 100;
amount = 30.75 + 75.35;
printf("%d\n”, number);
printf(%5.2f”, amount);
}
This program when executed will produce the following output: 100
106.10
The words number and amount are variable names that are used to store numeric data.
int number;
float amount; tell the compiler that number is an integer (int) and amount is a floating (float) point number,
this declaration statements must appear at the beginning of the functions
The words int and float are called the keywords and cannot be used as variable names. Data is stored in a variable
by assigning a data value to it, for example number = 100; The print statement: printf("%d\n", number) contains two
arguments. The first argument "%d" tells the compiler that the value of the second argument number should be printed
as a decimal integer.

CSE@HKBKCE 18
18CPS13 C Programming for Problem Solving

Basic Structure of C Programs


C program can be viewed as a group of building blocks called functions. A function is a subroutine that may include
one or more statements designed to perform a specific task. To write a C program, first create functions and then put
them together
Documentation Section
Link Section
Definition Section
Global Declaration Section
main () Function Section
{
Declaration part
Executable part /Program statements
}
Subprogram section
Function 1(User-defined functions)
Function 2
---
---
Function n
• The documentation section consists of a set of comment lines giving the name of the program, the author and other
details.
• The link section provides instructions to the compiler to link functions from the library.
• The definition section defines all symbolic constants.
• There are some variables that are used in more than one function are called global variables and are declared in the
global declaration section that is outside of all the functions. This section also declares all the user-defined functions.
• Every C program must have one main() function section. This section contains two parts, declaration part and
executable part. The declaration part declares all the variables used in the executable part. There is at least one
statement in the executable part, it appear between the {and }.The program execution begins at the opening brace
and ends at the closing brace. All statements in the declaration and executable parts end with a semicolon (;).
• The subprogram 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
/*Program to calculate the area of a circle Documentation Section */
#include<stdio.h> /* Link section */
#define PI 3.14 /*Definition section*/
void main ( )
{
float r, Area;
printf("enter the radius of the circle");
scanf("%f",&r);
Area=PI*r*r;
printf("Area=%f",Area);
}

Executing a 'C' Program


Executing a C program involves a series of following steps.
1. Creating the program;
2. Compiling the program;
3. Linking the program with functions that are needed from the C library;
4. Executing the program;
The steps remain same irrespective of the operating system (OS), system commands for implementing the steps
and conventions for file names may differ on different systems. The OS is an interface between the hardware and the

CSE@HKBKCE 19
18CPS13 C Programming for Problem Solving

user, handles the execution of user programs and all input/output operations are channelled through it. The two most
popular operating systems are UNIX (for minicomputers) and MSDOS(for microcomputers)

3. Constants Variables and Data Types

Character Set
The characters in C are grouped into the following categories:
1. Letters: Uppercase A-Z and Lowercase a-z
2. Digits: 0-9
3. Special characters: , . ;:? ‘“!| / \ ~ _ $ % & ^ * - + < > ( ) { }[ ] #
4. White spaces: Blank space(\b), Horizontal tab(\h), Carriage return(\r), Newline(\n), Form feed(\f)
if a keyboard does not support square brackets, we can still use them in a program using the trigraphs ??. ANSI C
Trigraph Sequences:

C Tokens
In a C program the smallest individual units are known as C tokens. C has six types of tokens.
1. Keywords (eg: int, while),
2. Identifiers (eg: main, total),
3. Constants (eg: 10, 20),
4. Strings (eg: “total”, “hello”),
5. Special symbols (eg: (), {}),
6. Operators (eg: +, /,-,*)
C programs are written using these tokens and the syntax of the language

CSE@HKBKCE 20
18CPS13 C Programming for Problem Solving

Keywords and Identifiers


Every C word is classified as either a keyword or an identifier. All keywords have fixed meanings and these
meanings cannot be changed. Keywords serve as basic building blocks for program statements. The list of all keywords
of ANSI C are in the below table.

Identifiers refer to the names of variables, functions and arrays. These are user-defined names and consist of a
sequence of letters and digits, with a letter as a first character. Both uppercase and lowercase letters are permitted,
although lowercase letters are commonly used. The underscore character is also permitted in identifiers, which is used
as a link between two words in long identifiers.
Rules for Identifiers:
1. First character must be an alphabet (or underscore).
2. Must consist of only letters, digits or underscore.
3. Only first 31 characters are significant.
4. Cannot use a keyword.
5. Must not contain white Space,

Constants
Constants in C refer to fixed values that do not change during the execution of a program. C supports several types
of constants

Integer Constants
An integer constant refers to a sequence of digits. There are three types of integers: decimal integer, octal integer
and hexadecimal integer. Decimal integers consist of a set of digits, 0 through 9, preceded by an optional - or + sign.
Embedded spaces, commas, and non-digit characters are not permitted between digits
Examples: 123 -321 0 654321 +78
An octal integer constant consists of any digits from the set 0 to 7, with a leading 0.
Examples of octal integer: 037 0 0435 0551
A sequence of digits preceded by 0x or 0X is considered as hexadecimal integer, which include alphabets A through
F or a through f to represent the numbers 10 through 15.
Examples of hex integers: 0X2 0x9F 0Xbcd 0x0
The largest integer value that can be stored is machine-dependent. It is 32767 on 16-bit machines and 2,147,483,647
on 32-bit machines. It is also possible to store larger integer constants on these machines by appending qualifiers U, L
and UL to the constants.
Examples:
56789U or 56789u (unsigned integer)
987612347UL or 98761234ul (unsigned long integer)
9876543L or 9876543l (long integer)
CSE@HKBKCE 21
18CPS13 C Programming for Problem Solving

Real Constants
The quantities that vary continuously are represented by numbers containing fractional parts like 17.548, which
are called real (or floating point) constants.
Examples of real constants are: 0.0083 -0.75 435.36 +247.0
In the decimal notation, it is possible to omit digits before the decimal point or after the decimal point. That is 215.
.95 -7.2 +.5 are all valid real numbers. A real number expressed in exponential (or scientific) notation has the form :
mantissa e exponent
The mantissa is either a real number expressed in decimal notation or an integer. The exponent is an integer
number with an optional plus or minus sign. The letter e can be written in either lowercase or uppercase. Since the
exponent causes the decimal point to float, this notation is known floating point representation. Examples are: 0.65e4
12e-2 1.5e+5 3.18E3 -1.2E-1
6983541L Yes Represents long integer 25,000 No Comma is not allowed
+5.0E3 Yes (ANSI C supports unary plus) 3.5e-5 Yes
7.1e 4 No No white space is permitted 1,5E+2.5 No Exponent must be an integer
5255 No $ symbol is not permitted OX7B Yes Hexadecimal integer

Single Character Constants


A single character constant (or character constant) contains a single character enclosed within a pair of single quote
marks. Example: ‘5’ ‘X’ ‘,’ ‘‘
Character constants has integer values known as ASCII values. For example: printf(“'%d”, ' a ' ) ; would print the
number 97, ASCII value of the a. printf(“%c”, 97); will output the letter 'a.'
String Constants
A string constant is a sequence of characters enclose in double quotes. The characters may be letters, numbers,
special characters and blank space.
Examples are: “Hello” “1972" “WELL DONE" “?….!" "5+3" "X"
A character constant ‘X’ is not equivalent to the single character string constant "X“. A single character string
constant do not have an equivalent ASCII value while a character constant has an integer value.
Backslash Character Constants
C supports special backslash character constants that are used in output functions. Example ‘\n’ stands for
newline character. Each one of them represents one character, although they consist of two characters. These
characters combinations are known as escape sequences. A List backslash character constants
‘\a’ audible alert (bell) ‘\b’ back space ‘\f’ form feed
‘\n’ new line ‘\r’ carriage return ‘\t’ horizontal tab
‘\v’ vertical tab ‘\’’ single quote ‘\”’ double quote
‘\?’ question mark ‘\\’ backslash ‘\0’ null
Variables
A variable is a data name that may be used to store a data value. Constants remain unchanged during the execution
of a program, but a variable may take different values at different times during execution. The variable amount in
Sample Program to store the value of money at the end of each year after adding the interest earned during that year.
A variable name is chosen by the programmer in a meaningful way to reflect its function or nature in the program.
Examples: Average height Total Counter_1 class_strength
Variable names consist of letters, digits, and the underscore (_) character, subject to the following conditions:
1. They must begin with a letter, or underscore.
2. ANSI standard recognizes a length of 31 characters. However, length should net be more than eight characters,
since only the first eight characters are treated as significant by many compilers. (In C99, at least 63 characters
are significant )
3. Uppercase and lowercase are significant, That is, the variable ‘Total is not the same as total or TOTAL,
4. It should not be a keyword.,
5. White space is not allowed.
Examples of valid variable names: John Value T_raise Delhi x1 ph_value mark sum distance int_type first_char
Invalid examples: 123 (area) % 25th char Price$ Avg+Value group 1

CSE@HKBKCE 22
18CPS13 C Programming for Problem Solving

Data Types
ANSI C supports three classes of data types
1. Primary (or fundamental) data types
2. Derived data types
3. User-defined data types
All C compilers support five fundamental data types, integer (int), character (char), floating point (float), double-precision
floating point (double) and void. Many of them also offer extended data types such as long int and long double.
Primary Data Types
1. Integer:
int unsigned int
Data Types Range of Values
short int unsigned short int
char -128 to 127
long int unsigned long int
int -32768 to 32767
2. Character:
char signed char unsigned char float 3.4e-38 to 3.4e+38
3. Floating Point Types: double 1.7e-308 to 1.7e+308
float double long double
4. Void: void
Integer Types
Integers are whole numbers with a range of values supported by a particular machine. Integers occupy one
word of storage, and since the word sizes of machines vary (16 or 32 bits) the size of an integer that can be stored
depends on the computer. C has three classes of integer storage, namely short int, int, and long int, in both signed and
un-signed forms. Declare int using long and unsigned integers to increase the range of values. The use of qualifier
signed on integers is optional because the default declaration assumes a signed number
Floating Point Types
Floating point (or real) numbers are stored in 32 bits(float) with 6 digits of precision. When the accuracy
provided by a float number is not sufficient, the type double can be used to define the number. A double data type
number uses 64 bits(double) giving a precision of 14 digits and known as double precision numbers. To extend the
precision further, use long double which uses 80 bits.
Void Types
The void type has no values and used to specify the type of functions. The type of a function is said to be void if it
does not return any value to the calling function. It can also play the role of a generic type ie. it can represent any of
the other standard types.
Character Types
A single character can be defined as a character (char) type data and stored in 8 bits. The qualifier signed or
unsigned may be explicitly applied to char. While unsigned chars have values between 0 and 255, signed chars have
values from 128 to 127.

Declaration of Variables
After designing suitable variable names, declare them to the compiler. Declaration does two things:
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
The declaration of variables must be done before they are used in the program.

CSE@HKBKCE 23
18CPS13 C Programming for Problem Solving

Primary Type Declaration


A variable can be used to store a value of any data type ie the name has nothing to do with its type. The syntax for
declaring a variable is: datatype v1, v2, …vn; where vl1, v2, ..., vn are the names of variables
In a declaration statement variables are separated by commas and end with a semicolon. For example, valid
declarations are: int count;
int number, total;
double ratio; where int and double are the keywords to represent integer type and real
type data values respectively.
User-Defined Type Declaration
C supports a feature known as "type definition" that allows users to define an identifier that would represent an
existing data type, which can later be used to declare variables. It takes the general form: typedef type identifier;
where type refers to an existing data type and "identifier" refers to the "new" name given to the data type.
The existing data type may belong to any class of type, including the user defined ones. Remember that the new
type is 'new' only in name, but not the data type. typedef cannot create a new type. Examples:
typedef int units;
typedef float marks;
They can be used to declare variables as follows: units a, b;
marks total, avg;
Advantage of typedef is that can create meaningful data type names for better the readability of the program.

User-Defined Type Declaration


Another user-defined data type is enumerated data type, it is defined as:
enum identifier {value1, valtue2,.., valueN };
The "identifier" is a user-defined enumerated data type which can be used to declare variables that can have
one of the values enclosed within the braces To declare variables to be of this 'new' type is:
enum identifier v1, v2, ... vn;
The enumerated variables v1, v2, …, vn can only have one of the values value', value2, valuen. The assignments
of the following types are valid: v1 = vaiue3;
v2 = value1;

An example: enum day {Monday, Tuesday, …, Sunday};


enum day week_st, week_end;
week_st = Monday;
week_end = Friday;
if (week_st == Tuesday)
week_end = Saturday;
The compiler assigns integer digits beginning with 0 to all the enumeration constants, ie., the enumeration constant
value1 is assigned 0, value 2 is assigned 1, and so on. This automatic assignments can be overridden by assigning values
explicitly to the enumeration constants. For example: enum day {Monday = 1, Tuesday, ... Sunday};
Here, the constant Monday is assigned 1, the remaining constants are assigned values that increase successively
by 1. The definition and declaration of enumerated variables can be combined in one statement. Example: enum day
(Monday, .. . Sunday) week_st, week_end;

Declaration of Storage Class


C provides storage class specifiers that can be used to declare explicitly the scope and lifetime of variables. The
scope and lifetime are important only in multifunction and multiple file programs. There are four storage class
specifiers:
1. auto: Local variable known only to the function in which it is declared. Default is auto
2. static: Local variable which exists and retains its value even after the control is transferred to the calling
function.
3. extern: Global variable known to all functions in the file.
4. register: Local variable which is stored in the register.

CSE@HKBKCE 24
18CPS13 C Programming for Problem Solving

Storage class is another qualifier (like long or unsigned) that can be added to a variable declaration:
auto int count;
register char ch;
static int x;
extern long total ;
Static and external (extern) variables are automatically initialized to zero. Automatic (auto) variables contain
undefined values (known as 'garbage') unless they are initialized explicitly.

Assigning Values to Variables


Values can be assigned to variables using the assignment operator = as follows:
varlable_name = constant;
Examples: initial_value = 0;
final_value = 100;
balance = 75.84;
C permits multiple assignments in one line: initial_value = 0; final_value = 100;
An assignment statement implies that the value of the variable on the left of the 'equal sign' is set equal to the
value of the quantity (or the expression) on the right. year = year + 1; means that the new value of year is equal to the
'old value' of year plus 1.
During assignment operation, C converts the data type of value on the right-hand side to the data type on the left,
which involve truncation when real value is converted to an integer.
It is possible to assign a value to a variable at the time the variable is declared:
Syntax: data-type variable_name = constant ,
Examples: int final_value = 100;
char yes = 'x';
The process of assigning initial values to variables is called initialization. C permits the initialization of more than
one variables in one statement using multiple assignment operators.
Valid assignment statements: a = b = c = 0; /* a b & c initialized to 0 */
x= y = z = MAX; /* x y & z initialized to MAX */
Example Program:
main()
{
float x, p ;
double y, q;
unsigned k ;
int m = 54321 ;
long int n = 1234567890;
x = 1.234567890000
p = q = 1.0 ;
printf(“m = %d\n”. m);
printf(“n = %ld\n”, n);
printf(“x = %.12lfd\n”, x);
printf(“x = %f\n”, x);
printf(“m = %d\n”);
printf(“k = %u p = %f q = %.12lf\n”, k,p,q);
}
Output:
m = -11215
n = 1234567890;
x = 1.234567890000
x = 1.234567
k = 54321 p = 1.000000 q = 1.0000000000000

CSE@HKBKCE 25
18CPS13 C Programming for Problem Solving

Reading Data from Keyboard


Another way of giving values to variables is to input data through keyboard using the scanf function, which is a
input function in C and is similar in concept to the printf function.
Syntax: scanf ( “Control string“, &rvariable1, &rvariable2, …);
The control string contains the format of data being received and ampersand symbol & before each variable name
is an operator to specify the variable name's address.
Example: scanf(“%d", &number);
When this statement is encountered by the computer, the execution stops and waits for the value of the variable
number to be typed in from keyboard. The control string "%d" specifies an integer value is to be read from the terminal,
so, type in the value in integer form. After the number is typed in and the ‘Enter' Key is pressed, it proceeds to the next
statement. If the scanf function contains 3 variables, the values entered must match the order and type of the variables
in the list. Any mismatch might lead to unexpected results. The compiler may not detect such errors.

Defining Symbolic Constants


The unique constants in a program may appear repeatedly in a number of places. For example constant 3.142,
representing the value of "pi“ and total number of students, say 50, may be used for calculating the class total and
average. Two problems in the subsequent use of such programs
1. Modification of the program(Modifiability)
• To change the value of "pi" from 3.142 to 3.14159 to improve the accuracy or the number 50 to 100 to
process the test results of another class.
• In both cases, have to search throughout the program and explicitly change the value of the constant
wherever it has been used.
2. Understanding the program.
• When a numeric value appears in a program, its use is not always clear, when the same value means
different things in different places.
• For example, the number 50 may mean the number of students at one place and the 'pass marks' at another
place.
Assignment of such constants to a symbolic name frees from remembering what number 50 meant. Assignment of
such constants to a symbolic name frees from these problems
A constant is defined as follows:
#define symbolic-name value-of-constant
Valid examples:
#define STRENGTH 100
#define PASS MARK 50
#define MAX 700
#define PI 3.14159
Symbolic names are sometimes called constant identifiers. The rules to form a #define statement which define a
symbolic constant:
1. Symbolic names have the same form as variable names, as a convention it is written in CAPITALS to visually
distinguish them from the variable names
2. No blank space between the pound sign #and the word define.
3. #must be the first character in the line.
4. A blank space is required between #define and symbolic name and between the symbolic name and the
constant.
5. #define statements must not end with a semicolon.
6. After definition, the symbolic name should not be assigned any other value within the program by using an
assignment statement.
7. Symbolic names are NOT declared for data types, Its data type depends on the type of constant.
8. #define statements may appear anywhere in the program but before it is referenced in the program
Declaring a Variable as Constant
To make the value of certain variables to remain constant during the execution of a program, the variable is declared
with the qualifier const at the time of initialization.
Example: const int size = 40;

CSE@HKBKCE 26
18CPS13 C Programming for Problem Solving

const is a data type qualifier tells the compiler that the value of the int variable size must not be modified by the
program. It can be used on the right hand side of an assignment statement like any other variable.

Declaring a Variable as Volatile


The qualifier volatile is used to tell explicitly the compiler that a variable's value may be changed at any time by
some external sources that is, from outside the program.
For example: volatile int date;
The value of date may be altered by some external factors even if it does not appear on the left-hand side of an
assignment statement. The value of a variable declared as volatile can be modified by its own program as well.

Overflow and Underflow of Data


Data overflow occurs when the value of a variable is either too big or too small for the data type to hold. The
largest value that a variable can hold is depends on the machine. The floating-point values are rounded off to the
number of significant digits allowed or specified, so an overflow results in the largest possible real value, whereas an
underflow results in zero.
Integers are always exact within the limits of the range of the integral data types used. An overflow is a serious
problem if the data type does not match the value of the constant. C does not provide any warning or indication of
integer overflow.

4. Operators and Expressions

Introduction
An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations.
Operators are used in programs to manipulate data and variables. They form a part of the mathematical or logical
expressions. C operators can be classified into 8 categories:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators
An expression is a sequence of operands and operators that reduces to a single value. For example, 10 + 15 is an
expression whose value is 25.

Arithmetic Operators
C provides all the basic arithmetic operators
+ Addition or unary plus (a + b)
- Subtraction or unary minus(a - b)
* Multiplication (a * b)
/ Division (a / b)
% Modulo division (a % b)
Integer division truncates any fractional part. The modulo division operation produces the remainder of an integer
division and cannot be used on floating point data. C does not have an operator for exponentiation.
Examples: a – b; a + b; a * b; a / b; a % b; -a + b; where a & b called as operands
Integer Arithmetic
When both the operands in a arithmetic expression are integers, the expression is called an integer expression and
the operation is called integer arithmetic which results an integer value.
Example: when a = 14 and b = 4 the results are :
a - b = 10 a + b = 18 a * b = 56
a / b = 3 (decimal part truncated)
a % b = 2 (remainder of division)

CSE@HKBKCE 27
18CPS13 C Programming for Problem Solving

if both the operands are of the same sign, the result is truncated to zero. If one of them is negative, the direction
of truncation is implementation dependent, ie. 6/7=0 and -6/-7=0, but -6/7 may be 0 or -1(Machine dependent)
Real Arithmetic
An arithmetic operation involving only real operands is called real arithmetic. A real operand values either in
decimal or exponential notation. Since floating point values are rounded to the number of significant digits permissible,
the final value is an approximation of the correct result.
If x, y, and z are floats, then: x = 6.0/7.0 = 0.857143
y = 1.0/3.0 -= 0.333333
z = 0.333333 * 3.0 = 0.999999
x = -2.0 / 3.0 = -0..666667
Mixed-mode Arithmetic
When one of the operands is real and the other is integer, the expression is called a mixed mode arithmetic
expression. If either operand is of the real type, then only the real operation is performed and the result is always a
real number. That is 15/10.0 = 1.5 but 15/10= 1
Relational Operators
Relational operators in C is used to make a decision based on comparing 2 quantities. The symbol '<', meaning 'less
than’ in an expression a < b or 1 < 20 containing a relational operator is termed as a relational expression. The value of
a relational expression is one if the specified relation is true and zero if the relation is false.
For example: 10 < 20 is true & 20 < 10 is false
C supports six relational operators
Operators Meaning
< Is less than
<= Is less than or equal to
> Is greater than
>= Is greater than or equal to
== Is equal to
!= Is not equal to
A simple relational expression contains one relational operator and syntax:
ae-1 relational_operator ae-2 where ae-1 and ae-2 are arithmetic expressions, which may be simple
constants, variables or both
• Example : 4.5 <= 10 TRUE
10 < 7+5 TRUE
Arithmetic operators have a higher priority over relational operators. Relational expressions are used in decision
statements such as if and while to decide the course of action.
Relational Operator Complements: > is complement of <=
< is complement of >=
== is complement of !=
Logical Operators
C has three to logical operators:
&& meaning logical AND
|| meaning logical OR
! meaning logical NOT
The logical operators && and || are used to test more than one condition and make decisions,
Example: a > b && x == 10
An expression which combines two or more relational expressions, is called as a logical expression or a compound
relational expression. A logical expression results in a value of 1 (TRUE) or 0 (FALSE). The above expression is true only
if a > b is true and x == 10 is true. if either (or both) of them are false, the expression is false,
Op-1 Op-2 Op-1 && Op-2 Op-1 && Op-2
0 0 0 0
0 Non-zero 0 1
Non-zero 0 0 1
Non-zero Non-zero 1 1

CSE@HKBKCE 28
18CPS13 C Programming for Problem Solving

Examples:
1. if (age > 55 && salary < 1000)
2. if (number < 0 || number > 100)
Relative precedence of the relational and logical operators are
Highest !
> >= < <=
== !=
&&
Lowest ||
Assignment Operators
Assignment operators are used to assign the result of an expression to a variable. C has shorthand assignment
operators:
v op= exp; where v is a variable, exp is an expression and op is an operator. v op= exp is equivalent to v = v op (exp);
Example:
x += y+1;  x = x + (y+1);
The use of shorthand assignment operators. What is on the left-hand side need not be repeated. The statement is
more concise and easier to read. The statement is more efficient
Example Program:

void main()
{
int a =1;
while (a<20)
{
printf(“d\n”, a);
a += a;
}
}

Increment and Decrement Operators


C has increment (++) and decrement (--) operators which are generally not found in other languages. The operator
++ adds 1 to the operand, while -- subtracts 1. Both are unary operators and has the following form:
++m or m++
--m or m--
++m; ----> m = m + 1; or m += 1;
--m; ----> m = m - 1; or m -= 1;
While ++m and m++ mean the same thing when they are independent form statements, they behave differently
when they are used in expressions on the right-hand side of an assignment statement.
m = 5;
y = m++; the value of y and m is 6_ Suppose, if we rewrite the above statements.
A prefix operator first adds I to the operand and then the result is assigned to the variable on left.
m = 5;
y = m++; the value of y is 5 and m is 6.
A postfix operator first assigns the value to the variable on left and then increments the operand.
Rules for ++ and -- Operators
These operators can be used in complex statements.
• Example: m = n++ -j +10; here old value of n is used in evaluating the expression.
Rules
1 Increment and decrement operators are unary operators and they require variable as their operands.
2 When postfix ++ or -- is used with a variable in an expression, the expression is evaluated first using the
original value of the variable and then the variable is incremented (or decremented) by one
3 When prefix ++( or--) is used in an expression, the variable is incremented (or decremented) first and then
the expression is evaluated using the new value of the variable.
4 The precedence and associatively of ++ and -- operators are the same as those of unary + and unary -
CSE@HKBKCE 29
18CPS13 C Programming for Problem Solving

Conditional Operator (Ternary Operator)


A ternary operator pair “?:” in C used to construct conditional expressions of the form
exp1? exp2 : exp3; where exp1, exp2 and exp3 are expressions.
Here exp1 is evaluated first, if it is nonzero (true), then the expression exp2 is evaluated and becomes the value of
the expression, If exp1 is false, exp3 is evaluated and its value becomes the value of the expression, Ie.only one of the
expressions (either exp2 or exp3 is evaluated.
For example:
a = 10;
b = 15;
x = (a > b) ? a : b; x will be assigned the value of b.
This can be achieved using the if -- else
if (a > b)
x = a;
else
x = b;

Bitwise Operators
C supports special operators known as bitwise operators for manipulation of data at bit level. These operators are
used for testing the bits, or shifting them right or left. Bitwise operators are not be applied to float or double.
Bitwise Operators
Operators Meaning
& bitwise AND
| bitwise OR
^ bitwise exclusive OR
<< shift left
>> shift right
Example: x = 13 and y = 25 then
x = 0000 0000 0000 1101
y = 0000 0000 0001 1001
a = x & y; -> a = 0000 0000 0000 1001 ->9
b = x | y; -> b = 0000 0000 0001 1101 ->29
c = x ^ y; -> c = 0000 0000 0001 0100 ->20
d = x >>2; -> d = 0000 0000 0000 0011 ->3
e = x <<2; -> e = 0000 0000 0011 0100 ->52

Special Operators
C supports special operators comma operator, sizeof operator, pointer operators (& and *) and member selection
operators (. and —> )
The Comma Operator
The comma operator used to link the related expressions together. A comma-linked list of expressions are
evaluated left to right and the value of right-most expression is the value of the combined expression.
Example: value = (x = 10, y = 5, x + y);
Here it first assigns the value 10 to x, then assigns 5 to y and assigns 15 (i.e. 10 + 5) to value.
Comma operator has the lowest precedence of all operators, the parentheses are necessary. Applications of
comma operator:
In for loops: for ( n = 1, m = 10; n <=m; n++, m++)
In while loops: while (c = getchar(), c != ‘y’ )
Exchanging values t = x, x = y, y = t;
The sizeof Operator
The sizeof is a compile time operator and returns the number of bytes the operand occupies. The operand may be
a variable, a constant or a data type qualifier.
Examples:
m = sizieof (sum);
CSE@HKBKCE 30
18CPS13 C Programming for Problem Solving

n = sizeof (long int);


k = sizeof (235I.);
The sizeof operator is used to
1. Determine the lengths of arrays and structures when their sizes are not known.
2. Allocate memory space dynamically to variables during execution of a program

Arithmetic Expressions
An arithmetic expression is a combination of variables, constants, and operators arranged as per the syntax of the
language. C can handle any complex mathematical expressions, but C dont have exponential operator.
Example
ab-c -> a*b–c
𝑎𝑏
𝑐
-> a*b/c
3 2
3x +2x +x+1 -> 3*x*x*x+2*x*x+x+1
𝑥
𝑦
+𝑐 -> 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, the expression is evaluated first and the result 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.
Examples of evaluation statements are
x = a * b- c;
z= a - b / c + d; when these statements are used in a program, the variables x,z, a, b, c, and d must be defined
before they are used in the expressions.

Precedence of Arithmetic Operators


An arithmetic expression without parentheses will be evaluated from left to right using the rules of precedence of
operators. There are two priority levels of arithmetic operators:
High priority * %
Low priority + -
The evaluation includes two left-to-right passes through the expression.
In pass 1, high priority operators (if any) are applied as they are encountered.
In pass 2, low priority operators (if any) are applied as they are encountered.
Example: x = 9 – 12 /3 + 3 * 2 – 1;
Pass1: Step1: x = 9 – 4 + 3 * 2 - 1;
Step2: x = 9 – 4 + 6- 1;
Pass2: Step3: x = 5 + 6- 1;
Step4: x = 11 - 1;
Step5: x = 10

The order of evaluation can be changed using parentheses into an expression.


Example: x = 9 – 12 / (3 + 3) * (2 – 1); when parentheses are used, the expressions within parentheses has
highest priority.
If two or more sets of parentheses appear one after another, the expressions left-most set is evaluated first and the
right-most in the last.
Pass 1: Step1: x = 9 – 12 / 6 * (2 – 1);
Step2: x = 9 – 12 / 6 *1;
Pass 2: Step3: x = 9 – 2 * 1;
Step4: x = 9 – 2;
Pass 3: Step5: x =7;

CSE@HKBKCE 31
18CPS13 C Programming for Problem Solving

Rules for Evaluation of Expression


• First, parenthesized sub expression from 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 associativity rule is applied when two or more operators of the same precedence level appear in a sub-
expression
• Arithmetic expressions are evaluated from left to right using the rules of precedence.
• When parentheses are used, the expressions within parentheses has highest priority.
Computational Problems
First Problem is the computer gives approximate values for real numbers and the errors, due to such
approximations computation may lead to serious problems.
Example: a = 1.0/3.0;
b = a * 3.0; (1.0/3.0) is equal to 1, but there is no guarantee that the value of b computed will equal to 1.
Second problem is division by zero. On most computers, any attempt to divide a number by zero will result in
abnormal termination of the program or meaningless results. Here test the denominator that is likely to assume zero
value and avoid any division by zero.
Third problem is avoiding Overflow or Underflow errors. Make sure that operands are correct type and range and
result produced will not overflow or underflow

Type Conversions in Expressions


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 conversion is known as implicit type conversion.If the operands are of different types, the 'lower' type is
automatically converted to the 'higher' type before the operation and result is higher type.
A typical type conversion process

Rules that are applied while evaluating expressions.


All short and char are automatically converted to int then:
1. if one of the operands is long double, the other will be converted to long double and the result will be long double;
2. else, if one of the operands is double, the other will he converted to double and the result will be double;
3. else, if one of the operands is float, the other will he converted to float and the result will be float.
4. else, if one of the operands is unsigned long int, the other will he converted to unsigned long int and the result
will be unsigned long int;
5. else, if one of the operands is long int and the other is unsigned int, then
a) if unsigned int can be converted to long int, the unsigned int operand will be converted as such and the
result will be long int;
b) else, both operands will be converted to unsigned long int and the result will be unsigned long int;
6. else, if one of the operands is long int, the other will be converted to long int and the result will be long int;
7. else, if one of the operands is unsigned int, the other will be converted to unsigned int and the result will be
unsigned int.

CSE@HKBKCE 32
18CPS13 C Programming for Problem Solving

Conversion Hierarchy

The final result of an expression is converted to the type of the variable on the left of the assignment sign.
Following changes are introduced during the final assignment:
1. float to int causes truncation of the fractional part.
2. double to float causes rounding of digits.
3. long int to int causes dropping of the excess higher order bits
Explicit Conversion
Forcing a type conversion which is different from automatic conversion is known as Explicit Conversion or Casting
a Value or Typecast
Syntax: (type_name) expression; where type_name is standard data type
Example: ratio = (float)car_count / bike_count ; Here the operator (float) converts car_count to floating point for
the purpose of evaluation of the expression.
Examples:
x = (int) 7.5 7.5 is converted to integer 7 by truncation
a = (int) 21.3/(int)4.5 Evaluated as 21/4 and the result would be 5
b = (double)sum/n Division is done in floating point mode
y = (int)(a+b) The result of a+b is converted to integer
z = (int)a+b a is converted to integer and then added to b.
p = cos((double)x) Converts x to double before using it

Operator Precedence and Associativity


Each operator in C has precedence associated with it, which is used to determine how an expression involving more
than one operator is evaluated. There are distinct levels of precedence and an operator belong to one of levels. The
operators at the higher level are evaluated first. The operators of the same precedence are evaluated either form ‘left
to right’ or from ‘right to left’, depending on that levels associativity property.
Rules of Precedence and Associativity
• Precedence rules decides the order in which different operators are applied
• Associativity rule decides the order in which multiple occurrences of the same level operator are applied
Summary of C Operators Precedence and Associativity
Operator Description Associativity Rank
() Function call/ Parenthesis
Left to Right 1
[] Array Element reference
+ Unary plus
- Unary minus
++ Increment
-- Decrement
! Logical negation
Right to Left 2
~ Ones complement
* Pointer reference(indirection)
& Address
sizeof Size of an object
(type) Type cast (conversion)
CSE@HKBKCE 33
18CPS13 C Programming for Problem Solving

* Multiplication
/ Division Left to Right 3
% Modulus
+ Addition
Left to Right 4
- Subtraction
<< Left shift
Left to Right 5
>> Right shift
< Less than
<= Less than or equal to
Left to Right 6
> Greater than
>= Greater than or equal to
== Equality
Left to Right 7
!= Inequality
& Bitwise AND Left to Right 8
^ Bitwise XOR Left to Right 9
| Bitwise OR Left to Right 10
&& Logical AND Left to Right 11
|| Logical OR Left to Right 12
?: Conditional / Ternary Operator Right to Left 13
= *= /= %= += -= &=
Assignment Opertors Right to Left 14
^= |= <<= >>=
, Comma Operator Left to right 15
Mathematical Functions
Mathematical functions such as cos, sqrt, log, etc, are frequently used in analysis of real-life problems. C
compliers support these basic standard math functions from the Library math.h.

Function Meaning Function Meaning

acos(x) Arc cosine of x


ceil(x) x rounded up to the nearest integer
asin(x) Arc sine ofx
exp(x) e to the x power (ex)
atan(x) Arc tangent of x
fabs(x) Absolute value of x
atan 2(x,y) Arc tangent of x/y
floor(x) x rounded down to the nearest integer
cos(x) Cosine of x
fmod(x,y) remainder of x/y
sin(x) Sine of x
log(x) natural log of x,x>0
tan(x) Tangent of x
log10(x) Base 10 log x,x>0
cosh(x) Hyperbolic cosine of x
pow(x,y) x to the power y (xy)
sinh(x) Hyperbolic sine of x
sqrt(x) Square root of x,x>=0
tanh(x) Hyperbolic tangent of x

• x and y should be declared as double


• All the functions return a double

CSE@HKBKCE 34
18CPS13 C Programming for Problem Solving

Module 2
4 MANAGING INPUT AND OUTPUT OPERATIONS
Reading, processing, and writing of data are the three essential functions of a computer program.

Unlike other high-level languages, C does not have any built-in input/output statements as part of its syntax. All
input/output operation are carried out through function calls such as prinf() and scanf(). These functions are collectively
known as the standard I/O library.

Each program that uses a standard input/output function must contain the following statement at the beginning
#include <stdio.h>

4.1 Reading a Character


Reading a single character can be done by using the function getchar.
General form/Syntax : variable_name = getchar ();
variable_name is a valid C name that has been declared as char type. When this statement is encountered, the
computer waits until a key is pressed and then assigns this character as a value to getchar function.

Example:
char name;
name = getchar (); will assign the character ‘H’ to the variable name when we press the key H on the
keyboard.
Table 4.1 Character Test functions
Function Test
isalnum(c) Is c an alphanumnberic character?
isalpha(c) Is c an alphabetic character?
isdgit(c) Is c a digit?
islower(c) Is c lower case letter?
isprint(c) Is c a printable character?
ispunct(c) Is c a punctuation mark?
isspaace(c) Is c a whit space character?
isupper(c) Is c an upper case letter?
4.2 Writing a character
function putchar writes characters one at a time to the terminal. Genral form/Syntax: putchar (variable_name);
where variable_name is a type char variable containing a character. This statement displays the
character contained in the variable_name at the terminal. For example, the statements
answer = ‘Y’
putchar (answer);
will display the character Y on the screen. The statement
putchar (‘\n’);
would cause the cursor on the screen to move to the beginning of the next line.

Example Programs
Write a program to test whether the character is a digit or letter
#include <stdio.h>
#include <ctype.h>
main ()
{
char character;
printf(“press any key\n”);
character = getchar ();
if (isalpha(character) > 0)/* test for letter */
CSE@HKBKCE 35
18CPS13 C Programming for Problem Solving

printf(“ The character is a letter’’);


else if (isdigit (character) > 0)/* test for digit */
printf(“ The character is a digit’’);
else
printf(“ The character is not alphanumeric”);
}

Output
Press any key
h
The character is a letter.
Press any key
5
The character is a digit

Write a program to read a character and print it in reverse case


#include <stdio.h.>
#include <ctype.h>
main ( )
{
char alphabet;
printf(‘’Enter an a alphabet’’);
putchar(‘\n’); /* move to next line*/
alphabet = getchar ( );
if (islower(alphabet));
putchar(toupper(alphabet));/* Reverse and display*/
else
putchar(tolower(alphabet));/* Reverse and display*/
}
Output
Enter an alphabet
a
A
Enter an alphabet
Z
z

4.3 Formatted Input- Scanf()


Formatted input refers to an input data that has been arranged in a particular format. The formatted input
function in c is scanf();

The general from of scanf is : scanf(“control string “, arg1,arg2,........argn);

The control string specifies the field format in which the data is to be entered and the arguments arg1, arg2, ,,,....argn
specify the address of locations where the data is stored. Control string and arguments are separated by commas.

Control string contains field specifications, which direct the interpretation of input data. It may include:
 The conversion character %,
 Data type character (or type specifier)- The data type character indicates the type of data that is to be
assigned to the variable associated with the corresponding argument.
 An optional number, specifying the field width

CSE@HKBKCE 36
18CPS13 C Programming for Problem Solving

Inputting integer numbers-


The field specification for reading an integer number is % wd
 The percentage sign(%) indicates that a conversion specification follows.
 W is an integer number that specifies the field width of the number to be read and as
 Data type character(d) , indicates that the number to read is in integer mode

Consider the following example:


scanf (“%d %d”, &num1, &num2);
If the input is 50 31426
The value 50 is assigned to num1 and 31426 to num2

Inputting Real Number


The field specification for reading an integer number is % wf

 The percentage sign(%) indicates that a conversion specification follows.


 W is an integer number that specifies the field width of the number to be read and as
 Data type character(f) , indicates that the number to read is in float mode

Consider the following example:


The statement
scanf(“%f %f %f”, &x. &y, &z)
with the input data
475.89 43.21 678
will assign the value 475.89 to x, 43.21 to y, and 678.0 to z.

Inputting Character Strings

Characters can be read using %wc


Strings can be read using %ws

Example: scanf(“%c%c”, &x,&y)


Input data A b
Will assign the character A to x and b to y

Reading Mixed Data Types


It is possible to use one scanf statement to input a data line containing mixed mode data. In such case, care should be
takento ensure that the input data items mach the control specification in order and type

The statement scanf(“%d %c %s”, &count, &ratio, name);


Will read the data
15 p coffee
and assign 15 to count p to ratio and coffee to name

Rules for scanf


 Each variable to be read must have a field specification
 For each field specification, there must be a variable address of proper type.
 Never end the format string with whitespace. It is a fatal error!
 The scanf reads until:
o A whitespace character is found in a numeric specification, or
o The maximum number of characters have been read or
o An error is detected, or’
o The end of file is reached

CSE@HKBKCE 37
18CPS13 C Programming for Problem Solving

4.4 Formatted Output- printf()


printf function can be used for printing captions and numerical results. It is highly desirable that the outputs are
produced in such a way that they are understandable and are in an easy-to-use form.

The general from of printf statement is: printf(“control string “, arg1, arg2,......argn);

Control string consists of three types of items:


1. Characters that will be printed on the screen as they appear.
2. Format specifications that define the output format for display of each item.
3. Escape sequence characters such as \n, \t, and \b.

The control string indicates how many arguments follow and what their types are. The arguments
arg1, arg2,........argn are the variables whose values are formatted and printed according to the specifications of the
control string. The arguments should match in number, order and type with the format specifications.
Examples:
printf(“Programming in C”);
printf(‘ ‘);
printf (“ \n “);
printf(“a = %f \n b = %f “, a, b);

Output Of Integer Numbers


The format specification for printing an integer number is % w d where w specifies the minimum field width for the
output. However, if a number is greater than the specified field width it will be printed in full, overriding the
minimum specification. D specifies that the value to be printed is an integer. The number is written right-justified in
the given field width. Leading blanks will appear as necessary. The following examples illustrate the output of the
number 9876 under different formats:

Example of Format Output


printf(“%d “, 9876) -> 9876
printf(“%6d “, 9876) -> 9876
printf(“%2d “, 9876) -> 9876
printf(“%-6d “, 9876) -> 9876
printf(“%06d “, 9876) -> 009876

Output of Real Numbers


The output of a real number may be displayed in decimal notation using the following specification: % w p f
The integer w indicates the minimum number of positions that are to be used for the display of the value and the
integer p indicates the number of digits to be displayed after the decimal point (precision). The value, when displayed,
is rounded to p decimal places and printed right-justified in the field of w columns.

Example:
float y = 98.7654
printf(“%7.4f\n”,y); -> 98.7654
printf(“%f\n “,y); ->98.765404
printf(“%7.2f\n” ,y); -> 98.77

Printing of a Single Character


A single character can be displayed in a desired position using the format %wc

Printing of String
The format specification for outputting strings is of the form where w specifies the field width for display and p instructs
that only the first p characters of the string are to be displayed. The display is right- justified.

CSE@HKBKCE 38
18CPS13 C Programming for Problem Solving

Example
Char str[]= “good day”;
printf(“%s”,str) -> good day
printf(“%4s”,str); -> good

Mixed Data Output


It is permitted to mix data types in one printf statement. For example, the statement of the type printf(“%d %f %s %c
“, a,b,c,d); is valid. The format specifications should match the variables in number, order, and type.

Chapter-5
DECISION MAKING AND BRANCHING

Branching statements or Decision making statements execute certain statement based on whether a particular
condition has occurred or not.

C supports the following decision making statements


1. If statement
2. Switch statement
3. Conditional operator statement
4. goto statement

Since these statements ‘control’ the flow of execution, they are also known as control statements.

1. if statement
If statement is used to control the flow of execution of statements. It is a two-way decision statements and is used in
with an expression. It takes the following form
if(test expression)
It evaluates the expression first and then depending on whether the value of the expression (relation or condition) is
‘true’(or non-zero) or ‘false’ (zero), it transfers the control to a particular statement.

Example:
1. if (bank balance is zero)
borrow money
2. if (room is dark)
put on lights

The if statement may be implement in different forms depending on the complexity of conditions to be tested. The
different forms are:
1. Simple if statement
2. If..........else statement
3. Nested if ......else statement
4. else if ladder.

1.1 Simple if Statement

General Form/Syntax
If (test expression)
{
Statement-block;
}
Statement –x;
CSE@HKBKCE 39
18CPS13 C Programming for Problem Solving

The ‘statement-block’ may be a single statement or a group of statements. If the test expression is true. The statement-
block will he executed. Otherwise the statement-block will be skipped and the execution will jump to the statement-x.

Flow chart

Example
The program reads four values a,b,c and d from the terminal and evaluates the ratio of (a+b) to (c-d) and prints the
results. If c-d is not equal to zero.
#include<stdio.h>
void main ()
{
int a, b, c,d
float ratio
printf(“Enter four integer values\n “);
scanf(“%d %d %d “ , &a, &b, &c, &d);
if (c-d !=0) / * Execute statement block */.
{
ratio = (float)(a+b)/(float)(c-d);
printf(“Ratio = %f\n”, Ratio);
}
}
Output
Enter four integer values
3342
Ratio= 3

1.2 The if.......else Statement


General form/Syntax:
if (test expression)
{
True-block statement(s)
}
else
{
false-block statement(s)
}
statement-x
if the test expression is true, then the true-block statement(s), immediately following the if statements are executed;
otherwise, the false-block statement(s) are executed. In both the cases, the control is transferred subsequently to the
statement-x

CSE@HKBKCE 40
18CPS13 C Programming for Problem Solving

Flow chart

Example
Program to find Largest of Two numbers
void main()
{
int a,b;
printf(“Enter two numbers”);
scanf(“%d%d”, &a,&b);
if (a>b)
printf(“%d is largest”, a);
else
printf(“%d is largest”, a);
}
Output:
Enter two numbers
25 70
70 is largest
1.3 Nesting of if ...else statements
When a series of decisions are involved, we may have to use more than one if........else statement in nested form
if the condition-1 is false, the statement -3 will be executed; otherwise it continues to perform the second test. If the
condition-2 is true. The statement-1 will be evaluated; otherwise the statement-2 will be evaluated and then the
control is transferred to the statement-x.

Syntax/ General Form


if (test condition – 1)
{
if (test condition – 2);
{
statement – 1;
}
else
{
statement – 2;
}
}
else
{
statement – 3;
}
statement – x;

CSE@HKBKCE 41
18CPS13 C Programming for Problem Solving

Flow chart

Example:
A program to print the largest of three numbers
void main ()
{
float a,b,c;
printf(“Enter three values \n”);
scanf(“%f %f %f”, &A, &B, &C);
printf(‘’\nLargest value is ‘’);
if (A>B)
{
If (A>C)
printf(‘’%f\n’’,A);
else
printf(‘’%f\n’’,C);
}
else
{
if(C>B)
printf(‘’%f\n’’,C);
else
printf(‘’%f\n\n’’,B);
}
}
Output
Enter three values
25 70 15
Largest value is 70
Dangling Else Problem

One of the classic problems encountered while using nested if....else statements is the dangling else. This occurs when
a matching else is not available for an if. Therefore always match an else to the most recent unmatched if in the current
block. In some cases. It is possible that the false condition is not required. In such situations, else statement may be
omitted. ‘else is always paired with the most recent unpaired if

CSE@HKBKCE 42
18CPS13 C Programming for Problem Solving

1.4. The else-if ladder

A multipath decision is a chain of ifs in which the statement associated with each else is another if. This construct is
known as the else if ladder. The conditions are evaluated from the top (of the ladder), downwards. As soon as a true
condition is found, the statement associated with it is executed and the control is transferred to the statement-x
(skipping the rest of the ladder). When all the n conditions become false, then the final else containing the default-
statement will be executed.

General Form/Syntax
if (conditional)
statement-1;
else if ( condition 2)
statement-2;
else if ( condition 3)
statement-3;
else if ( condition n)
statement –n;
else
default-statement;
statement –x

Flow chart

Example
An electric power distribution company charges its domestic consumers as follows:
Consumption units Rate of Charge
0 – 200 Rs 0.50 per unit

201 -400 Rs 100 plus Rs. 0.65 per unit excess of 200
401 – 600 Rs Rs. 230 plus Rs. 0.80 per unit excess of 400

601 and above Rs. 390 plus Rs. 1.00 per unit excess of 600

CSE@HKBKCE 43
18CPS13 C Programming for Problem Solving

Program
void main( )
{
int units, custnum;
float charges;
printf(“Enter CUSTOMER NO. and UNITS consumed\n”)
scanf(“%d %d”, &custnum, &units);
if(units <=200)
charges = 0.5 * units;
else if (units <=400)
charges = 100 + 0.65 * (units – 200)
else if (units <=600)
charges = 230 + 0.8 * (units – 400);
else
charges = 390 + (units – 600);
printf(“\n\n CUSTOMER No: %d: charges = %f\n”, custnum, charges);
}
Output
Enter CUSTOMER No.UNITS consumed
101 150
Customer No:101 Charges = 75.00

Rules of Indentation
When using control structures, a statement often controls many other statements that follow it. In such situations it
is a good practice to use indentation to show that the indented statements are dependent on the preceding
controlling statement.

Some guidelines that could be followed while using indentation are listed below:
 Indent statement that are dependent on the previous statements; provide at least three spaces of
indentation.
 Align vertically else clause with their matching if clause.
 Use braces on separate lines to identify a block of statements.
 Indent the statements in the block by at least three spaces to the right of the braces.
 Align the opening and closing braces.
 Use appropriate comments to signify the beginning and end of blocks.
 Indent the nested statements as per the above rules.
 Code only one clause or statement on each line
2. The switch Statement
when one of the many alternatives is to be selected, an if statement can be used to control the selection. However, the
complexity of such program increases dramatically when the number of alternatives increases. The program becomes
difficult to read and follow.

C has a built-in multiway decision statement known as a switch. The switch statement tests the value of a given variable
(or expression) against a list of case values and when a match is found, a block of statements associated with that case
is executed.

The general form/Syntax of the switch statement is as shown below


switch ( expression)
{
case value-1: block-1;
break;
case value-2: block-2;
break;
CSE@HKBKCE 44
18CPS13 C Programming for Problem Solving

..............
.............
default: default-block;
}
Flow chart

Example program
Example of grading the students in an academic institution. The grading is done according to the following rules
Average marks Grade
80 to 100 A
60 to 79 B
50 to 59 C
40 to 49 D
0 to 39 F
Program:
void main()
{
int marks,index, stud_id;
char grade;
printf(“Enter student id and marks”);
scanf(“%d%d”, &marks, &stud_id);
index = marks/10
switch ( index)
{
case 10:
case 9:
case 8: grade = ‘A’;
break;
case 7:
case 6: grade = ‘B’;
break;
case 5: grade = ‘C’;
break;
case 4: grade = ‘D’’;
break;
default: grade = ‘F’’
}
printf(‘’Stud id- %d\t grade= %c/n’’, stud_id,grade);
}
CSE@HKBKCE 45
18CPS13 C Programming for Problem Solving

Rules for switch statement


 The switch expression must be an integral type.
 Case labels must be constants or constant expressions.
 Case labels must be unique. No two labels can have the same value.
 Case labels must end with colon.
 The break statement transfers the control out of the switch statement.
 The break statement is optional. That is, two or more case labels may belong to the same statements.
 The default label is optional. If present, it will be executed when the ex-pression does not find matching case
label.
 There can be at most one default label.
 The default may be placed anywhere but usually placed at the end.
 It is permitted to nest switch statements.

3. The ? : Operator
This operator is useful for making two-way decisions. This operator is a combination of ? and :. It takes three
operands. This operator is popularly known as the conditional operator or ternary operator.

The general form /Syntax


Conditional_expression? expression 1 : expression 2
The conditional expression is evaluated first. If the result is non-zero(True) , expression1 is evaluated and is returned
as the value of the conditional expression. Otherwise, expression2 is evaluated and its value is returned.

Example:
The segment
if ( x <0)
flag = 0;
else
flag = 1;

can be written as

flag = (x<0) ? 0:1

4. The goto Statement

The goto statement branch unconditionally from one point to another in the program. The goto requires a label in
order to identity the place where the branch is to be made. A label is any valid variable name, and must be followed by
a colon. The label is placed immediately before the statement where the control is to be transferred.

The general forms of goto and label statements are shown below:

 The label can be anywhere in the program either before or after the goto label: statement.
 A goto breaks the normal sequential execution of the program.
CSE@HKBKCE 46
18CPS13 C Programming for Problem Solving

 If the label is before the statement goto label; a loop will be formed and some statement will be executed
repeatedly, such a jump is known as backward jump.
 On the other hand, if the label; is placed after he goto label; some statements will be skipped and the jump is
known as forward jump.
Example:
Program to find the square root of a positive number
void main ( )
{
double x,y
read: scanf(“%f”, &x);
if (x<0)
goto read;
y = sqrt(x)
print(“%f %f\n”, x, y);
}
Write a program to find the roots of a quadratic equation
#include <stdio.h>
#include <math.h>
void main()
{
inta,b,c;
float r1,r2,d,rp,ip,r;
printf("Enter three coefficients\n");
scanf("%d%d%d",&a,&b,&c);
if (a==0)
printf("Invalid Input\n");
else
{
d=b*b-4*a*c;
r=sqrt(fabs(d));
if (d>0)
{
r1=(-b+r)/(2.0*a);
r2=(-b-r)/(2.0*a);
printf("Roots are Real and Distinct\n");
printf("Root1=%f\nRoot2=%f\n",r1,r2);
}
else if (d==0)
{
r1=r2=-b/(2.0*a);
printf("Roots are Real and Equal\n");
printf("Root1=Root2=%f\n",r1);
}
else
{
rp=-b/(2.0*a);
ip=r/(2.0*a);
printf("Roots are Real and Imaginary\n");
printf("Root1=%f+i%f\nRoot2=%f-i%f\n",rp,ip,rp,ip);
}
}
getch();
}

CSE@HKBKCE 47
18CPS13 C Programming for Problem Solving

6 DECISION MAKING AND LOOPING


6.1 Introduction
Looping statements can be used to execute a sequence of statement repeatedly until some condition is satisfied. A
program loop consists of two segments, one known as the body of the loop and the other known as the control
statement. The control statement tests certain conditions and then directs the repeated execution of the statements
contained in the body of the loop.

Depending on the position of the control statement in the loop, a Loop may be classified either as the entry-controlled
loop or as the exit-controlled loop. In the case of an exit-controlled loop, the test is performed at the end of the body
of the loop and therefore the body is executed unconditionally for the first time. The entry-controlled and exit-
controlled loops are also known as pre-test and post-test loops respectively.

The loops may also be classified into two general categories:


1. Counter-controlled loops- When we know in advance exactly how many times the loop will be executed, we
use a counter-controlled loop. We use a control variable known as counter. The counter must be initialized,
tested and updated properly for the desired loop operations
2. Sentinel-controlled loops- a special value called a sentinel value is used to change the loop control
expression from true to false. For example, when reading data we may indicate the “end of data” by a
special value, like -1 and 999. The control variable is called a sentinel variable
A looping process, in general, would include the following four steps:
1. Setting and initialization of a condition variable.
2. Execution of the statements in the loop.
3. Test for a specified value of the condition variable for execution of the loop.
4. Incrementing or updating the condition variable.

The C language provides for three constructs for performing loop operations. They are:
1. The while statement.
2. The do statement.
3. The for statements

6.2 While Statement


Syntax:

while (test condition)


{
body of the loop // may have one or more statements
}

The while is an entry-controlled loop statement. The test-condition is evaluated and if the condition is true, then the
body of the loop is executed. After execution of the body, the test condition is once again evaluated and if it is true,
CSE@HKBKCE 48
18CPS13 C Programming for Problem Solving

the body is executed once again. This process of repeated execution of the body continues until the test-condition
finally becomes false and the control is transferred out of the loop. On exit, the program continues with the statement
immediately after the body of the loop.
Example Programs:
Write a program to print the first 10 natural numbers
void main()
{
int i=1;
while(i<=10)
{

Printf(“%d\t”,i);
i++;
}
}
Output: 1 2 3 4 5 6 7 8 9 10

Write a program to print the sum of first 10 natural numbers


void main()
{
int i=1,s=0;
while(i<=10)
{
s=s+i;
i++;
}
printf("Sum=%d",s);
}
Output
Sum= 55
Write A program to evaluate the equation y=xn (power function) when n is a non-negative integer

#include<stdio.h>
int main()
{
int x,y,n,i;
printf("enter the value of x and n");
scanf("%d%d",&x,&n);
i=1;
y=1;
while(i<=n)
{
y=y*x;
i++;
}
printf("x power n=%d",y);
return(0);
}

CSE@HKBKCE 49
18CPS13 C Programming for Problem Solving

6.3 The do statement


Syntax/Geeral form

do
{
body of the loop
}
while (test-condition);

On reaching the do statement, the program proceeds to evaluate the body of the loop first. At the end of the loop, the
test-condition in the while statement is evaluated. If the condition is true, the program continues to evaluate the body
of the loop once again. This process continues as long as the condition is true. When the condition becomes false, the
loop will be terminated and the control goes to the statement that appears immediately after the while statement.

Since the test-condition is evaluated at the bottom of the loop, the do…while construct provides an exit-controlled
loop and therefore the body of the loop is always executed at least once.
Example:
Write a program to read a series of character until the user presses enter key
#include<stdio.h>
int main()
{
char c;
printf("enter a series of character press enter to stop reading\n");
do
{
c=getchar();
putchar(c);
}while(c!='\n');
return(0);
}

Difference between while loop and do while loop


While loop Do-while loop

The condition is first tested and then the block of The block of code is executed at least once, even
code is executed if the test result is true though the condition given is false
Syntax: while(cond) Syntax: do
{ {
//body //body
} }while(cond);
there is no semicolon at the end of while statement there is a semicolon at the end of while statement

CSE@HKBKCE 50
18CPS13 C Programming for Problem Solving

Example Example
i=10; i=10;
while(i<10) do{
{ printf(“%d”,i);
printf(“%d”,i); } while(i<10);
} Output: 10
No Output

6.4 THE FOR STATEMENT


The for loop is another entry-controlled loop.

for ( initialization ; test-condition ; increment )


{
Body of the loop
}

The execution of the for statements as follows:


1. Initialization of the control variable is done first, using assignment statements such as I =1 and count = 0. The
variables i and count are known as loop-control variables.
2. The value of the control variable is tested using the test-condition. The test-condition is a relational expression,
such as i< 10 that determines when the loop will exit. If the condition is true, the body of the loop is executed;
otherwise the loop is terminated and the execution continues with the statement that immediately follows the
loop.
3. When the body of the loop is executed, the controls transferred back to the for statement after evaluating the
last statement in the loop. Now, the control variable is incremented using an assignment statement such as i
=i+1 and the new value of the controls variable is again tested to see whether it satisfies the loop condition. If
the condition is satisfied, body of the loop is again executed. This process continues till the value of the control
variable fails to satisfy the test-condition.

Example Programs:
Write a program to print the sum of the square of all numbers from 1 to 10

#include<stdio.h>
void main()
{
int i=1,s=0;
while(i<=10)
{

s=s+i*i;
i++;
}
printf("Sum=%d",s);
}

Output:
Sum=385

CSE@HKBKCE 51
18CPS13 C Programming for Problem Solving

Write a Program to print the factorial of a number


#include <stdio.h>
void main()
{
int n,i,f=1;
printf("Enter any number:");
scanf("%d",&n);
for(i=1;i<=n;i++)
f=f*i;
printf("the factorial of %d is %d",n,f);
}
Write a ‘C’ Program to print the first n numbers of Fibonacci series
#include <stdio.h>
void main()
{
int n,i,f1,f2,fn;
printf("Enter any number:");
scanf("%d",&n);
f1=0;
f2=1;
printf(“%d \n %d”, f1,f2)
for(i=3;i<=n;i++)
{
fn=f1+f2
printf("%d",fn);
f1=f2;
f2=fn;
}
}
Write a ‘C’ Program to print the ODD numbers from 1 to N natural numbers.
#include <stdio.h>
int main()
{
int n,i;
printf("Enter any number:");
scanf("%d",&n);
for(i=1;i<=n;i=i+2)
printf("%d",i);
return 0;
}
Write a program to print the multiplication table of a given number
#include <stdio.h>
int main()
{
int i ,n;
printf("Enter number to display table:\n");
scanf("%d",&n);

for(i=1;i<10;i++)
printf("%dX%d=%d\n",n,i,n*i);
return 0;
}

CSE@HKBKCE 52
18CPS13 C Programming for Problem Solving

Nesting of for loops


One for loop is included within another for loop
----------------------
---------------------
for ( i =1; i < 10; ++j)// outer loop
{
--------------------------
for(j=1;j<5;j++) // inner for loop
{
---------------------
---------------------
}
}
Write a program to print the multiplication table of n numbers using nested for loops
#include <stdio.h>
int main()
{
int i ,j,n;
printf("Enter number upto which to display table:\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=10;j++)
printf("%4d",i*j);
printf("\n");
}
return 0;
}
Output: Enter number upto which to display table: 10

1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
6.5 Jumps in loops

Sometimes, when executing a loop it becomes desirable to skip a part of the loop or to leave the loop as soon as a
certain conditions occur

Jumping out of a loop (break statement)


An early exit from a loop can be accomplished by using the break statement or the goto statement. When a break
statement is encountered inside a loop, the loop is immediately exited and the program continues with the
statement immediately following the loop. When the loops are nested, the break would only exit from the loop
containing it. That is, the break will exit only a single loop.

Since a goto statement can transfer the control to any place in a program. It is useful to provide branching within a
loop. Another important use of goto is to exit from deeply nested loop when an error occurs.

CSE@HKBKCE 53
18CPS13 C Programming for Problem Solving

while(……………..) do
{
………………..
…………………
if(condition)
break; //exit from the loop
…………………
…………………
}
----------------

Example:
The program reads a list of positive values and calculates their sum. The for loop is written to read 1000values.
However, if we want the program to calculate the sum, of any set of values less than 100, then we must enter a ‘
negative’ number after the last value in the list, to mark the end of input.
#include<stdio.h>
void main ( )
{
int sum,x,i;
sum=0;
for(i=1;i<=100;i++)
{
printf("enter a number");
scanf("%d",&x);
if (x<0)
break;
sum=sum+x;
}
printf("sum of %d number =%d",i-1,sum);
}
Skipping a part of a loop (continue statement)
During the loop operations, it may be necessary to skip part of the body of the loop under certain conditions. The
continue statement causes the loop to be continued with the next iteration after skipping any statements in between.
The continue statement tells the compiler, “SKIP THE FOLLOWING STATEMENTS AND CONTINUE WITH THE NEXT
ITERATION”.
The format of the continue statement is
continue;

Usage: Can be used with all looping statements


while(test condition)
{

---------------
--------------

If (condition)
Continue;
---------------
--------------
}

CSE@HKBKCE 54
18CPS13 C Programming for Problem Solving

Example
Write a program to enter 100 number. Add the positive numbers and ignore negative numbers.
#include<stdio.h>
void main ( )
{
int sum,x,i;
sum=0;
printf("enter 100 number");
for(i=1;i<=10;i++)
{
scanf("%d",&x);
if (x<0)
continue;
sum=sum+x;
}
printf("sum of psitive number =%d",sum);
}
Program that illustrates the use of break and continue
#include <stdio.h>
int main()
{
int n,i;
for(i=0;i<10;i++)
{
if(i==7)
break;
if(i==5)
continue;
printf("%d ",i);
}
}
In this above program, the loop has to repeat 10 times, but when i=7 it breaks and come out of the loop, and when
i=5, it does not print it, the next iteration continues.
Output: 0 1 2 3 4 6

Jumping out of the program


we can jump out of a program by using the library function exit ( ). In case, due to some reason, we wish to break out
of a program and return to the operating system, we can use the exit( ) function, as shown below.
………………..
…………………
if(test-condition)
exit (0);
……………..
………………
The exit ( ) function takes an integer value as its argument. Normally zero is used to indicate termination and a nonzero
value to indicate termination due to some error or abnormal condition. The use of exit( ) function requires the inclusion
of the header file <stdio.h>.

Write a ‘C’ Program to plot a Pascal’s triangle.


Formula used is Binom(m,x)=Binom(m,x-1)*(m-x+1)/x

#include <stdio.h>
int main()

CSE@HKBKCE 55
18CPS13 C Programming for Problem Solving

{
int row, m, s, x, binom;
printf("Enter number of rows:\n");
scanf("%d",&row);

for(m=0;m<row;m++)
{
for(s=1;s<=row-m ;s++)
printf(" ");
for(x=0;x<=m;x++)
{
if(m==0||x==0)
binom=1;
else
binom=binom*(m-x+1)/x;
printf("%2d",binom) ;

}
printf("\n");
}

return 0;
}
Output

Enter number of rows 5


1
11
121
1331
14641

CSE@HKBKCE 56
18CPS13 C Programming for Problem Solving

Module 3
7 ARRAYS

7.1 Introduction
The fundamental data types, namely char, int, float ,double and variations of int and double can store only one value
at any given time.

An array is a fixed size collection of elements of same data type. Each element is stored and accessed with the help of
name of the array and an index.

Different types of arrays are


 One-dimensional arrays.
 Two- dimensional arrays
 Multi dimensional arrays
7.2 One-Dimensional Arrays
In a one dimensional array a collection of elements are given one name and uses only one subscript to access it
Declaration of one dimensional array:
Syntax: data_type array_name[size];
Example:
int a[10];
It declares an array ‘a’ of type integer of size 10.

One dimensional Array initialization


Array can be initialized at
 Compile time
 Run Time

Compile time Initialization


It can be initialized during declaration as per Syntax: data_type array_name[ ]={list of values};
Example: int a[ ]={0,0,0,0};
It initializes an array ‘a’ of type integer with size 4 and initializes all elements to zero.

Run time Initialization


An array can be explicitly initialized at run time. This approach is usually applied for Initializing large arrays.
Example : Elements can be initialized with assignment operator
for(i=0;i<10;i++)
{
a[i]=0;
}
The first 10 elements of the array is initialized with zero

Example: Elements can be initializes with a read function


for(i=0;i<10;i++)
{
scanf(“%d”, &a[i]);
}
Initializes the array elements with the values entered through keyboard

CSE@HKBKCE 57
18CPS13 C Programming for Problem Solving

Searching and Sorting


Searching and sorting are the two most frequent operations performed on arrays

Sorting
Sorting is the process of arranging elements in the list according to their values, in ascending or descending order. A
sorted list is called an ordered list.

Some of the sorting technique are


 Bubble sort
 Selection sort

Develop a C program that reads N integer numbers and arrange them in ascending order using Bubble Sort
#include <stdio.h>
void main()
{
intn,i,a[10],t,j;
printf("Enter the size of an array:");
scanf("%d",&n);
printf("enter the elements os an array:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n-1;i++)
for(j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
printf("The sorted array is ...\n");
for(i=0;i<n;i++)
printf("%d",a[i]);
}
Develop a C program that reads N integer numbers and arrange them in ascending order using Selection Sort
#include <stdio.h>
int main()
{
intn,i,a[10],t,j,min,minp,k;
printf("Enter the size of an array:");
scanf("%d",&n);
printf("enter the elements os an array:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n-1;i++)
{
minp=i;
for(j=i+1;j<=n;j++)
{
if(a[j]<a[minp])
CSE@HKBKCE 58
18CPS13 C Programming for Problem Solving

{
minp=j;
}
}
//swap min with a[i]
t=a[i];
a[i]=a[minp];
a[minp]=t;
}
printf("The sorted array is ...\n");
for(i=0;i<n;i++)
printf("%d",a[i]);
}

Searching
Searching is the process of finding the location of the specified element in a list. If the process of searching finds a
match of the search key , the search said to be successful; otherwise, it is unsuccessful.
The two most commonly used search techniques are;
 Sequential search (Linear Search)
 Binary search

Write a program to search an element in a list using Linear search

#include <stdio.h>
void main()
{
intn,i,a[10], key,found=0;
printf("Enter the size of an array:");
scanf("%d",&n);
printf("enter the elements os an array:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the key:");
scanf("%d",&key);
for(i=0;i<n;i++)
{
if(key==a[i])
{ found=1;
break;
}
}
if(found==1)
printf("%d is found ",key);
else
printf("%d is not found",key);

CSE@HKBKCE 59
18CPS13 C Programming for Problem Solving

Write a program to search an element in a list using Binary search

#include <stdio.h>
void main()
{
intn,i,a[10], key,found=0,mid,low,high;
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 key:");
scanf("%d",&key);
low=0;high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(key==a[mid])
{found=1;
break;
}
else
if(key<a[mid])
high=mid-1;
else
low=mid+1;
}
if(found==1)
printf("%d is found ",key);
else
printf("%d is not found",key);
}

Write a C program to find the mean variance and standard deviation of a set of numbers

#include<stdio.h>
#include<math.h>
void main()
{
float a[10],mean,std,sum=0,sum_var=0,var;
int n,i;
printf("Enter the no of elements\n");
scanf("%d",&n);
printf("Enter the array elements\n");
for(i=0;i<n;i++)
{
scanf("%f",&a[i]);
}

for(i=0;i<n;i++)
{
sum=sum+ a[i];
}

CSE@HKBKCE 60
18CPS13 C Programming for Problem Solving

mean=sum/n;

for(i=0;i<n;i++)
{
sum_var=sum_var+ (a[i]-mean)* (a[i]-mean);
}
var=sum_var/n;
std=sqrt(var);
printf("sum=%f\n",sum);
printf("Mean=%f\n",mean);
printf("Variance=%f\n",var);
printf("standard deviation=%f\n",std);
getch();
}
7.3 Two Dimensional Arrays
Two dimensional array is an array of arrays. It is represented as a table of rows and columns. To store and access
each element in the 2D array, we need name of the array and two indices.
Syntax Declaration:data_typearray_name[size][size];
Example:inta[10][10];
‘a’ is a two dimensional array of integers of 10 rows and 10 columns.

Array can be initialized at


 Compile time
 Run Time
Compile time Initialization
It can be initialized during declaration as per Sytax: data_type array_name[ ]={list of values};
Example:
int a[ 2][3]={0,0,0,0,0,0};
It initializes an array ‘a’ of type integer with size 2X3 =6 and initializes all elements to zero
int a[2][3]= {{0,0,0},{1,1,1,})
It initializes an array ‘a’ of type integer with size 2X3 =6 and initializes all elements in first row to zero and
second row to 1

.Run time Initialization


An array can be explicitly initialized at run time. This approach is usually applied for
Initializing large arrays.

Example : Elements can be initialized with assignment operator


for(i=0;i<2;i++)
for(j=0;j<3;j++)
{
a[i][j]=0;
}
The first 6 elements of the array is initialized with zero

Example: Elements can be initializes with a read function


for(i=0;i<2;i++)
for(j=0;j<3;j++)
{
scanf(“%d”, &a[i][j]);
}
Initializes the array elements with the values entered through keyboard
CSE@HKBKCE 61
18CPS13 C Programming for Problem Solving

Develop a C program to read a matrix and print the original matrix and its transpose

#include<stdio.h>
void main()
{
int a[10][10],b[10][10];
int m,n,i,j;
printf("Enter the order of matrix\n");
scanf("%d%d",&m,&n);
printf("Enter the elements\n");
for (i=0;i<m;i++)
for (j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
b[j][i]=a[i][j];
}
printf("original Matrix\n");

for (i=0;i<m;i++)
{
for (j=0;j<n;j++)
printf("%d\t",a[i][j]);
printf("\n");
}
printf("Transpose Matrix\n");
for (i=0;i<n;i++) //No of rows and columns are interchanged in transpose matrix
{
for (j=0;j<m;j++)
printf("%d\t",b[i][j]);
printf("\n");
}

}
Develop a program to introduce 2D Array manipulation and implement Matrix multiplication and ensure the
rules of multiplication are checked.

#include<stdio.h>
void main()
{
inti,j,k,a[10][10],b[10][10],c[10][10],m,n,p,q;
printf("Enter the order of matrix A:\n");
scanf("%d%d",&m,&n);
printf("Enter the order of matrix B:\n");
scanf("%d%d",&p,&q);
if (n!=p)
printf("Matrices are Incompatible\n");
else
{
printf("Enter Matrix A\n");
for (i=0;i<m;i++)
for (j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("Enter Matrix B\n");
for (i=0;i<p;i++)
CSE@HKBKCE 62
18CPS13 C Programming for Problem Solving

for (j=0;j<q;j++)
scanf("%d",&b[i][j]);
//matrix multiplication
for (i=0;i<m;i++)
{
for (j=0;j<q;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}

printf("Matrix A:\n");
for (i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d\t",a[i][j]);
printf("\n");
}

printf("Matrix B:\n");
for (i=0;i<p;i++)
{
for(j=0;j<q;j++)
printf("%d\t",b[i][j]);
printf("\n");
}
printf("Matrix C:\n");
for (i=0;i<m;i++)
{
for(j=0;j<q;j++)
printf("%d\t",c[i][j]);
printf("\n");
}
}

CSE@HKBKCE 63
18CPS13 C Programming for Problem Solving

8 CHARACTER ARRAYS AND STRINGS


8.1 Introduction
A string is sequence of characters that is treated as single data item and terminates with a null character(‘\0’).
Terminating Null Character- Is a way to determine the end of the string data and the null character serves as the ‘
end-of-string” marker. A group of character enclosed between double quotation is a string constant.
Example: “Hello”

The common operations performed on character strings include:


 Reading and writing strings.
 Combining strings together.
 Copying one string to another
 Comparing strings for equality.
 Extracting a portion of a string.

8.2 Declaring and Initializing String Variables


Declaration
strings are represented as character arrays. The general form of declaration of string variable is:
char string_name [size];
Examples:
char city [10];
char name[30];
When the compiler assigns a character string to character array, it automatically suppliesa null character (‘\0’) at
the end of the string. Therefore, the size should be equal to themaximum number of characters in the sting plus one.

Initialization
Strings can be initialized during declaration in the following two forms
Example
char city[9] = “NEW YORK”;
char city[9] = {‘N’,’E’,’W’,’’,’Y’,’O’,’R’,’K’,’\0’};
The reason that city had to be 9 elements long is that the string NEW YORK contains 8characters and one element
space is provided for the null terminator.

C also permits us to initialize a character array without specifying the number of elements. In such cases, the size of
the array will be determined automatically, based on the number of elements initialized. For example, the statement
char string [ ] = {‘G’,’O’,’O’,’D’,’\0’};
defines the array string as a five element array.
We can also declare the size much larger than the string size in the initialize. That is, the statement.
char str [10] = ‘GOOD’;

8.3 Reading Strings from Terminal


Using scanf Function
The input function scanf() can be used with %s format specification to read in s string of characters.
Example:
char address[10]
scanf(“%s”, address);
scanf function terminates its input on the first white space it finds. A while space includes blanks, labs, carriage
returns, form feeds, and new lines. The scanf function automatically terminates the string that is read with a null
character and therefore the character array should be large enough to hold the input string plus the null character.
Note that unlike previous scanf calls, in the case of character arrays, the ampersand (&) is not required before the
variable name.

CSE@HKBKCE 64
18CPS13 C Programming for Problem Solving

We can also specify the field width using the form %ws in the scanf statement for reading a specified number of
characters from the input string.

Example:
scanf(“%ws”, name); here, two things may happen.

1. The width w is equal to or greater than the number of characters typed in. The entire string will be stored in the
string variable.
2. The width w is less than the number of characters in the string. The excess characters will be truncated and left
unread.

Consider the following statements:


Char name[10]
Scanf(“%5s”, name);

The input string RAM will be stored as


R A M \0 ? ? ? ? ? ?
0 1 2 3 4 5 6 7 8 9

The input string KRISHNA will be stored as:

K R I S H \0 ? ? ? ?
0 1 2 3 4 5 6 7 8 9

Reading a Line Text Using getchar and gets Functions

The getchar() function can be repeatedly used to read successive single characters from the input and place them into
a character array The reading is terminated when the newline character(‘\n’) is entered
and the null character is then inserted at the end of the string.

Example:
char ch;
ch = getchar();
Write a program to read a line of text containing a series of words from the terminal.
#include<stdio.h>
void main()
{
char str[25],c;
int i;
printf("enter a string\n");
i=0;
do
{
c=getchar();
str[i]=c;
i++;
} while(c!='\n');
str[i-1]='\0';

printf("the string is %s ",str);


}

CSE@HKBKCE 65
18CPS13 C Programming for Problem Solving

Another and more convenient method of reading a string of text containing whitespace isto use the library function
gets() available in the <stdio.h> header file. This is a simple functionwith one string parameter.
Syntax: gets(str);
str is a string variable .It reads characters into str from the keyboard until anew-line character is encountered and
then appends a null character to the string.

Example
char line[80];
gets (line);
printf (“%s”, line);
This code segment reads a line of text from the keyboard and displays it on the screen.

Write a program to read a string and count the number of vowels and consonants
#include<stdio.h>
#include<stdio.h>
#include<string.h>
void main ()
{
char str[30];
int vow = 0, cons = 0, i= 0;

printf("Enter a string:");
gets(str);
while (str[i] != '\0')
{
if(str[i] == 'a' || str[i] == 'A' || str[i] == 'e' || str[i] =='E' || str[i] =='i'
|| str[i] == 'I' || str[i] =='O' || str[i] == 'o' || str[i] == 'U' || str[i] =='u')
vow++;
else
cons++;
i++;
}
printf("\nNumber of Vowels = %d", vow);
printf("\nNumber of Consonants = %d",cons);

Write a program to copy one string into another and count the number of characters copied.
#include<stdio.h>
void main ( )
{
char s1[80], s2[80];
int i;
printf("Enter two string \n");
scanf("%s%s",s1,s2);
for( i = 0; s2[i] != '\0'; i++)
s1[i] = s2[i];
s1[i]='\0';
printf(" \nstring 1 is copied to string 2 string1=%s,string2=%s",s1,s2);
printf("\nNumber of characters copied=%d",i);
}

CSE@HKBKCE 66
18CPS13 C Programming for Problem Solving

8.4 Writing Strings to Screen


printf function with the format %s can be used to display an array of characters that is terminated by the null
character.
For example, the statement
printf (“%s”, name);
can be used to display the entire contents of the array name.

We can also specify the precision with which the array is displayed. For instance, the specification
%10.4 indicates that the first four characters are to be printed in a field width of 10 columns

writing strings using putchar() and puts() Functions


Function putchar() can be used to output the values of character variables. General Form:
char ch = ‘A’;
putchar (ch);
The function putchar requires one parameter.

We can use this function repeatedly to output a string of characters stored in an array using a loop.
Example:
char name[6] = “PARIS”
for (i=o, i<5 i++)
putchar (name[i];
putchar (‘\n’);

The function puts() is declared in the header file <stdio.h>. This is a one parameter function. Genral form: puts (str);
where str is a string variable containing a string value. This prints the value of the string variable
str and then moves the cursor to the beginning of the next line on the screen

Example, the program segment


char line[80];
puts (line);
reads a line of text from the keyboard and displays it on the screen

8.6 Putting Strings Together


The process of combining two strings together is called concatenation
Program to concatenate two strings.
#include <stdio.h>
void concat_str(char s1[],char s2[]);
void main()
{
char s1[50],s2[50],len,c;
printf("enter the 1st string\n");
scanf("%s",s1);
printf("enter the 2nd string\n");
scanf("%s",s2);
concat_str(s1,s2);
printf("concatination of string1 and string2 %s \n",s1);
}
void concat_str(char s1[],char s2[])
{
int i=0,j=0;
while(s1[i]!= '\0')
i++;
CSE@HKBKCE 67
18CPS13 C Programming for Problem Solving

while(s2[j]!='\0')
{
s1[i]=s2[j];
j++;
i++;
}
s1[i]='\0';
}

8.7 Comparison of Two Strings


To compare the two strings it is necessary to be test, character by character. The comparison is done until there is a
mismatch or one of the strings terminates into a null character, whichever occurs first.

Write a program to compare two strings without using building function


#include <stdio.h>
int strcompare(char s1[],char s2[]);

void main()
{
char s1[50],s2[50],len,c,flag;

printf("enter the 1st string\n");


scanf("%s",s1);
printf("enter the 2nd string\n");
scanf("%s",s2);
flag=strcompare(s1,s2);
if(flag==1)
printf("strings are equal");
else

printf("strings are not equal");


getch();
}

int strcompare(char s1[],char s2[])


{
int i=0,j=0;
while(s1[i] != '\0' && s2[i] !='\0' && s1[i]==s2[i])
{
i++;
}
if (s1[i] == '\0' && s2[i] =='\0')
return(1) ;
else
return(0);

CSE@HKBKCE 68
18CPS13 C Programming for Problem Solving

8.8 String-Handling Functions


The C library supports large number of string-handling functions that can be used to carry out many of the string
manipulations discussed so far. Following are the most
commonly used string-handling functions.

strcat() concatenates two strings


strcmp() compares two strings
strcpy() copies one string over another
strlen() finds the length of a string
strcat ( ) function
The strcat function joins two strings together. It takes the following form:
Syntax: strcat(string1, string2)
string1 and string2 are character arrays, when the function strcat is executed, string2 is appended to string1. It does so
by removing the null character at the end of string1 and placing string2 from there. The string at string2 remains
unchanged.
Example
char str1[]={“hello”};
char str2[]={“world”);
strcat(str1,str2);
str1 contains helloworld
Str2 remains unchanged with word world
strcmp( ) function
The strcmp function compares two strings identified by the arguments and has a value 0 if they are equal. If they are
not, it has the numeric difference between the first no matching characters in the strings. It

General Form/syntax: strcmp(string1,string2);


string1 and string2 may be string variables or string constants. Examples are:
strcmp(name1, name2);
strcmp(name1, “John”);
strcmp(“Rom”, “Ram”);
return 0 since the two strings are not equal

strcpy( ) function
The strcpy function works almost like a string-assignment operator. General form/syntax : strcpy(string1,string2)
Assigns the contents of string2 to string1. String2 may be a character array variable or a string constant.
Example
strcpy(city, “DELHI”);
will assign the string “DELHI” to the string variable city.
Similarly, the statement
strcpy(city1, city2)
will assign the contents of the strings variable city2 to the string variable city1. The size of the array city1 should be
large enough to receive the contents of city2.
char str1[]={“hello”};
char str2[]={“world”);
strcpy(str1,str2);
str1 contains world
Str2 remains unchanged with word world

srtlen( ) function
This function counts and returns the number of characters in a string. General form/ syntax n = strlen(string)
where n is an integer variable, which receives the value of the length of the string. The argument may be a string
constant. The counting ends at the first null character.
char str1={“hello”};

CSE@HKBKCE 69
18CPS13 C Programming for Problem Solving

strlen(str1); returns the value 5


Module-4
USER DEFINED FUNCTIONS
4.1 Functions

A function is a group of statements that together perform a particular task. Every C program has at least one
function, which is main (), and all the programs can define additional functions.

A function declaration or prototype tells the compiler about a function's name, return type, and parameters. A
function definition provides the actual body of the function.

C functions can be classified into two categories


 Library functions - library functions are not required to be written by user. printf and scanf belong to the
category of library functions.
 User-defined functions- user-defined function has to be developed by the user at the time of writing a
program. Main() is an example of user- defined functions. . However, a user-defined function can later
become a part of the C program library. This is one of the strengths of C language.

Uses of C functions:
 It facilitates top-down modular programming as shown in Fig 1. In this programming style the high level logic
of the overall problem is solved first while the details of each lower-level function are addressed later.
 Reusability: C functions are used to avoid rewriting same logic/code again and again in a program.
 The length of a source program can be reduced by using functions at appropriate places
 It is easy to locate and isolate a faulty function for further investigations
 A function may be used by many other programs
 There is no limit in calling C functions to make use of same functionality wherever required.
 Improve understand ability of very large C programs

Fig 1: Top down modular programming using functions

4.2 Modular programming


Modular programming is defined as organizing a large program into small, independent program segments called
modules that are separately named and individually called program units. These modules are carefully integrated to
become a software system that satisfies the system requirements.

CSE@HKBKCE 70
18CPS13 C Programming for Problem Solving

In C, each module refers to a function that is responsible for a single task.Some characteristics of modular programming
are:

1. Each module should do only one thing.


2. Communication between modules is allowed only by a calling module.
3. a module can be called by one and only one higher module.
4. No communication can take place directly between modules that do not have calling called relationship.
5. All modules are designed as single-entry, single-exit systems using control structures.

4.3 Elements Of User-Defined Function


In order to make use of a user-defined function, we need to establish three elements that are
related to functions.
1. Function definition
2. Function call.
3. Function declaration.

 The function definition is written to implement the task of the function.


 In order to use this function we need to invoke it at a required place in the program. This is known as the
function call.
 The program (or a function) that calls the function is referred to as the calling program or calling function.
 The calling program should declare any function (like declaration of a variable) that is to be used later in the
program. This is known as the function declaration or function prototypes.

4.3.1 Function Definition


Function definition, also known as function implementation shall include the following elements:
1. function name;
2. function type;
3. list of parameters;
4. local variable declarations;
5. function statements; and
6. a return statement.

All the six elements are grouped into two parts, namely
 Function header (first three elements); and
 Function body (second three elements).

General Format / Syntax of function Definition


function_type function_name(parameter list)
{
local variable declaration;
executable statement1;
executable statement2;
…………………………….
……………………………
return statement;
}

Function header :The function header consists of three parts:


 The function type (also known as return type)
 The function name and
 Formal parameter list.
Note : that a semicolon is not used at the end of the function header.

CSE@HKBKCE 71
18CPS13 C Programming for Problem Solving

The function type specifies the type of value (like float or double) that the function is expected to return to the program
calling the function. If the return type is not explicitly specified, C will assume that it is an integer type. If the function
is not returning anything, then we need to specify the return type as void.
The function name is any valid C identifier and therefore must follow the same rules of formation as other variable
names in C.
Formal parameter list : The parameter list declares the variables that will receive the data sent by the calling
program. They serve as input data to the function to carry out the specified task. Since they represent actual
input values, they are often referred to as formal parameter. These parameters can also be used to send values
to the calling programs. The parameters are also known as arguments. The parameter list contains declaration
of variables separated by commas and surrounded
by parentheses.
Examples: float quadratic(int a, int b, int c){………}

To indicate that the parameter list is empty, we use the keyword void between the parentheses as in
void printline(void)

Function body
The function body contains the declarations and statements necessary for performing the required task. The body
enclosed in braces, contains three parts, in the order given below:

1. Local declarations that specify the variables needed by the function.


2. Function statements that perform the task of the function.
3. A return statement that return the value evaluated by the function.

a function does not return any value (like the printline function), we can omit the return
statement. However, note that its return type should be specified as void.

4.3.2 Function Call


Function can be called by simply using the function name followed by a list of actual parameters (or arguments), if
any, enclosed in parentheses.

Example
main( )
{
int y;
y = mul(10,5); /*function call*/
printf(“%d\n”, y);
}

int mul(int s, int y)


{
return(x*y)
}
When the compiler encounters a function call, the control is transferred to the function mul(). This function is then
executed line by line as described and a value is returned when a return statement is encountered. This value is assigned
to y.

4.3.3 Function Declaration


Like variables, all functions in a C program must be declared, before they are invoked. A function declaration (also
known as function prototype) consists of four parts.

CSE@HKBKCE 72
18CPS13 C Programming for Problem Solving

 Function type(return type)


 Function name.
 Parameter list.
 Terminating semicolon.

General format/ syntax : Function-type function-name(parameter list);

This is very similar to the function header line except the terminating semicolon.
For example, mul function defined in the previous section will be declared as:

int mul(int x, int y); /* Function prototype*/

Example: C program to find the sum of two numbers

#include <stdio.h>
int sum(int, int); // function declaration
void main()
{
int a, b, c;
printf(“Enter a and b\n”);
scanf(“%d%d”, &a, &b);
c=sum(a,b); // function call
printf(“Sum=%d\n”,c);
}
int sum(int x, int y) // function definition
{
int z;
z=x+y;
return z;
}

4.4 Category of Functions


A function, depending on whether arguments are present or not and whether a value is returned or not, may belong
to one of the following categories:

Category 1: functions with no arguments and no return values.


Category 2: functions with arguments and no return value.
Category 3: functions with arguments and one return value.
Category 4: functions with no arguments and but a return value.
Category 5: functions that return multiple values.

4.4.1 Functions with No Arguments and No Return Values

When a function has no arguments, it does not receive any data from the calling function. Similarly, when it does not
return a value, the calling function does not receive any data from the called function

Void sum(); // function declaration

void main()
{
sum( ); // function call
}
CSE@HKBKCE 73
18CPS13 C Programming for Problem Solving

void sum( ) // function definition


{
int x, y, z;
printf(“Enter x and y\n”);
scanf(“%d%d”, &x, &y);
z=x+y;
printf(“Sum=%d\n”,z);
}

4.4.2 Functions with Arguments but No Return Values

The function value receives data from the calling function through arguments, but does not send back any value.
Rather, it displays the results of calculations at the terminal.

void sum(a,b); // function declaration

void main()
{
int a, b, c;
printf(“Enter a and b\n”);
scanf(“%d%d”, &a, &b);
sum(a,b); // function call
}
void sum(int x, int y) // function definition
{
int z;
z=x+y;
printf(“Sum=%d\n”,z);
}

4.4.3. Functions with Arguments with Return Values

The function value receives data from the calling function through arguments, and sends back the result to the calling
function.
int sum(int x, int y);
void main()
{
int a, b, c;
printf(“Enter a and b\n”);
scanf(“%d%d”, &a, &b);
c=sum(a,b); // function call
printf(“Sum=%d\n”,c);
}

int sum(int x, int y) // function definition


{
int z;
z=x+y;
return z;
}

CSE@HKBKCE 74
18CPS13 C Programming for Problem Solving

4.4.4 Functions with No Arguments but Returns a Value


The function does not receive data from the calling function through arguments, but it sends back the result to the
calling function.

int sum(Void) // function definition


void main()
{
int c;
c=sum( ); // function call
printf(“Sum=%d\n”,c);
}
int sum( ) // function definition
{
int x, y, z;
printf(“Enter x and y\n”);
scanf(“%d%d”, &x, &y);
z=x+y;
return z;
}
4.4.5 Functions that return multiple values
A return statement can return only one value. Suppose, we want to get more information from a function. We can
achieve this in C using arguments not only to receive information but also to send back information to the calling
function. The arguments that are used to “send out” information are output parameters. The mechanism of sending
back information through arguments is achieved using what are known as the address operator (&) and indirection
operator (*).

void mathoperation(int x, int y, int *s,int *d); /

void main()
{
int x = 20, y = 10, s, d;
mathoperation(x,y, &s, &d);
printf(“sum=%d\n”, s);
printf(“Difference=%d\n”, s);
}

void mathoperation (int a, int b, int *sum, int *diff);


{
*sum = a+b;
*diff = a-b;
}

The actual arguments x and y are input arguments, s and d are output arguments.

Example Programs

Write a Program to print the fibonocci series using function


#include<stdio.h>

void fibo(int n)
{
CSE@HKBKCE 75
18CPS13 C Programming for Problem Solving

int f1,f2,fn,i;
f1=0;
f2=1;
if(n==1)
{
printf("0") ;
}
else if(n==2)
printf("0 \t 1");
else
{
printf("0 \t 1");

for(i=3;i<=n;i++)
{
fn=f1+f2;
printf("\t%d",fn);
f1=f2;
f2=fn;

}
}
}

{ void main()

int n,res;
printf("enter n : ");
scanf("%d",&n);
if (n<=0)
{
printf("invalid input");
exit(0);
}
else
fibo(n);
}

4.5 Nesting of functions


C PERMITS NESTING OF functions freely. main can call funcion1, which calls function2,which calls function3,
............and so one. There is in principle no limit as to how deeply functions can be nested.

Example for Nested functions:

The program calculates the ratio a/b-c and prints the result

float ratio (int x, int y, int z);

int difference (int x, int y);

void main( )

CSE@HKBKCE 76
18CPS13 C Programming for Problem Solving

{
int a,b,c;
float r;
printf(“enter 3 numbers\n”);
scanf(“%d%d%d”, &a,&b, &c);
r=ratio(a,b,c)
printf(“%f \n”, r);
}

float ratio (int x, int y, int z)


{
int d;
d=difference(y,z);
if(d!=0)
return(x/(float)d));
else
return(0.0);
}

int difference(int p, int q)


{
if(p != q)
return(p-q);
else
return(0);
}

4.6 Recursion
Recursion is a process, where a function calls itself.

Example:

Fact(4)= 4* fact(3)

=4*3*fact(2)

=4*3*2*fact(1);

=4*3*2*1=24

A C program to find factorial of a given number using recursion

int factorial (int n) ;

void main()
{
int n,f;
printf(“Enter n:\n”);
scanf(“%d”,&n);
f=factorial(n);
printf(“Factorial=%d\n”,f);
CSE@HKBKCE 77
18CPS13 C Programming for Problem Solving

int factorial (int n)


{
if (n==0||n==1)
return 1;
return n*factorial(n-1);
}

Sample Input/Output:
Enter n:
4
Factorial=24

A C Program to print nth Fibonacci number using recursion

#include<stdio.h>
int fibo(int n)
{
if (n==1)
return(0);

if (n==2)
return(1);

return(fibo(n-1)+fibo(n-2));

void main()
{
int n,res;
printf("enter n : ");
scanf("%d",&n);
if (n<0)
{
printf("invalid input");
exit(0);
}

res=fibo(n);
printf("%dth fibonocci number=%d",n,res);

Sample Output:
Enter n: 5

CSE@HKBKCE 78
18CPS13 C Programming for Problem Solving

5th fibonocci number=5

4.7 Passing Arrays to Functions

4.7.1 One-Dimensional Arrays


Like the values of simple variables, it is also possible to pass the values of an array to a function. To pass a one-
dimensional an array to a called function, it is sufficient to list the name to the array, without any subscripts, and the
size of the array as arguments.

The rules are

1. The function must be called by passing only the array name.


2. In the function definition, we must indicate that the array has one-dimensions by including one set of
brackets.
3. The size of the dimension need not have to be specified.
4. The prototype declaration should be similar to the function headers

Example : largest(a,n)

This will pass the whole array a to the called function. The called function expecting this call must be appropriately
defined. The largest function header might look like:

int largest(int a[], int size)

Example:
Program to find the largest element in the array using functions

#include <stdio.h>
void read(int a[10],int n)
{
int i;
printf("Enter elements\n");
for (i=0;i<n;i++)
scanf("%d",&a[i]);
}

int largest(int a[],int n)


{
int lar,i;
lar=a[0];
for (i=1;i<n;i++)
if (a[i]>lar)
lar=a[i];
return(lar);
}

void main()
{
int n,i,a[10],l;
printf("Enter the number of elements\n");

CSE@HKBKCE 79
18CPS13 C Programming for Problem Solving

scanf("%d",&n);
read(a,n);
l=largest(a,n);
printf("largest=%d",l);
}

Program to sort the elements of the array using function


#include <stdio.h>
void read(int a[10],int n)
{
int i;
printf("Enter elements\n");
for (i=0;i<n;i++)
scanf("%d",&a[i]);
}
void sort(int a[],int n)
{
int i,j,t;
for (i=0;i<n;i++)
for (j=0;j<n-i;j++)
if (a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
void display(int a[10],int n)
{
int i;
printf("Sorted Array\n");
for (i=0;i<n;i++)
printf("%d\n",a[i]);
}
main()
{
int n,i,a[10];
printf("Enter the number of elements\n");
scanf("%d",&n);
read(a,n);
sort(a,n);
display(a,n);
}
Sample Input/Output:
Enter the number of elements
5
Enter elements
5
4
3
2
CSE@HKBKCE 80
18CPS13 C Programming for Problem Solving

1
Sorted Array
1
2
3
4
5

Program to find the standard deviation and mean of the array using functions
#include<math.h>

float std_dev(float a[], int n);


float mean(float a[], int n);

void main()
{
float value[10], sd;
int i,n;
printf("enter totoal elements: ");
scanf("%d", &n);
printf("enter elements\n");
for(i=0; i < n; i++)
scanf("%f", &value[i]);
sd= std_dev(value, n);
printf("std.deviation is %f\n",sd );
}

float std_dev(float a[], int n)


{
int i;
float x, sum = 0.0;
x = mean(a,n);
printf("Mean=%f",x);
for(i=0; i < n; i++)
sum = sum+(x-a[i])* (x-a[i]);
return(sqrt(sum/(float)n));
}
float mean(float a[], int n)
{
int i;
float sum = 0.0;
for(i=0; i<n; i++)
sum = sum + a[i];
return(sum/(float)n);
}

4.7.2 Two dimensional arrays


Like simple array, we can also pass multi-dimensional arrays to functions.

The rules are

CSE@HKBKCE 81
18CPS13 C Programming for Problem Solving

5. The function must be called by passing only the array name.


6. In the function definition, we must indicate that the array has two-dimensions by including two sets of
brackets.
7. The size of the second dimension must be specified.
8. The prototype declaration should be similar to the function headers.

Example:
Write a program to read a matrix(mXn) and find the sum of all the elements of the matrix
#include<stdio.h>
void allsum(int a[][10],int m,int n);

void main()
{
int a[10][10];
int m,n,i,j;
printf("Enter the order of matrix\n");
scanf("%d%d",&m,&n);
printf("Enter the elements\n");
for (i=0;i<m;i++)
for (j=0;j<n;j++)
scanf("%d",&a[i][j]);
allsum(a,m,n);
}

void allsum(int a[][10],int m,int n)


{
int i,j,sum=0;
for (i=0;i<m;i++)
for (j=0;j<n;j++)
sum=sum+a[i][j];
printf("\nSum of all elements=%d\n",sum);
}

4.8 Passing Strings to Functions


The strings are treated as character arrays in C and therefore the rules for passing strings to functions are very similar
to those for passing arrays to functions

Basic rules are:


1. The string to be passed must be declared as a formal argument of the function when it is
defined.
Example:
void display(char item_name[])
{
..................
}
2. The function prototype must show that the argument is a string.
Example: For the above function definition, the prototype can be written as
void disiplay(char str[ ]);
3. A call to the function must have a string array name without subscripts as its actual argument. Example
display(name);
where names is a properly declared string array in the calling function.
CSE@HKBKCE 82
18CPS13 C Programming for Problem Solving

Example;
Write a program to concatenate two strings using function

#include <stdio.h>
voidconcat_str(char s1[],char s2[]);

void main()
{
char s1[50],s2[50],len,c;
clrscr();
printf("enter the 1st string\n");
scanf("%s",s1);
printf("enter the 2nd string\n");
scanf("%s",s2);
concat_str(s1,s2);
printf("concatination of string1 and string2 %s \n",s1);
getch();
}

voidconcat_str(char s1[],char s2[])


{
int i=0,j=0;

while(s1[i]!=’\0’)
i++;

while(s2[j]!='\0')
{
s1[i]=s2[j];
j++;
i++;
}
s1[i]='\0';
}

4.9 Parameter Passing Techniques


The technique used to pass data from one function to another is known as parameter passing. Parameter passing can
be done in two ways.
 Pass by value (also known as call by value).
 Pass by pointers/Reference(also known as pointers)

In pass by value, values of actual parameters are copied to the variable in the parameter list of the called function. The
called function works on the copy and not on the original values of the actual parameters. This ensures that the original
data in the calling function cannot be changed accidentally.

Example program (using call by value):


#include<stdio.h>
void swap(int a, int b);
main()
{
CSE@HKBKCE 83
18CPS13 C Programming for Problem Solving

int m = 22, n = 44;


// calling swap function by value
printf(" values before swap m = %d \nand n = %d",m,n);
swap(m, n);
}
void swap(int a, int b)
{
int tmp;
tmp = a;
a = b;
b = tmp;
printf(" \nvalues after swap m = %d\n and n = %d",a,b);
}
Output:
values before swap m = 22 and n = 44
values after swap m = 44 and n = 22

In pass by pointers (also known as pass by Referenceor address), the memory addresses of the variables
rather than the copies of values are sent to the called function. In this case, the called function directly works on the
data in the calling function and changed values are available in the calling function for its use.
Pass by pointers method is often used when manipulating arrays and strings. This method is also used when we require
multiple values to be returned by the calling function.

#include<stdio.h>
void swap(int *a, int *b);
main()
{
int m = 22, n = 44;
// calling swap function by reference
printf("values before swap m = %d \n and n = %d",m,n);
swap(&m, &n);
printf("\n values after swap m = %d \n and n=%d",m, n);

}
void swap(int *a, int *b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
Output:
values before swap m = 22 and n = 44 values
after swap m = 44 and n = 22

CSE@HKBKCE 84
18CPS13 C Programming for Problem Solving

The scope, visibility and lifetime of variables


In C all variables have data typeand have a storage class. The following variable storage classes are most relevant to
functions:
1. Automatic variables.
2. External variables.
3. Static variables.
4. Register variables.

The scope of variable determines the region of the program where a variable is available for use (‘active’).
Longevity refers to the period for which the variable retains a given value during execution of a program (‘alive’).

The visibility refers to the accessibility of a variable from the memory.

Automatic variables
Automatic variables are declared inside a function in which they are to be utilized. They are created when the function
is called and destroyed automatically when the function is exited, hence the name automatic.

Automatic variables are therefore private (or local)to the function in which they are declared. Because of this property,
automatic variables are also referred to as local or internal variables. A variable declared inside a function without
storage class specification is, by default, an automatic variable.

Example:
void function1(void);
void function2(void);
main( )
{
int m =1000;
function1();
printf(“%d\n”, m);
}

void function1(void)
{
int m= 10;
printf(“%d\n”, m);
}
Output
10
1000

External variables
Variable that are both alive and active throughout the entire program are known as external variables. They are also
known as global variables. Unlike local variables, global variables can be accessed by any function in the program.
External variables are declared outside a function.

Example:
int fun1(void);
int fun2(void);

int x; /* global */
main()
{

CSE@HKBKCE 85
18CPS13 C Programming for Problem Solving

x = 10; /* global x*/


printf(“x= %d\n” ,x);
fim1();
}

fun1(void)
{
x = x + 10;
printf(“x= %d\n” ,x);
}

Output
x = 10
x = 20

External Declaration
In a program segment if a variable has been declared after the main function. The main function can access the variable,
if the variable is declared with the storage class extern.

void main()
{
extern int u;
u=10;
printf("%d",u);
func1();
}
void func1(void)
{
extern int u;
printf("%d",u);
}
int u;

Output
10 10
Static variables
The value of static variables persists until the end of the program. A variable can be declared static using the keyword
static.

static int x;
static float y;

void stat(void);
main()
{
int i;
for(i=1; i<=3; i++)
stat();
}
void stat(void)
{
static int x = 0;
x = x+1;

CSE@HKBKCE 86
18CPS13 C Programming for Problem Solving

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


}
Output
x=1
x=2
x=3
A static variable is initialized only once, when the program is compiled. It is never initialized again.

Register variables
We can tell the compiler that a variable should be kept in one of the machine’s registers, instead of keeping in the
memory(where normal variables are stored). Since a register access is much faster than a memory access, keeping the
frequently accessed variables (e.g., loop control variables) in the register will lead to faster execution of programs. This
is done as follows:

register int count;


Since only a few variables can be placed in the register, it is important to carefully select the variables for this purpose.
However, C will automatically convert register variables into non register
variables once the limit is reached.

CSE@HKBKCE 87
18CPS13 C Programming for Problem Solving

MODULE - 5
STRUCTURES
1. Introduction
C supports a constructed data type or user defined data type known as structures, which is a mechanism
for packing data of different types. A structure groups logically related data items.

For example, it can be used to represent a set of attributes, such as student name, roll_number and marks.
More examples of such structures are:
time : seconds, minutes, hours
date : day, month, year
address : name, door-number, street, city

2. Defining a Structure

Structures must be first defined for their format, so that it may be used later to declare structure
variables.

The general format of a structure Definition is as follows:

struct tag_name
{
data_type member1;
data_type member2;
------------------------------
------------------------------
Data type member n;
};

In defining a structure use the following syntax


1. The template is terminated with a semicolon
2. While the entire definition is considered as a statement, each member is declared independently for its
name and type in a separate statement inside the template
3. The tag name can be used to declare structure variables of its type, later in the program.

Example :

Consider a book database consisting of book name, author , number of pages, and price.

Structure definition to hold this information as follows:

struct book _bank


{
char title[20]:
char author [15]
int pages;
float price;
};

The keyword struct declares a structure to hold the details of four data fields , namely title, author , pages, and
price. These fields are called structure elements or members.
Each member may belong to a different type of data. book_bank is the name of the structure and is called the
CSE@HKBKCE 88
18CPS13 C Programming for Problem Solving

structure tag. The tag name may be used subsequently to declare variables that have the tag‘s structure.

Arrays Vs Structures

Arrays Structures
An array is a collection of related data elements of Structure can have elements of different types.
same type
An array is derived data type Structure is a user defined data type
Any array behaves like a built-in data type. declare But in the case of a structure, first we have to
an array variable and use it design and declare a data structure before the
variables of that type are declared and used.

3. Declaring Structure Variables

After defining a structure format ,declare variables of that type. A structure variable declaration includes the
following elements:

1. The keyword struct.


2. The structure tag name.
3. List of variable names separated by commas.
4. A terminating semicolon.

Syntax: Struct tag name var_nme;

Example:

structbook_bank

{
char title[20];
char author [15];
int pages;
float price;
};

struct book bank bookl, book2, book3;

Declares bookl, book2, and book3 as variables of type struc tbook_bank Each one of these variables has four
members as specified by the template.

Members of a structure themselves are not variables. They do not occupy any memory until they are associated
with the structure variables such as bookl. When the compiler comes across a declaration statement, it reserves
memory space for the structure variables.

It is also allowed to combine both the structure definition and variables declaration in one statement.

The declaration

struct book bank

CSE@HKBKCE 89
18CPS13 C Programming for Problem Solving

{
char title[20];
char author [15];
int pages;
float price;

}bookl, book2, book3;


is valid.

Type Defined Structures

Use the keyword typedef to define a structure as follows:


typedef struct

{
data_type memberl;
data_type member2;
---------------------------
--------------------------
} type_name;

The type_name represents structure definition associated with it and therefore can be used to
declare structure variables as shown below:

type_name variablel,va1iable2, ...... ;

 The name type_name is the type definition name, not a variable


 We cannot define a variable with typedef declaration.

4. Accessing Structure Members

To access and assign values to the members of a structure the members should be linked to the structure
variables in order to make them meaningful members.

The link between a member and a variable is established using the member operator ’.’ which is also known
as 'dot operator‘ or' period operator‘.

For example : bookl.price

is the variable representing the price of bookl and can be treated like any other ordinaryvariable.

Values can be assigned to the members of bookl as follows

strcpy (book1.title, "BASIC");


strcpy (book.author, "Balagurusamy"):
book1.pages =250;
book1.price =120.50;

CSE@HKBKCE 90
18CPS13 C Programming for Problem Solving

Use scanf to give the values through the keyboard.


scanf("%s", book1.title);
scanf("%d", &book1.pages);

are valid input statements.

Example : Write a program to declare a structure to read the name and salary of a person and print it.

struct personal

{
char name[20];
float salary;
};

void main()
{
struct personal p1;
printf(" enter the name and salary Values\n");
scanf(”%s %f ",p1.name, &p1..salary);
printf(”%s %f \n", p1.name,p1..salary);
}
Output
Input Values
M.L.Goel 4500
M.L.Goel 4500.00

5. Structure Initialization

C language does not permit the initialization of individual structure members within the template. The
initialization must be done only in the declaration of the actual variables.

Compile-time initialization of a structure variable must have the following elements:

1. The keyword struct.


2. The structure tag name
3. The name of the variable to be declared.
4. The assignment operator =.
5. A set of values for the members of the structure variable, separated by commas and enclosed
6. in braces
7. A terminating semicolon.

Rules for Initializing Structures

1. We cannot initialize individual members inside the structure template.


2. The order of values enclosed in braces must match the order of members in the structure definition.
3. It is permitted to have a partial initialization. We can initialize only the first few members and The
uninitialized members will be assigned default values as follows:
a. Zero for integer and floating point numbers.
b. ‘\0’ for characters and strings
CSE@HKBKCE 91
18CPS13 C Programming for Problem Solving

Example:

struct stud
{
Char name[25];
int weight;
float height;
};
struct stud s1 = {“Alex”,60, 180.75};

struct stud s2 = {“Bob”,53, 170.60};

Run time Initialization:


At run time the structure variables can be initialized using the input function

Example:
Scanf(“%s%d%f”,s1.name,&s1.weight, &s1.height)

It can also be initialized as follows


strcpy(s1.name,”alex”);
s1.weight=60;
s1.height=180.75;

5. Copying and Comparing Structure Variables

Two variables of the same structure type can be copied the same way as ordinary variables. If personl and
person2 belong to the same structure, then the following statements are valid

person1 = person2;
person2 = person1;

However, the following statements are not permitted


person1== person2
person1!=person2

- C does not permit any logical operations on structure variables.


- compare them, by comparing members individually.

A program to illustrate copying and comparing structure variables


struct class
{
int number;
char name[20];
float marks;
};

main()
{
CSE@HKBKCE 92
18CPS13 C Programming for Problem Solving

int x;
struct class student1 = {111,"Rao",72.50};
struct class student2 = {222,"Reddy", 67.00};
struct class student3;
student3 = student2;

x = ((student3.number == student2.number) &&(student3.marks == student2.marks)) ? 1 : 0;

if(x ==1)
{
printf(”\nstudent2 and student3 are same\n\n”);
printf(”%d %s %f\n”, student3.number,student3 .name,student3 .marks);
}
else
printf(”\nstudent2 and student3 are different\n\n");
}

Output
student2 and student3 are same

222 Reddy 67.000000

6. Different Ways of Accessing Structure Members

Along with dot(.) operator there are two other way of accessing the members of the structure variables

Example
Typedef struct
{
int x;
int y;
} VECTOR;

VECTOR v, * ptr;
ptr = & v;

The identifier ptr is known as pointer that has been assigned the address of the structure variable ‘v’
Now, the members can be accessed in three ways:

 using dot notation : v.x


 using indirection notation : (*ptr).x
 using selection notation : ptr->x

7. Arrays of Structures
An array of structures can be used to define a collection of structure variables. Each element of the array represents a
structure variable.

CSE@HKBKCE 93
18CPS13 C Programming for Problem Solving

Example 1:
In analyzing the marks obtained by a class of students, we may use a template to describe student name and
marks and then declare all the students as structure variables.

Consider the following declaration

struct class

{
Char name[25];
Char usn[11];
Int marks;
};

struct class student [100];

Defines an array called student, that consists of 100 elements, Each element is defined to be of the type struct
class.

Example 2:

struct marks
{
int subject1;
int subject2;
int subject3;
};

main()
{
struct marks student [3] ={{45,68,81},{75,53,69},{57,36,71}};
This declares the student as an array of three elements student[0], student[1], and student[2] and
initializes their members as follows:

Student[0].subject1 45
Student[0].subject2 68
Student[0].subject3 81
Student[1].subject1 75
Student[1].subject2 53
Student[1].subject3 69
Student[2].subject1 57
Student[2].subject2 36
Student[2].subject3 71

The array student inside memory

Implement structures to read the student details, write and compute average marks and students scoring above and
below the average marks for a class of N students.

#include<stdio.h>
CSE@HKBKCE 94
18CPS13 C Programming for Problem Solving

void main()
{
struct stud
{
char name[25];
char usn[25];
int marks;
};
struct stud s[25];
int n,i,sum;
float average;
sum=0;
printf("enter number of students\n");
scanf("%d",&n);
printf("enter the name usn and marks of %d students",n);
for(i=0;i<n;i++)
{
scanf("%s%s%d",s[i].name,s[i].usn,&s[i].marks);
sum=sum+s[i].marks;
}
average=sum/(float)n;
printf("average marks=%f",average);
printf(" Details of students scoring above average marks\n");
for(i=0;i<n;i++)
if (s[i].marks >= average)
printf("name=%s \t usn=%s \t marks= %d\n",s[i].name,s[i].usn,s[i].marks);

printf(" Details of students scoring below average marks\n");


for(i=0;i<n;i++)
if (s[i].marks < average)
printf("name=%s \t usn=%s \t marks= %d\n",s[i].name,s[i].usn,s[i].marks);
}

Input:
enter number of students :3
enter the name usn and marks of 3 students
abc 1 25
xyz 2 28
pqr 3 30
Output:
average marks=27.666666
Details of students scoring above average marks
name=xyz usn=2 marks= 28
name=pqr usn=3 marks= 30

Details of students scoring below average marks


name=abc usn=1 marks= 25

8. Arrays within Structures

Cpermits the use of arrays as structure members .we can use single or multi dimensional arrays as structure
members.

CSE@HKBKCE 95
18CPS13 C Programming for Problem Solving

Example
struct student
{ int stud_id;
float subject[3];
};

struct stud s;

variable s contains 2 members stud_id an integer and member subject has 3 elements , subject[0], subject[1],
subject[2].

These elements can be accessed using appropriate subscripts


s.subject[2]; refers to the marks obtained by the student in subject 3

Write a Program to read the detail of one student and compute the total marks obtained by the student
and print the total marks
#include <stdio.h>
struct student
{ int stud_id;
float subject[3];
};
void main()
{
struct student s;
int i;
float total;
printf("enter the student id");
scanf("%d", &s.stud_id);
total=0.0;
printf("Enter 3 subject marks\n");
for(i=0;i<3;i++)
{
scanf("%f",&s.subject[i]);
total= total+s.subject[i];
}
printf("Studen with id :%d scored a total mark of %f", s.stud_id, total);
}
Input:
Enter student id: 1
Enter 3 subject marks: 20 25 30
Output:
Student with id:1 scored a total mark of 75

CSE@HKBKCE 96
18CPS13 C Programming for Problem Solving

9. Structures within Structures


In C, a structure declaration can be placed inside another structure. This is also known as nesting of structure
Example1:
struct student
{
int stu_id;
char name[30];
struct
{
int dd;
int mm;
intyy;
}dob;
int marks:
};
struct student s1;

The structure student contains the member named dob ,which itself is a structure with three members.
Members contained in the inner structure namely dd,mm and yy.
It can be referred as

s1.dob.dd
s1.dob.mm
s1.dob.yy

An innermost member in a nested structure can be accessed by chaining all the concerned structure variables.
From outermost to innermost with the member using dot operator.

Example2 :

Struct dob
{
int dd;
int mm;
int yy;
};
struct student
{
intcstu_id;
char name[30];
struct dob date;
int marks:
};
struct student s1;

dob template is defined outside the student template and is used to define the structure of date

CSE@HKBKCE 97
18CPS13 C Programming for Problem Solving

10. Structures and Functions


C supports the passing of structure values as arguments to functions There are three methods by which the
values of a structure can be transferred from one function to another.

1. The first method is to pass each member of the structure. as an actual argument of the function.The
actual arguments are then treated independently like ordinary variables. This is the most elementary
method and becomes unmanageable and inefficient when the structure size is large.

2. The second method involves passing of a copy of the entire structure to the called function. The function
is working on a copy of the structure. any changes to structure members within the function are not
reflected in the original structure (in the calling function). it is, therefore ,necessary for the function to
return the entire structure back to the calling function.

3. The third approach employs a concept called pointers to pass the structure as an argument. In this case
the address location of the structure is passed to the called function. The function can access indirectly
the entire structure and work on it.
The general format of sending a copy of a structure to the called function is:
function_name(structure_variable_name);
The called function takes the following form:
data_type function_name(struct_type structure_var)
{
…………
………….
return(expression);
}
Example to pass each member of the structure. as an actual argument of the function
struct student
{
char name[20];
int roll_no;
int marks;
};

Void print_struct(char name[20], int roll_no, int marks);


int main()
{
struct student stu = {"Tim", 1, 78};
print_struct(stu.name, stu.roll_no, stu.marks);

voidprint_struct(char name[20], int roll_no, int marks)


{
printf("Name: %s\n", name);
printf("Roll no: %d\n", roll_no);
printf("Marks: %d\n", marks);
printf("\n");
}

Example for passing a copy of the entire structure to the called function

struct student
{
CSE@HKBKCE 98
18CPS13 C Programming for Problem Solving

char name[20];
introll_no;
int marks;
};

void print_struct(struct student stu);

int main()
{
struct student stu = {"George", 10, 69};
print_struct(stu);
}

voidprint_struct(struct student stu)


{
printf("Name: %s\n", stu.name);
printf("Roll no: %d\n", stu.roll_no);
printf("Marks: %d\n", stu.marks);
printf("\n");
}

CSE@HKBKCE 99
18CPS13 C Programming for Problem Solving

POINTERS
A pointer is a derived data type in C. It is built from one of the fundamental data types available in C.
Pointers store memory addresses as their values. pointers can be used to access and manipulate data stored in
the memory;

Pointers offer a number of benefits to the programmers They include:

1. Pointers are more efficient in handling arrays.


2. Pointers can be used to return multiple values from a function via function arguments.
3. Pointers permit references to functions and thereby facilitating passing of functions as argumentsto
other functions.
4. The use of pointer arrays to character strings results in saving of data storage space inmemory,
5. Pointers allow C to support dynamic memory management.
6. Pointers provide an efficient tool for manipulating dynamic data structures such as structures, linked
lists, queues, stacks and trees.
7. Pointers reduce length and complexity of programs.
8. They increase the execution speed and thus reduce the program execution time.

Understanding pointers

The computer‘s memory is a sequential collection of storage cells as shown in the below Fig. Each cell,
commonly known as a byte, has a number called address associated with it. Typically, the addresses are
numbered consecutively, starting from zero. The last address depends on the memory size. A computer system
having 64 K memory will have its last address as 65,535.

Memo Cell Address


0
1
2
3
4
5
.
.
.
65535
Fig 1: Memory Organization
Whenever we declare a variable, the system allocates, somewhere in the memory, an appropriate location to
hold the value of the variable. Since, every byte has a unique address number, this location will have its own
address number.
Consider the following statement int quantity = 179;

This statement instructs the system to find a location for the integer variable quantity and puts the value 179 in
that location. Assume that the system has chosen the address location 5000 for quantity. Represent this as
shown in Fig 2, (Note that the address of a variable is the address of the first byte occupied by that variable.)

Quantity Variable
Address value
5000 179
Fig 2 : Representing of Variable

CSE@HKBKCE 100
18CPS13 C Programming for Problem Solving

During execution of the program, the system always associates the name quantity with the address 5000.
Since memory addresses are simply numbers, they can be assigned to some variables that can be stored in
memory, like any other variable. Such variables that hold memory addresses are called pointer variables.

Since a pointer is a variable, its value is also stored in the memory in another location. Suppose, we assign the
address of quantity to a variable p. The link between the variables p and quantity can be visualized as shown
in Fig 3. The address of p is 5048.

Fig 3. Pointer Variable

Since the value of the variable p is the address of the variable quantity, we may access the valueof quantity by
using the value of p and therefore. we say that the variable p 'points‘ to the variable quantity. Thus, p gets the
name 'pointer'.

Underlying Concepts of Pointers


Pointers are built on the three underlying concepts as illustrated below:

 Memory addresses within a computer are referred to as pointer constants. We cannot change them;
we can only use them to store data values.
 We can obtain the memory address through the variable stored there using the address operator(&).
The value thus obtained is known as pointer value,
 A pointer value can be stored into another variable. The variable that contains a pointer value is called
a pointer variable.

Accessing theaddress of a varialbe

The actual location of a variable in the memory is system dependent. Address of a variable is determined with
the help of the operator &. The operator & immediately preceding a variable returns the address of the variable
associated with it.
For example, the statement
p =&quantity;

CSE@HKBKCE 101
18CPS13 C Programming for Problem Solving

Would assign the address 5000 (the location of quantity) to the variable p. The & operator can be referred as
'address of ’ operator

Declaring a pointer Variable

In C, every variable must be declared for its type. Since pointer variables contain addresses tha tbelong to a
separate data type, they must be declared as pointers before we use them.

The declaration of a pointer variable takes the following General form:


data_type *pt_name;

This tells the compiler three things about the variable pt_name

1. The asterisk (*) tells that the variable pt_name is a pointer variable.
2. pt_name stores the address of a memory location.
3. pt_nam epoints to a variable of type data_type.

For example,

int *p; /* integer pointer */


Declares the variable p as a pointer variable that points to an integer data type.

float *x; /*float pointer */ declares x as a pointer to a floating-point variable.

The declarations cause the compiler to allocate memory locations for the pointer variables p and x. since the
memory locations have not been assigned any values, these locations may contain some unknown values in
them and therefore they point to unknown locations as shown:

Initialization of pointer variables


The process of assigning the address of a variable to a pointer variable is known as initialization. Once a pointer
variable has been declared we can use the assignment operator to initialize the variable. Example:
int quantity;
int *p; /* declaration */
p =&quantity; /* initialization */
Rules for initialization:
 The only requirement here is that the variable quantity must be declared before the initialization takes
place.
 We must ensure that the pointer variables always point to the corresponding type of data.
Example
float a ;
int x, *p;
p= &a ; /* wrong /*
p=&x ; /*correct*/
We could also define a pointer variable with an initial value of NULL or 0 (zero). That is, the following
statements are valued.
int *p = NULL;
int *p = 0;

CSE@HKBKCE 102
18CPS13 C Programming for Problem Solving

Accessing a variable through its pointer

Once a pointer has been assigned the address of a variable. Using the pointer the value of the variable can be
accessed by using unary operator *(asterisk), known as the indirection operator.

Another name for the indirection operator is the dereferencing operator.


Consider the following statements:
int quantity, *p, n;
quantity = 179;
p = &quantity;
n = *p;
 The first line declares quantity and n as integer variables and p as a pointer variable pointing to an
integer.
 The second line assigns the value 179 to quantity
 The third line assigns the address of quantity to the pointer variable p.
 The fourth line contains the indirection operator *. The * is referred as “ value at address”. Thus the
value of n would be 179.
Program : Write a program to illustrate the use of indirection operator * to access the value pointed to by a
pointer.
#include<stdio.h>
void main()
{
int a=5;
int *p
p=&a;// p is now pointing at a
*p=*p+1
printf(“ %d %d %p”, a, *p);
}
Output: 6 6
Chain of pointers
A pointer to point to another pointer, thus creating a chain

The pointer variable p2 contains the address of the pointer variable p1 which points to the location that contains the
desired value. This is known as multiple indirections. A pointer to a pointer variable must be declared using additional
indirection operator.

Example: int**p2;
- This declaration tells the compiler that p2 is a pointer to a pointer of int type the pointer p2 is not a pointer to an
integer. but it is a pointer to an integer pointer.
- Can access the target value indirectly pointed to by pointer to a pointer by applying the indirection operator twice.
Consider the following code:
#include<stdio.h>
void main ( )
{
int x, *p1,**p2;
x = 100;
p1 =&x; /* address of x */
p2 = &pl /* address of pl */
printf ("%d",**p2);
}
Output: 100

CSE@HKBKCE 103
18CPS13 C Programming for Problem Solving

Pointer increments and scale factor


Pointers can be incremented like
pl = p + 1;
or
p1++;
It will cause the pointer p1 to point to the next value of its type.
For example: if p1 is an integer with an initial value. say 2800, then after the operation p1 = p1 + 1, the value of p1 will
be 2802,
when we increment a pointer, its value is increased by the 'length' of the data type it points to. This length called the
scale factor.
For an IBM PC, the length of various data types are as follows:
characters 1 byte
integers 2 bytes
floats 4 bytes
long integers 4 bytes
doubles 8 bytes
Rules of pointer operations
The following rules apply when performing operations on pointer variables:
1. A pointer variable can be assigned the address of another variable.
2. A pointer variable can be assigned the values of another pointer variable.
3. A pointer variable can be initialized with NULL or zero value.
4. A pointer variable can be pre-fixed or post-fixed with increment or decrement operators.
5. An integer value may be added or subtracted from a pointer variable.
6. When two pointers point to the same array, one pointer variable can be subtracted from another.
7. When two pointers point to the objects of the same data types. they can be compared using relational
operators.
8. A pointer variable cannot be multiplied by a constant.
9. Two pointer variables cannot be added.
10. A value cannot be assigned to an arbitrary address (i.e., &x = 10; is illegal

Pointers and arrays


When an array is declared, the compiler allocates a base address and sufficient amount of storage to contain all the
elements of the array in contiguous memory locations. The base address is the location of the first element (index 0)
of array. The compiler also defines the array name as a constant pointer to the element.
When an array x is declared as below
i n t x [ 5] = {1 , 2, 3 , 4, 5 };

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


Value 1 2 3 4 5
Address 1000 1002 1004 1006 1008

The base address of x is 1000 and assuming that each integer requires two bytes, the five elements will be stored as
follows:
The name x is defined as a constant pointer pointing to the first element, x[0] and therefore the value is 1000 ,the
location where x[0] is stored. That is,
x = &x[0] = 1000

CSE@HKBKCE 104
18CPS13 C Programming for Problem Solving

if we declare p as an integer pointer, then the pointer p can point to the array x by the following assignment:
p = x ; i s e q u i v a l e n t t o p = &x [0] ;
we can access every value of x using p++ to move from one element to another.

Program to find the standard deviation and mean of the array using pointers
#include<stdio.h>
#include<math.h>
void main()
{
float a[10],*ptr,mean,std,sum=0,sumstd=0;
int n,i;
printf("Enter the no of elements\n");
scanf("%d",&n);
printf("Enter the array elements\n");
for(i=0;i<n;i++)
{
scanf("%f",&a[i]);
}
ptr=a;
for(i=0;i<n;i++)
{
sum=sum+ *ptr;
ptr++;
}
mean=sum/n;
ptr=a;
for(i=0;i<n;i++)
{
sumstd=sumstd+ (*ptr-mean)* (*ptr-mean);
ptr++;
}
std=sqrt(sumstd/n);
printf("sum=%f\n",sum);
printf("Mean=%f\n",mean);
printf("standard deviation=%f\n",std);
getch();
}

Pointers as f unction argum ents

Pointer as a function parameter is used to hold addresses of arguments passed during function call. This
is also known as call by reference. When a function is called by reference any change made to the reference
variable will effect the original variable
Example.
#include<stdio.h>
void swap(int *a, int *b);
main()
{
int m = 22, n = 44;
// calling swap function by reference
printf("values before swap m = %d \n and n = %d",m,n);
swap(&m, &n);
CSE@HKBKCE 105
18CPS13 C Programming for Problem Solving

printf("\n values after swap m = %d \n and n=%d",m, n);


}
void swap(int *a, int *b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
Output: values before swap m = 22 and n = 44 values
after swap m = 44 and n = 22

Function returning pointers


In C, function can also return pointer to the calling function. Consider the following code:
int *larger (int *, int *); /* prototype */
void main ( )
{
int a = 10;
int b = 20;
int *p;
p = larger(&a, &b); /Function call */
printf ("%d", *p);
}
int * larger (int *x, int *y)
{
if (*x>*y)
return (x); / *address of a */
else
return (y); /* address of b */
}

PREPROCESSOR DIRECTIVES

Definition
The preprocessor is a program that processes the source code before it passes through the Compiler. It operates
under the control of what is known as preprocessor command lines or directives.

Preprocessor directives are placed in the source program before the main line. Before the source code passes
through the compiler, it is examined by the preprocessor for any preprocessor directives. If there are any,
appropriate actions (as per the directives) are taken and then the source program is handed over to the compiler.

They all begin with the symbol #, and do not require a semicolon at the end. A set of commonly used
preprocessor directives are:

Directive Function
#deflne Defines a macro substitution
#undef Undefines a macro
#include Specifies the files to be included
#ifdef Test for a macro definition
#if Test a compile-time condition
#else Specifies alternatives when #iftest fails

CSE@HKBKCE 106
18CPS13 C Programming for Problem Solving

These directives can be divided into three categories:


1. Macro substitution directives
2. File inclusion directives
3. Compiler control directives

1. Macro Substitution
Macro substitution is a process where an identifier in a program is replaced by a predefined String composed
of one or more tokens. The preprocessor accomplishes this task under the direction of #define statement.

General form/Syntax : #define identifier string


The string may be any text, while the identifier must be a valid C name.
The most common forms of macro substitutions are:
 Simple macro substitution
 Argumented macro substitution
 Nested macro substitution

Simple Macro Substitution


Simple string replacement is commonly used to define constants
Examples of definition of Constants are:
#define COUNT 100
#define PI 3.1415926
#define CAPITAL "DELHI"
It is a convention to write all macros in capitals to identify them as symbolic constants. A definition, such as
#define M 5
will replace all occurrences of M with 5, starting from the line of definition to the end of the Program. However,
a macro inside a string does not get replaced. Consider the following two lines:
total = M * value;
prinf("M = %d\n", M);
These two lines would be changed during preprocessing as follows:
total = 5 * value;
printf("M = %d\n“, 5);
#define TEST if (x> y)
#define AND
#define PRINTprintf("Very Good. \n");
To build a statement as follows:
TEST AND PRINT
The preprocessor would translate this line to
if(x>y) printf("VeryGood.\n");

Macros with Arguments


The preprocessor permits us to define more complex and more useful form of replacements, It
Takes the form:
#define identifier(f1,f2,....fn) string
The identifiers f1, 12,...,fn are the formal macro arguments that are similar to the formal arguments in a function
definition. Subsequent occurrence of a macro with arguments is known as a macro call (similar to a function
call). When a macro is called. the preprocessor substitutes the string, replacing the formal parameters with the
actual parameters. Hence, the string behaves like a template.

CSE@HKBKCE 107
18CPS13 C Programming for Problem Solving

Example of a macro with arguments is


#define CUBE(x) (x*x*x)
If the following statement appears later in the program
volume = CUBE(side);
Then the preprocessor would expand this statement to:
volume = (side * side * side );
Other commonly used examples
#define MAX(a,b) (((a)>(b))?(a):(b))
#define MIN(a,b) (((a)<(b))?(a):(b))

Nesting of Macros
We can also use one macro in the definition of another macro. That is, macro definitions may be nested.
For instance, consider the following macro definitions.
#define M 5
#define N M+1
The preprocessor expands each #define macro, until no more macros appear in the text.
For example the statement p=N+t is replaced as
P=M+1+t
P=5+1+t
Undeflning a Macro
A defined macro can be undefined, using the statement.

#undef identifier

This is useful when we want to restrict the definition only to a particular part of the program.

2. File Inclusion
An external file containing functions or macro definitions can be included as a part of a program so that we
need not rewrite those functions or macro definitions. This is achieved by the preprocessor directive
#include "filename"
Where file name is the name of the file containing the required definitions or functions. At this point, the
preprocessor inserts the entire contents of filename into the source code of the program. When the filename is
included within the double quotation marks, the search for the file is made first in the current directory and
then in the standard directories.

Alternatively, this directive can take the form #include <filename> without double quotation

In this case, the file is searched only in the standard directories, If an included file is not found, an error is
reported and compilation is terminated.

Example
Assume that we have created the following three files:
SYNTAXC contains syntax definitions.
STATC contains statistical functions.
TESTC contains test functions.
We can make use of a definition or function contained in any of these files by including them in the program
as:
#include <stdio.h>
#include “SYNTAXC”
#include “STAT.C”
#include “TEST.C”
#define M 100
CSE@HKBKCE 108
18CPS13 C Programming for Problem Solving

main()
{
----
----
----
}

3. Compiler Control Directives


The C preprocessor offers a feature known as conditional compilation, which can be used to ‘switch‘on or off
a particular line or group of lines in a program. While developing large programs, one or more problems arises
for of the following situations:
Situation 1
This situation refers to the conditional definition of a macro. We want to ensure that the macro
TEST is always defined, irrespective of whether it has been defined in the header file or not. This can be
achieved as follows:
#include “DEFLNE.H”
#ifndef TEST
#define TEST 1
#endif
DEFINE.H is the header file that is supposed to contain the definition of TEST macro. The directive. #ifndef
TEST searches for the definition of TEST in the header file and if not defined, then all the lines between the
#ifndef and the corresponding #endif directive are left ‘active' in the program. That is, the preprocessor
directive # define TEST is processed.

In case, the TEST has been defined in the header file, the #ifndef condition becomes false, Thereforethe
directive #define TEST is ignored.

Similar is the case when we want the macro TEST never to be defined. Consider the following code:
#ifdef TEST
#undef TEST
#endif
This ensures that even if TEST is defined in the header file, its definition is removed.

Situation 2
The main concern here is to make the program portable. This can be achieved as follows:
--------
---------
void main()
{
--------
---------
#ifdef IBM_PC
{
--------
---------
code for IBM_PC
}
#else
{ --------
---------
code for HP machine
CSE@HKBKCE 109
18CPS13 C Programming for Problem Solving

---------
}
#endif
--------
---------
}
If we want the program to run on IBM PC, we include the directive #define IBM_PC in the program; otherwise
it is not included.The compiler complies the code for IBM PC if lBM_PC is defined, otherwise code for the
HP is compiled.

Situation 3
This is similar to the above situation and therefore the control directives take the following form:
#ifdef ABC
group-A lines
#else
group-B lines
#endif
Group-A lines are included if the customer ABC is defined. Otherwise, group-B lines are included.

Situation 4
Debugging and testing are done to detect errors in the program. While the Compiler can detect syntactic and
semantic errors, it cannot detect a faulty algorithm where the program executes, but produces wrong results .
The process of error detection and isolation begins with the testing of the program with a known Set of test
data. The program is divided down and printf statements are placed in different parts to See intermediate results.
Such statements are called debugging statements and are not required once The errors are isolated and
corrected. We can either delete all of them or, alternately, make them Inactive using control directives as:

-----------
-----------
#ifdefTEST
{
printf("Arrayelementsts\n");
for (i=0; i< m; i++)
printf("x[%d] : %d\n”,i.x[i]);
}
#endif
-----------
-----------
#ifdef TEST
printf (… );
#endif
The statements between the directives #ifdef and #endif are included only if the macro TEST is defined. Once
everything is OK, delete or undefine the TEST. This makes the #ifdefTEST conditions false and therefore all
the debugging statements are left out.

The C preprocessor also supports a more general form of test condition - #if directive. This takes
The following form:
#if constant_expression
{
statement-l;
statement-2;
………….
CSE@HKBKCE 110
18CPS13 C Programming for Problem Solving

}
#endif
The constant-expression may be any logical expression such as:
TEST <= 3
MACHINE == ‘A’
If the result of the constant-expression is nonzero (true), then all the statements between the #if and #endif are
included for processing; otherwise they are skipped. The names TEST, MACHINE etc. may be defined as
macros.

ANSI additions
ANSI committee has added some more preprocessor directives. They are:
#elif Provides alternative test facility
#pragma Specifies certain instructions
#error Stops compilation when an error occurs
The ANSIstandard also includes two new preprocessor operations:
# Stringizing operator
## T'oken-pasting operator

CSE@HKBKCE 111

You might also like