Vtu 18CPSC13/23
Vtu 18CPSC13/23
Vtu 18CPSC13/23
Prepared by
Dr. Loganathan R
Prof & HOD
Department of Computer Science and Engineering
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.
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-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
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.
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.
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.
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.
CSE@HKBKCE 4
18CPS13 C Programming for Problem Solving
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.
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.
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
CSE@HKBKCE 9
18CPS13 C Programming for Problem Solving
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.
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.
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.
CSE@HKBKCE 18
18CPS13 C Programming for Problem Solving
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);
}
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)
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
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
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
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.
CSE@HKBKCE 25
18CPS13 C Programming for Problem Solving
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.
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;
}
}
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
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.
CSE@HKBKCE 31
18CPS13 C Programming for Problem Solving
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
* 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.
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>
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
Output
Press any key
h
The character is a letter.
Press any key
5
The character is a digit
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
CSE@HKBKCE 37
18CPS13 C Programming for Problem Solving
The general from of printf statement is: printf(“control string “, arg1, arg2,......argn);
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);
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 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
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.
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.
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
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.
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
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.
..............
.............
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
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.
Example:
The segment
if ( x <0)
flag = 0;
else
flag = 1;
can be written as
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
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 C language provides for three constructs for performing loop operations. They are:
1. The while statement.
2. The do statement.
3. The for 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
#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
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);
}
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
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
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
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
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;
---------------
--------------
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
#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
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.
CSE@HKBKCE 57
18CPS13 C Programming for Problem Solving
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.
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
#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
#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.
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
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’;
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.
K R I S H \0 ? ? ? ?
0 1 2 3 4 5 6 7 8 9
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';
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
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
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
while(s2[j]!='\0')
{
s1[i]=s2[j];
j++;
i++;
}
s1[i]='\0';
}
void main()
{
char s1[50],s2[50],len,c,flag;
CSE@HKBKCE 68
18CPS13 C Programming for Problem Solving
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
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.
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
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:
All the six elements are grouped into two parts, namely
Function header (first three elements); and
Function body (second three elements).
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:
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.
Example
main( )
{
int y;
y = mul(10,5); /*function call*/
printf(“%d\n”, y);
}
CSE@HKBKCE 72
18CPS13 C Programming for Problem Solving
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:
#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;
}
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 main()
{
sum( ); // function call
}
CSE@HKBKCE 73
18CPS13 C Programming for Problem Solving
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 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);
}
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);
}
CSE@HKBKCE 74
18CPS13 C Programming for Problem Solving
void main()
{
int x = 20, y = 10, s, d;
mathoperation(x,y, &s, &d);
printf(“sum=%d\n”, s);
printf(“Difference=%d\n”, s);
}
The actual arguments x and y are input arguments, s and d are output arguments.
Example Programs
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);
}
The program calculates the ratio a/b-c and prints the result
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);
}
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
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
Sample Input/Output:
Enter n:
4
Factorial=24
#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
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:
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]);
}
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);
}
1
Sorted Array
1
2
3
4
5
Program to find the standard deviation and mean of the array using functions
#include<math.h>
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 );
}
CSE@HKBKCE 81
18CPS13 C Programming for Problem Solving
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);
}
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();
}
while(s1[i]!=’\0’)
i++;
while(s2[j]!='\0')
{
s1[i]=s2[j];
j++;
i++;
}
s1[i]='\0';
}
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.
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 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’).
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
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
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:
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.
struct tag_name
{
data_type member1;
data_type member2;
------------------------------
------------------------------
Data type member n;
};
Example :
Consider a book database consisting of book name, author , number of pages, and 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.
After defining a structure format ,declare variables of that type. A structure variable declaration includes the
following elements:
Example:
structbook_bank
{
char title[20];
char author [15];
int pages;
float price;
};
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
CSE@HKBKCE 89
18CPS13 C Programming for Problem Solving
{
char title[20];
char author [15];
int pages;
float price;
{
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:
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‘.
is the variable representing the price of bookl and can be treated like any other ordinaryvariable.
CSE@HKBKCE 90
18CPS13 C Programming for Problem Solving
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.
Example:
struct stud
{
Char name[25];
int weight;
float height;
};
struct stud s1 = {“Alex”,60, 180.75};
Example:
Scanf(“%s%d%f”,s1.name,&s1.weight, &s1.height)
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;
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;
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
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:
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.
struct class
{
Char name[25];
Char usn[11];
Int marks;
};
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
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);
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
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].
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
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
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;
};
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;
};
int main()
{
struct student stu = {"George", 10, 69};
print_struct(stu);
}
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;
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.
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.
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'.
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.
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
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.
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,
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:
CSE@HKBKCE 102
18CPS13 C Programming for Problem Solving
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.
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
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();
}
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
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
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.
CSE@HKBKCE 107
18CPS13 C Programming for Problem Solving
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()
{
----
----
----
}
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