0% found this document useful (0 votes)
17 views201 pages

Sanet.st-fundamentals of Computing and Programming

The document outlines the book 'Fundamentals of Computing and Programming', which aims to provide both theoretical knowledge and practical skills to prepare students for the industry. It covers various topics including computer fundamentals, C programming, arrays, strings, functions, pointers, structures, and unions, with each chapter featuring examples and interview readiness questions. The authors emphasize a simple and understandable language to facilitate learning and comprehension.

Uploaded by

shrikant
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views201 pages

Sanet.st-fundamentals of Computing and Programming

The document outlines the book 'Fundamentals of Computing and Programming', which aims to provide both theoretical knowledge and practical skills to prepare students for the industry. It covers various topics including computer fundamentals, C programming, arrays, strings, functions, pointers, structures, and unions, with each chapter featuring examples and interview readiness questions. The authors emphasize a simple and understandable language to facilitate learning and comprehension.

Uploaded by

shrikant
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 201

Fundamentals of Computing and Programming provides not only theoretical knowledge, but TM

also practical aspects to make the student industry-ready. Each chapter is presented in a
unique way with a lot of examples, sample programs and, most importantly, comprehensive
interview readiness questions in the last section, which will not only help revisit the concepts,
but also make sure that the student can face the interviewer in this prescribed area without
fear and hesitation.
The book starts with the fundamentals, characteristics of computers, generations,
organisation and architecture of computers, number systems, software classification, the
Internet, and so on. This chapter is aimed at giving the student a platform for the subject and
to set the mood for further reading. The language chosen is simple and understandable.
Chapter 2 deals with C programming, its introduction, fundamental rules and guidelines,
process of compilation and linking, variables, naming conventions, operators, etc. All these
topics have examples to substantiate the learning process. Chapter 3 discusses arrays and
string operations quite comprehensively while chapter 4 is all about functions and pointers.
Chapter 5 discusses the structures and unions with coverage also given to the preprocessor
directives. Each chapter other than chapter 1 has interview questions as part of it.

INTRODUCTION TO COMPUTERS
Introduction • Characteristics of Computers • Computer Generations • Classification of Computers
• Basic Computer Organisation • Number Systems • Algorithm • Pseudocode • Flowchart • Computer
Software • Types of Software • Internet Terminology

C PROGRAMMING BASICS
Introduction to C Programming • Fundamental Rules • Structure of a C Program • Compilation and
Linking Processes • Constants, Variables, Keywords, Identifiers, Delimiters • Declaring and Initialising
Variables • Data Types • Operators and Expressions • Managing Input and Output Operations
• Decision Making and Branching • Looping Statements • Solving Simple Scientific and Statistical
Problems.

ARRAYS AND STRINGS


Arrays • Characteristics, Initialisation • Declaration • One-Dimensional and Two-Dimensional Arrays
• String • String Operations • String Arrays • Simple Programs • Sorting • Searching • Matrix Operations
(Addition, Subtraction and Multiplication).

FUNCTIONS AND POINTERS


Function • Definition of Function • User-defined Functions • Declaration of Function • Call by Reference
• Call by Value • Recursion • Pointers • Definition • Initialisation • Pointers Arithmetic • Pointers and
Arrays • Example Problems.

S. Karthik • B. Chellaprabha • T. Kalaikumaran


STRUCTURES AND UNIONS
Defining Structures and Unions • Structure Declaration • Need for Structure Data Type • Structure
within a Structure • Union-Programs using Structures and Unions • Preprocessor Directives.

Dr. S. Karthik is Dean and Professor, Dept. of CSE, SNS College of Technology, Coimbatore. S. Karthik
Dr. B. Chellaprabha is Head – Academics, Dept. of CSE, SNS College of Technology, Coimbatore.
Dr. T. Kalaikumaran is Head and Professor, Dept. of CSE, SNS College of Technology, Coimbatore. B. Chellaprabha
978-93-89633-46-7 T. Kalaikumaran
` 345/- Distributed by:

9 789389 633467
TM
Fundamentals of
Computing and Programming

Book 8.indb 1 6/7/2017 1:27:55 PM


Book 8.indb 2 6/7/2017 1:27:55 PM
Fundamentals of
Computing and Programming

S. Karthik
Dean and Professor
Dept. of CSE, SNS College of Technology
Coimbatore

B. Chellaprabha
Head – Academics
Dept. of CSE, SNS College of Technology
Coimbatore

T. Kalaikumaran
Head and Professor
Dept. of CSE, SNS College of Technology
Coimbatore

Book 8.indb 3 6/7/2017 1:27:55 PM


©Copyright 2019 I.K. International Pvt. Ltd., New Delhi-110002.

This book may not be duplicated in any way without the express written consent of the publisher,
except in the form of brief excerpts or quotations for the purposes of review. The information
contained herein is for the personal use of the reader and may not be incorporated in any commercial
programs, other books, databases, or any kind of software without written consent of the publisher.
Making copies of this book or any portion for any purpose other than your own is a violation of
copyright laws.

Limits of Liability/disclaimer of Warranty: The author and publisher have used their best efforts in
preparing this book. The author make no representation or warranties with respect to the accuracy or
completeness of the contents of this book, and specifically disclaim any implied warranties of
merchantability or fitness of any particular purpose. There are no warranties which extend beyond the
descriptions contained in this paragraph. No warranty may be created or extended by sales
representatives or written sales materials. The accuracy and completeness of the information provided
herein and the opinions stated herein are not guaranteed or warranted to produce any particulars
results, and the advice and strategies contained herein may not be suitable for every individual.
Neither Dreamtech Press nor author shall be liable for any loss of profit or any other commercial
damages, including but not limited to special, incidental, consequential, or other damages.

Trademarks: All brand names and product names used in this book are trademarks, registered
trademarks, or trade names of their respective holders. Dreamtech Press is not associated with any
product or vendor mentioned in this book.

ISBN: 978-93-89520-72-9

EISBN: 978-93-89795-39-4
PREFACE

Fundamentals of Computing and Programming provides not only theoretical knowledge


but also practical aspects to make the student industry-ready. Each chapter is presented
in a unique way with lot of examples, sample programs and most importantly
comprehensive interview readiness questions in the last section, which will not only
help revisit the concepts, but also make sure that the student can face the interviewer
in this prescribed area without fear and hesitation.
The book starts with the fundamentals, characteristics of computers, generations,
organization and architecture of computers, number systems, software classification, the
Internet and so on. This chapter is aimed at giving the student a platform for the subject
and to set the mood for the further reading. The language chosen is simple and
understandable. Chapter 2 deals with C programming, its introduction, fundamental
rules and guidelines, process of compilation and linking, variables, naming conventions,
operators, etc. All these topics have examples to substantiate the learning process.
Chapter 3 discusses arrays and string operations quite comprehensively while chapter
4 is all about functions and pointers. The kind of examples given for pointers shall be
pretty much enjoyable and easier to understand as well. Chapter 5 discusses the structures
and unions with coverage also given to the preprocessor directives. Each chapter other
than chapter 1 has interview questions as part of it.
We are thankful to the SNS group of institutions and its management for consistently
supporting us.

S. Karthik
B. Chellaprabha
T. Kalaikumaran

Book 8.indb 5 6/7/2017 1:27:55 PM


Book 8.indb 6 6/7/2017 1:27:55 PM
CONTENTS

Preface v
1. Introduction 1
1.1 Introduction 1
1.2 Characteristics of Computers 3
1.3 Computer Generations 5
1.4 Classification of Computers 8
1.5 Computer Organization 10
1.6 Number Systems 13
1.7 Algorithms and Pseudocode 17
1.8 Flowcharts 20
1.9 Computer Software and Its Types 22
1.10 Internet Terminology 25
Key Points to Remember 28
Exercise 31
2. C Programming 32
2.1 Introduction 32
2.2 Fundamental Rules 33
2.3 Structure of a C Program 33
2.4 Compilation and Linking Process 34
2.5 Constants, Variables, Keywords, Identifiers and Delimiters 36
2.6 Data Types 41
2.7 Operators 45
2.8 Managing Input and Output Operations 66
2.9 Decision Making and Branching 67
2.10 Looping Statements 74
2.11 Solving Simple Scientific and Statistical Problems 79
Key Points to Remember 81
Questions to Test Your Skills! 82

Book 8.indb 7 6/7/2017 1:27:55 PM


viii Contents

3. Arrays and Strings 88


3.1 Introduction 88
3.2 Characteristics, Initialization and Declaration of Arrays 91
3.3 One-dimensional and Two-dimensional of Arrays 93
3.4 Strings and String Operations 96
3.5 String Arrays 99
3.6 Programming Examples Using Arrays and Strings 101
3.7 Matrix Operations 107
Key Points to Remember 112
Exercise 113
Questions to Test Your Skills 115
4. Functions: An In-depth Analysis and Understanding 120
4.1 Introduction 120
4.2 Declaration: Function has to be Declared This Way (Prototype) 122
4.3 What is Call by Reference? What is Call by Value? 124
4.4 Recursion and Its Importance 126
4.5 Pointer and Its Importance 130
4.6 Arrays with Pointer. 137
Key Points to Remember 139
Exercise 139
Interview Readiness Questions 140
5. Structures and Unions 146
5.1 Introduction 146
5.2 Structure Declaration 149
5.3 Need for Structure Data Type 151
5.4 Structure within a Structure 156
5.5 Union 158
5.6 Programs Using Structures and Unions 161
5.7 Preprocessor Directives 168
Key Points to Remember 170
Exercise 172
Questions to Test Your Skills 173
Appendix 183
Index 189

Book 8.indb 8 6/7/2017 1:27:55 PM


1 INTRODUCTION

LEARNING OBJECTIVES

After reading this chapter, the reader would be able to understand:


•• What is a computer and why it is needed?
•• What are the different characteristics of computers?
•• Computer generations in detail.
•• Classification of computers.
•• Basic computer organization.
•• Number systems and algorithms.
•• What is pseudocode?
•• Flowchart and different symbols used in it.
•• What is meant by computer software and its different types?
•• Internet terminology in detail.

1.1 INTRODUCTION

A computer is an electronic device that can receive data in a certain form and process
the same through a sequence of operations in accordance with a set of instructions
provided in the form of a software programme and produces the result in the form of
data or information.
Today computers are all around us – from desktop computers to smartphones,
they are changing the ways we live our life. They manipulate information or data.
The computer sees data as ones and zeros but it knows how to combine them into
more complex things such as a photograph, a movie, a website, a game and much
more.

Fundamentals of Computing and Programming

Book 8.indb 1 6/7/2017 1:27:55 PM


2 Fundamentals of Computing and Programming

Output Devices

System
Unit

Mass Storage Input Devices


Device

Figure 1.1 A simple computer.


Image Courtesy: http://www.webopedia.com

Computers use a combination of hardware and software. Hardware refers to any


physical part of the computer which includes all of the internal components and also
the external parts like the display and the keyboard. Software also refers to any set of
instructions that tells the hardware what to do. Examples include web browser, media
player or word processor. Computers can be a desktop computer or a laptop computer.
There are many different companies that make them including Dell, Toshiba, Lenovo,
Sony, Acer, Samsung and HP to name a few. They usually come with an operating
system like a Microsoft Windows or a Linux OS. Operating system here refers to the
set of programs that manage the activities of the computer and allows the user use the
system resources effectively.

Mango
Pulp

Mango
Churning Shake
Sugar

Process Output
Milk

Input

Figure 1.2 I/O Processing with an example.

Computers come in other shapes and sizes as well, for example, smartphones, gaming
consoles, tablets and smart TVs that have built-in computers. Servers are another type

Book 8.indb 2 6/7/2017 1:27:56 PM


Introduction 3

of computers that plays an important role in the industries. A server serves information
to other computers on a network. Servers are also used to store and share files across
machines. Figure 1.2 represents the input output system with a practical example.
Input devices are used for entering the data or instructions into the computer. Some
common examples of input devices include keyboard and mouse. Performing calculations
or comparing data is called the processing. The Central Processing Unit (CPU) present
in the computer does this. It is the action that converts data into meaningful information.
A large amount of data can be stored on computers. The data entered in a computer is
stored on its hard disk. The hard disk, DVD-ROM, CD-ROM and USB drives are generally
used for permanent storage of the information.

Input Device Output Device


e.g. Keyboard, Mouse e.g. Display, Printer

Processing Unit
e.g. CPU

Storage Device
e.g. DVD, Pen drive

Figure 1.3 Basic components of a computer system.

The role of the output device is to display information stored in the computer system
to the user. The major three types of output devices include monitor, printer and speakers.
The data gets displayed on the monitor screen which includes text, graphics, animation
and video. The printer produces hard copies while the speakers produce sounds or
audio to the end user.

1.2 CHARACTERISTICS OF COMPUTERS

Computers are an integral part of our lives and are playing vital roles in the working
atmosphere. They possess their own characteristics such as:
▪▪ Speed
▪▪ Accuracy
▪▪ Diligence
▪▪ Storage capacity
▪▪ Versatility
▪▪ Power of remembering
▪▪ No IQ and feelings

Book 8.indb 3 6/7/2017 1:27:56 PM


4 Fundamentals of Computing and Programming

The faster the CPU can run, the faster the output is also going to be. It helps to
run multiple tasks in parallel and produce the output in less time. Generally, the clock
speed defines the processing power. A system with 3 GHZ clock speed can run three
thousand million cycles per second and compute the results. The performance of the
computer is hence defined by the amount of work accomplished by a computer system.
Short response time, throughput and low utilization of computing resources are the
different parameters used to judge the performance of a computer system.

Figure 1.4 Basic information about a computer.

Figure 1.4 represents the basic information about the computer which decides upon
the performance of the system. There are many components that help improve the
performance of the system including the CPU, bus speed, cache, hard drive, RAM, video
card and the operating system itself. The hardware refers to the physical components
and the software refers to the visual component that helps the system perform better.
Accuracy represents the correctness of the information. Bug-free computer chips help
to produce better accurate information. If there is any software or hardware concern,
then the results may not be precise leading to wrong analyses for the end user. The
accuracy of the system is identified through the process of analysing the robustness,
correctness and safety.
Diligence refers an effort to accomplish something. Computers are highly consistent
and are not like human beings. They yield the same consistent results across diverse
times when there are no modifications introduced. They also do not experience human
traits like boredom and tiredness. There is no concept of lack of concentration with these
machines. Hence, computers are good in performing voluminous and repetitive jobs.
Computers can store large volume of data. Gordon E. Moore, in 1965 foresaw the
prospect of the semiconductor constituents and said that the amount of transistors
that can be fabricated on the thick integrated circuit (IC) will double approximately in

Book 8.indb 4 6/7/2017 1:27:57 PM


Introduction 5

every two years and is seen to be true till date. Figure 1.5 represents the same which
aids computers to hoard huge quantity of data on small storage devices such as USB
drives and SD cards. This also means that the whole processing power of the computers
will double every two years.
Moore’s Law
Process Technology (m)
10 1 0.1 45 nm 0.01
10,000,000,000
Dunnington
1,000,000,000 Intel Microprocessors Core i7
Core 2 Duo
Number of Transistors
per Integrated Circuit

100,000,000 Pentium 4
Pentium II Silverthorne
10,000,000
Pentium
1,000,000 486
386
1,00,000 286
8086 Doubles every 2.1 yrs
10,000 4004
1,000
1970 1975 1980 1985 1990 1995 2000 2005 2010 2015 2020
Year

Figure 1.5 Moore’s law in storage technology.


Image Courtesy: https://forums.anandtech.com

Computers are multipurpose machines and when they are programmed with logical
steps, they are proficient in executing any task. They are engaged at wide variety of places
like railway reservation, hotels, airways, weather forecasting, textiles, medical field, banks,
real estate industries, mechanical designing and educational institutions, etc.
Data and information are the two common words used in computing technology.
Data refers to the raw piece of text or numbers that are gathered and processed to yield
information. Computers are good in taking the data, process it and then store the output
or display the results based on user needs. Though computers can store and retrieve
data at any point of time, they do not hold any IQ or sensation like human beings which
is the only aspect that differentiates human beings from the computing machines. The
different features of the computer discussed so far makes it more vital in today’s digital
world and is difficult to imagine a world without computers.

1.3 COMPUTER GENERATIONS

Computers has been existing in the world since 19th century when an English
Mathematician Charles Babbage first invented it. Based on the capabilities of different
computers developed from time to time, they are considered computer generations.
There are totally five computer generations as of now and have seen a remarkable
growth over these years. Table 1.1 provides the details on different generations of
computers along with examples.

Book 8.indb 5 6/7/2017 1:27:58 PM


6 Fundamentals of Computing and Programming

Table 1.1 Computer generations


Generation Device Details Characteristics Examples
First Vacuum tubes Vacuum tubes were • Machine language UNIVAC and
(1940-1956) used for circuitry and • Costly ENIAC
magnetic drums were • Huge size
used for memory.

Second Transistors Transistors replaced • Smaller Honeywell and


(1957-1963) vacuum tubes in • Faster IBM produced
second generation. • Cheaper computers
• Reliable based on this
• Energy efficient technology

Third Integrated Transistors got • I ncrease in speed IBM 360/370


(1964-1971) circuits miniaturized and were more efficient and CDC 6600
also placed on the were based on
silicon chips called this generation
semiconductors. principles

Fourth Microprocessor Thousands of ICs got •M  ore powerful Intel 4004 chip,
(1972-1988) on to one single silicon • GUIs, mouse and IBM’s first
chip thereby reducing hand-held devices computer for
the space and home users and
improved performance. Apple Mac

Fifth ULSI and IC’s got in with ULSI • Powerful IBM, Pentium
(1988- Artificial technology. Large • Cheaper and PARAM
Present) Intelligence capacity hard disks • Easy to use
with RAID support, • Portability
advanced servers, • Ease of software
internet, cluster development,
computing came in this debugging and
generation. enhancements

Digital computers which are a class of devices that are capable of working on the
problems by processing the information or data provided to them in discrete form.
These are the latest types of computers and are more powerful than the computers
used earlier. Figure 1.6 represents the different computers developed across different
generations.

Book 8.indb 6 6/7/2017 1:27:58 PM


Introduction 7

Generation Type of Computer

FIRST

Image Courtesy: http://www.chilloutpoint.com

SECOND

Image Courtesy: http://it-history.net/second_generation.html

THIRD

Image Courtesy: https://www.tutorialspoint.com

FOURTH

Image Courtesy: https://www.tutorialspoint.com

FIFTH

Image Courtesy: http://blog.mirchimart.com/history-of-computers/

Figure 1.6 Computers in use over the generations.

Portable PCs, laptops and hand-held smartphones are common these days and allows
users to do computing even on travel. They also consume less power when compared
with their predecessors. The growth is expected to increase in the coming generations.

Book 8.indb 7 6/7/2017 1:27:59 PM


8 Fundamentals of Computing and Programming

1.4 CLASSIFICATION OF COMPUTERS

Data processing capabilities differentiate different types of computers. Purpose, data


handling and functionality will help in classifying computers. Computers can be called
general-purpose computers or specific-purpose computers based on their design and
usage. General-purpose computers can store numerous programs but lack in efficiency
and speed of execution. Specific-purpose computer can do only a specific jobs and are
generally fast in execution.

Computer

Analog Computer Digital Computer Hybrid Computer

 Microcomputer
 Minicomputer
 Mainframe computer
 Supercomputer

Figure 1.7 Types of computers.

Based on the data handling, computers can be classified as analog, digital or hybrid
computers. Measurements are obtained and translated into data and analog computers
work on the principle of this measuring. They employ electrical parameters like voltage,
current, resistance, etc., to represent the quantities. They don’t work on numbers. Figure
1.7 represents the different types of computers in usage.
Digital computers also operate on discrete data directly and are represented in digital
form. 0’s and 1’s are used in this technology for communication and processing purposes.
The results are generally more accurate than the analog computers and they also execute
at a faster rate. Hybrid computers are the combination of both analog and digital
computers in the sense that they have measuring features of the analog computer and
also the binary feature of the digital computer.
On the basis of size, computers can be classified as supercomputers, mainframe
computers, minicomputers, microcomputers or personal computers and workstations.
Supercomputers are the fastest and most powerful type of computers. They are quite
expensive and are generally used for specialized applications where a large amount of

Book 8.indb 8 6/7/2017 1:27:59 PM


Introduction 9

mathematical calculations is involved. Figure 1.8 represents the IBM’s supercomputer


at the Argonne National Laboratory and runs over 2,50,000 processors.

Figure 1.8 IBM’s supercomputer.


Image Courtesy: https://en.wikipedia.org/wiki/Supercomputer

Mainframe computers are just below supercomputers and support simultaneous


programs. They are large and generally expensive but capable of supporting multiple
users simultaneously. Though supercomputers can execute programs much faster than
mainframe computers, they are used widely for their parallelism. Figure 1.9 shows an
IBM system z9 mainframe computer.

Figure 1.9 IBM’s system z9 mainframe computer.


Image Courtesy: https://en.wikipedia.org/wiki/Mainframe_computer

A minicomputer developed in mid-1960 refers to the machine that lies in the middle
range of the computing spectrum and it includes computers like higher end SPARC,
Itanium based systems from Oracle, and Hewlett-Packard. Figure 1.10 represents a
minicomputer.

Figure 1.10 First generation DEC minicomputer.


Image Courtesy: https://en.wikipedia.org/wiki/Minicomputer

Book 8.indb 9 6/7/2017 1:28:00 PM


10 Fundamentals of Computing and Programming

A microcomputer refers to the small and relatively inexpensive computers that contains
a microprocessor, I/O devices and memory on a single printed circuit board. The IBM
PC introduced during 1981 became popular and the term personal computer was more
used than microcomputer. The recent introduction of Raspberry Pi refers to credit card
sized computer and is more popular these days for both development as well application
usage. Figure 1.11 represents a microcomputer.

Figure 1.11 Micro/Personal computer.


Image Courtesy: http://classificationofcomputers.blogspot.in/

Computers can also be classified based on the operating principles, applications, size
and capability, number of microprocessors, word length and number of users. Portable
computers are very common these days and they include:
▪▪ Laptop
▪▪ Notebooks
▪▪ Palmtops
▪▪ Wearable computers
Workstation refers to a desktop computer terminal and is mostly networked. They
are generally more powerful than a personal computer. Workstations are used in offices
and educational institutions for maintaining and processing a huge data.

1.5 COMPUTER ORGANIZATION

Hardware and software together form a computer. While the hardware includes the
processor, memory and I/O devices, the software refers to the programs which are a
set of instructions that the hardware will execute. Figure 1.12 represents computer
organization with different parts labelled.

Book 8.indb 10 6/7/2017 1:28:00 PM


Introduction 11

Processor

Common Bus (address, data, & control)

Control Unit

Data path

Arithmetic
Logic Unit Memory

Output Input
Program Data
Units Units
Registers Storage Storage

Figure 1.12 Computer organization.

The processor in computer organization refers to the central processing unit of the
system and it contains:
▪▪ Data path
▪▪ Control unit
Data path includes the register file and the arithmetic logic unit. A register file is a
storage location which is present within the CPU. The arithmetic logic unit will perform
all the mathematical calculations along with the logical evaluations.
The control unit decodes as well monitors the execution of instructions along with
coordination of the operations. The clock present in the system synchronize the different
activities of the CPU and are generally measured by the clock cycles. It also maintains
the following two registers:
▪▪ Program counter (keeps track of the next instruction address)
▪▪ Status register (flags the result of the instruction execution)
Microprocessor refers to the computer’s processor which includes the functions of a
computer’s central processing unit (CPU) on a single integrated circuit (IC), or at most
a few integrated circuits. It is a multipurpose, register based and clock driven digital
IC which takes binary data as input and processes it as per the instructions fed and
provides the result through the output unit.
Microcontrollers integrate the above discussed microprocessor along with the
peripheral devices in embedded systems. It is also called a small computer on a single
integrated circuit. Hence, it is a system on a chip or SoC. A microcontroller can have
one or more CPU’s inside it. They also contain memory and programmable input/output
peripherals in it. Figure 1.13 shows the difference between a microprocessor and a
microcontroller.

Book 8.indb 11 6/7/2017 1:28:01 PM


12 Fundamentals of Computing and Programming

Microcontroller as SoC Microprocessor and other units

CPU Clock
  CPU
  Timer /
Counter Memory I/O Interface
  Memory
  Clock
Timer USART
  I/O Interface
  Memory
Other Peripherals

Figure 1.13 Microprocessor and microcontrollers.

A computer memory refers to any physical device that is capable of storing the data
or information either for a short time or permanently. Memories can be classified as
volatile memory or non-volatile memory. Random Access Memory (RAM) refers to the
volatile memory while Read Only Memory (ROM) belongs to the non-volatile memory
category. Solid state drives are one type of non-volatile memory. They can retain the
stored data even when they are not powered. Figure 1.14 represents the solid state drive.

Figure 1.14 Solid state drives (non-volatile memory).

I/O devices refer to the pieces of hardware used in order to communicate with the
computer. Keyboard and mouse are some examples of input devices through which the
computer programmer or user can provide inputs to the computer. Printers and monitors
refer to the output units. Other devices used for communication between the computers
include modems and network cards that can perform both input and output operations.
A bus is a communication medium that helps in transfer of data between different
components or peripherals in the system. The three different types of bus include:
▪▪ Control bus
▪▪ Address bus
▪▪ Data bus

Book 8.indb 12 6/7/2017 1:28:01 PM


Introduction 13

The size of the bus, also called width of the bus, determines how much amount of
data can be transmitted at any point of time. For example, an 8-bit bus can transfer 8
bits of data while a 16-bit bus can do 16 bits of data. Figure 1.15 represents the bus used
in computing technology.

CPU Memory Input and Output

Control Bus

Address Bus

Data Bus

Figure 1.15 Single system bus.

An address bus is a computer bus which contains a physical address. When the CPU
needs to read or write data to a particular memory, it specifies the address on the address
bus. The width of the same determines the capacity that the system can address. The
memory bus, on the other hand, connects the main memory to the memory controller
present in the computer systems.
For the purpose of communication between different devices, control bus is used.
The data bus will carry the data that is being processed in the system. Bus contention
is a common problem in computer architecture where more than one device try to place
value on the bus at the same time. This can lead to errors in results or sometimes even
damage the hardware.

1.6 NUMBER SYSTEMS

Number systems is a way to represent numbers. It defines a set of values used to


represent quantity. These number systems are classified in two broad categories:
▪▪ Non-positional number system
▪▪ Positional number system
Normal usage of fingers, pebbles, etc., for counting corresponds to non-positional
number system. Even Roman letters belong to this category. They are generally difficult
to represent as well as the calculations that can be performed with these are limited.
In case of positional number system, each and every quantity has a discrete
symbol. We can also perform calculations in a simple manner while using the
positional number system. Decimal number system is one good example for positional
number system. There are 10 different symbols to represent a particular quantity. For

Book 8.indb 13 6/7/2017 1:28:01 PM


14 Fundamentals of Computing and Programming

each and every position, we allocate one value and addition, subtraction, multiplication
and division will be performed.
Base, also called Radix, is a vital part in number system. The total number of discrete
symbols used in a number system will be identified by the base parameter. Table 1.2
represents the details of base.

Table 1.2 Radix in number systems


Number system (Radix) Representation

Decimal (10) 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9


Binary (2) 0 and 1

Octal (8) 0, 1, 2, 3, 4, 5, 6 and 7


Hexadecimal (16) 0 to 9 followed by A to F

The decimal number system has 10 as its base and is written 10 in decimal. It may
also at times used to represent the numbers that have an integer part along with a
fractional part detached by a decimal separator (e.g., 14.72).
In mathematics as well as in digital electronics, a binary number represents numeric
values using two different symbols – zero and one. It has a radix of two. All computers
and computer based devices use the binary system internally. Each digit is referred to
as a bit.
The octal number system corresponds to the base-8 number system and uses
digits ranging from 0 through 7. Computing systems like PDP-8 and IBM mainframes
used octal number system. Their word size is divisible by three and hence it was an
ideal abbreviation of binary for these machines. Octal number system is also used in
aviation engineering for the purpose of distinguishing different aircraft on the radar
screen.
Hexadecimal number system has the base of 16 and it uses 16 different symbols to
represent the values. It is a more human-friendly representation of binary coded values
as each of the digit in it represents four binary bits.
Most of the times in computing technology, there will be a need for conversion from
one number system to another number system. This includes decimal to other base
system, other base system to decimal, binary to octal, octal to binary, binary to
hexadecimal and hexadecimal to binary to name a few.

1.6.1 Decimal to Other Base System


The first step in this process is to divide the decimal number to be converted by the
value of the new base. Then we store the remainder from the above process as the right
most digit of the new base number. The quotient part is now divided by the new base
number. Store the remainder part as usual. Repeat the steps until the quotient becomes
zero.

Book 8.indb 14 6/7/2017 1:28:01 PM


Introduction 15

Example: Find the binary equivalent of the decimal number 58.

Table 1.3 Example for decimal to binary conversion


S. No. Conversion Quotient Remainder
1 58 / 2 29 0
2 29 / 2 14 1
3 14 / 2 7 0
4 7/2 3 1
5 3/2 1 1
6 1/2 0 1

The resultant binary value is taken in the reverse order. In this example, the binary
equivalent of the decimal value (58)10 is (111010)2.

1.6.2 Other Base System to Decimal


For converting other base system into decimal number system, we first find the positon
of the digit in order to determine the column value of each digit. We then multiply the
column values found in the above process by the digits in the column. We then add all
the computations together to find the decimal equivalent value.
Example: Find the decimal equivalent of the binary number (111010)2.

Table 1.4 Example for binary to decimal conversion

S. No. Binary Number Decimal Equivalent

1 ((1*25) + (1*24) + (1*23) + (0*22) + (1*21) + (0*20))10

2 (111010)2 Sum (32 + 16 + 8 + 0 + 2 + 0)10

3 (58)10

In this example, the decimal equivalent of the binary value (111010)2 is (58)10.

1.6.3 Octal to Non-Decimal


There are multiple methods available for converting the other base systems to non-
decimal systems. For example, if we want to convert from octal number system to
binary equivalent, the straightforward method would include a two-step process: (a)
first convert the octal number into a decimal number and (b) then convert the resultant
decimal number into a binary number. The same resultant can also be obtained using
a shortcut method is shown in Table 1.5.
The shortcut method converts each octal digit into a three-digit binary number.
Then we will combine all the resulting binary groups into a single binary number

Book 8.indb 15 6/7/2017 1:28:01 PM


16 Fundamentals of Computing and Programming

which would be the resultant value. This method will save the computation time as
compared with the two-step process discussed above.
Example: Find the binary equivalent of the octal number (50)8.

Table 1.5 Example for octal to binary conversion


S. No. Octal Number Binary Equivalent
1 510010

2 (50)8 1012 0002

3 (101000)2

In this example, the binary equivalent of the octal value (50)8 is (101000)2.

1.6.4 Binary to Non-Decimal


We use the same shortcut method for converting the binary number into a hexadecimal
value. We divide the binary digits first into groups of four. We always start from the
right for this purpose. Now assign the hexadecimal symbol to each of these groups
independently. Combine the results to get the output.
Example: Find the hexadecimal equivalent of the binary number (110101)2.

Table 1.6 Example for binary to hexadecimal conversion

S. No. Binary Number Hexadecimal Equivalent

1 0011201012

2 (110101)2 316516

3 (35)16

In this example, the hexadecimal equivalent of the binary value (110101)2 is (35)16.

1.6.5 Non-Decimal to Binary


Shortcut method is used here as well for converting the non-decimal number into a
binary number. We convert each independent hex digit number into a four-digit binary
number first. The output of this step is then followed by combining the resulting binary
groups into a single binary number.
Example: Find the binary equivalent of the hexadecimal number (35)16 using the
shortcut method.

Book 8.indb 16 6/7/2017 1:28:01 PM


Introduction 17

Table 1.7 Example for hexadecimal to binary conversion

S. No. Hex Number Binary Equivalent

1 310510

2 (35)16 0011201012

3 (00110101)2

In this example, the binary equivalent of the hexadecimal value (35)16 is (00110101)2.

1.7 ALGORITHMS AND PSEUDOCODE

For a computer to solve the problem, it needs a set of instructions. A set of rules or
process needs to be followed in calculations and these are defined as algorithms first
before being converted into a programming language that the computer can understand.
It is an effective method that can be expressed within a finite amount of time and space.
Algorithm is a step-by-step instruction to solve a problem. It always starts with input
data, does the processing and stops when we find the answer. They are essential to the
way computers process data. Some examples include algorithms for calculating staff
pay cheques, printing student report cards, bank account balance calculation, etc.
Algorithms can be represented in different forms including pseudocodes, natural
languages, flowcharts, unified description languages, programming languages or
through technical algorithms. Algorithms include the four processes including:
▪▪ Analyse
▪▪ Design
▪▪ Experiment
▪▪ Implement
There is also a wide variety of ways to represent the algorithms including the following:
▪▪ High-level description
▪▪ Implementation description
▪▪ Formal description
Most of the algorithms are written in order to be implemented as computer programs.
They can also be used for biological neural network modelling, electrical circuit for the
system to work or in a mechanical device. In computer technology, they are an instance
of logic written by software developers to get the desired output from the given input.
Let’s take an example. We start with writing a simple algorithm for finding the largest
number in a list of numbers present in a random order. We consider using a high level
description English language for this purpose:

Book 8.indb 17 6/7/2017 1:28:02 PM


18 Fundamentals of Computing and Programming

Step 1: If the set does not contain any number, then there is no largest number.
Step 2: If there are numbers in the set, then we start with the first number as the
largest number in the set.
Step 3: We start comparing the current number with the next number and see if it is
greater than the current number. If yes, then we replace the current number with the
next number else we will continue to use the current number as the largest number.
Step 4: Continue the process until we reach the last number in the set.
Step 5: Identify the largest number at the end of the process and output the result to
the user.
Having written the algorithm, the next step is to write the pseudocode for the above
algorithm that can help in converting the logic into the program that the computer can
understand.
A pseudocode is an informal high level description of an algorithm. It uses the
structural conventions of a high level programming language but the intention is mostly
to understand rather than for the machines to understand. Some essentials like variable
declarations, system specific codes, initial assignments, etc., will be omitted in the
pseudocode and are generally required while writing a program.
Pseudocode helps us to understand more than the traditional programming language
code which would be lengthier and have more machine specific information. Pseudocode
on the other hand will have only the core part of the algorithm or the actual logic needed
for implementation. There is no standard for pseudocode as it is not an executable.
Flowcharts, Unified Modelling Language (UML) and drakon-charts are seen as an
alternative to pseudocode.
Pseudocode is also called the pidgin code which is a mixture of different
programming languages in the same program. For example, we write the pseudocode
for the largest number identification as follows:

Algorithm Largest_Number_Identification
Input: Dataset that contains a list of numbers L.
Output: The largest number identified from the dataset L.
if L.size = 0 return null
largest ← L[0]
for each item in L, do
if item > largest, then
largest ← item
return largest

A computer program can be written using a pseudocode. It is a collection of instructions


which can perform a certain task when the computer executes it. We will write a simple
C program to find the largest number in a given list of data.

Book 8.indb 18 6/7/2017 1:28:02 PM


Introduction 19

// C Program to find the largest number in a given set of values


#include <stdio.h> //Library inclusion for standard I/O operations
int main()
{
int i, n; //Variable declarations
float arr[100];
printf("Enter total number of elements(1 to 100): ");
scanf("%d", &n); //Provide input to the program
printf("\n");

// Stores number entered by the user


for(i = 0; i < n; ++i)
{
printf("Enter Number %d: ", i+1);
scanf("%f", &arr[i]);
}

// Loop to store largest number to arr[0]


for(i = 1; i < n; ++i)
{
// Do the computations
if(arr[0] < arr[i])
arr[0] = arr[i];
}

//Display the output which shows the largest value


printf("Largest element = %.2f", arr[0]);
return 0;
}

One interesting thing in writing a program is to find the resource usage identification
in executing a program. This is also called analysis of algorithms. Analysing an algorithm
helps us optimize the program and execute the same with limited resources thereby
saving cost and time.
Mathematical notations like Big O, Omega, theta, etc., are used in analysing the
algorithms. They help in classifying the algorithms according to their execution time
and memory requirements. Algorithms can also be classified by implementation as
recursive, logical, serial, parallel or distributed, by design paradigm as divide and
conquer, search and enumeration, by field of study and by complexity as constant time,
linear time, logarithmic time, polynomial time and exponential time.

Book 8.indb 19 6/7/2017 1:28:02 PM


20 Fundamentals of Computing and Programming

1.8 FLOWCHARTS

A flowchart is a diagrammatical representation of an algorithm workflow or a process.


It shows the steps as boxes of different shapes and their order as well through connecting
arrows. They are used in analysing, documenting, designing and managing the process
in various fields.
Flowcharts represent certain aspects of the processes and are also supplemented by
other types of diagrams like histogram, control chart, cause-and-effect diagram and
scatter diagram, to name a few.

START

Mixer does not work

No
Is Mixer Plug in
plugged in? Mixer

Yes

No
Replace
Burnt motor?
Motor

Yes

Repair Mixer

STOP

Figure 1.16 Flowchart representing a mixer issue.

Book 8.indb 20 6/7/2017 1:28:02 PM


Introduction 21

Figure 1.16 represents a simple flowchart for a mixer issue. It contains different
symbols each representing an action to be performed. This gives a clear indication for
the user to understand the different steps involved in solving the problem.
The two most common boxes used in a typical flowchart are:
▪▪ A processing step denoted by a rectangular box
▪▪ A decision step represented by a diamond box
There are also other boxes used in flowcharts for different purposes. These are listed
in Table 1.8.

Table 1.8 Building blocks in flowchart

SHAPE NAME DESCRIPTION

This is used to represent the “Start” or “end” of the


Terminal program execution. They are generally represented as
circles, stadiums, ovals or rounded rectangles.

Represents the control that passes from one box to


Flow line another. The line can be either solid or dashed
depending on the usage.

Parallelogram is used to represent the input / output


Input / Output operations. It involves data being received and also in
displaying the processed output.

Process is represented by rectangles. Most of the


Process computations are represented inside this box. Addition,
saving changes, etc., are some examples.

Whenever a decision is to be made, this diamond box is


used. It will have two outputs – yes and no. Usually,
Decision
the bottom point and the right point are used for these
true/false condition related process.

Rectangle with vertical edges struck is used to represent


Predefined
a predefined process. Process-files before proceeding is
process
one such predefined process.

Circles represent the connector. Generally, has more


Connector than one arrow coming on to it but mostly only one
goes out. Iterative processes use this connector.

There are also other kinds of symbols or shapes used but are not common in usage.
They are listed below:

Book 8.indb 21 6/7/2017 1:28:02 PM


22 Fundamentals of Computing and Programming

▪▪ Labelled connectors
▪▪ Concurrency symbols
▪▪ Annotation
▪▪ Preparation symbols
A wide variety of tools can be used for drawing a flowchart and there is no specific
tool to be used for this purpose. Some of the commonly used tools for drawing flowcharts
are Microsoft Visio, Inkscape, etc. Software packages are also available in the Internet
that can draw flowcharts automatically from the source code of the programming
language or from the flowchart description language.

1.9 COMPUTER SOFTWARE AND ITS TYPES

Software is a part of a computer system that consists of data or computer instructions


and is different from the hardware part of the computer. Computer programs, libraries
and non-executable data are all considered to be part of the computer software. Hardware
and software require each other to work in co-operation without which the machine
would become useless. The two main types of software are:
▪▪ System software
▪▪ Application software
System software is a type of computer program that is designed in order to run a
computer’s hardware and application programs. It is an interface between the physical
hardware unit and the user created applications. Operating systems, computational
science software, industrial automation and software as a service are examples of system
software.

User

Application Software

System Software

Kernel and Hardware

Figure 1.17 Computer hardware-software architecture diagram.

Book 8.indb 22 6/7/2017 1:28:03 PM


Introduction 23

Application software on the other hand is a program to perform a task for the benefit
of the end user. Internet browsers, word processors, Google map applications, spread
sheets, photo editors, media players, etc., are examples of application software.
Application software are sometimes bundled as part of the system software package
itself or provided separately and may be called open source or closed source software.
The application software that are built for smartphones like Android and Apple phones
are called mobile apps.
The executable code contains all the instructions that are necessary for the Central
Processing Unit (CPU) to perform. The processor executes the instructions in the
sequential order unless it is asked to jump to a particular piece of code or a set of
instructions. High-level programming languages are used for writing majority of the
software these days as they are easier and more efficient.
Compilers and interpreters help translate the high-level language written software
into machine language and sometimes the user may also write the software using
assembly language and in which case, assembler will be used to convert the assembly
code into machine code for the system to understand and respond. Figure 1.18 discusses
the software types in detail.

Types of software

Purpose based Domain based Programming tools based

 Application software  Desktop apps  Compilers


 System software  Java scripts  Debuggers
- Operating system  Server software  Interpreters
- Device drivers  Plugins  Linkers
- Utilities  Embedded  Loaders
 Malicious software software  Text editors

Figure 1.18 Software types.

People using modern computers which are general-purpose type see three layers of
software doing a set of tasks, namely:
▪▪ Platform software
▪▪ Application software
▪▪ User written software

Book 8.indb 23 6/7/2017 1:28:03 PM


24 Fundamentals of Computing and Programming

The platform software includes different layers of code like the firmware, device
driver, board support packages, operating system and a graphical user interface. This
allows the user to interact with the computer hardware and its associated peripherals.
Application software are generally purchased along with the computer hardware.
Office suites and video games are considered to be application software by the end
users. They run as independent applications even if they are bundled as part of the
computer.
User software generally corresponds to spreadsheet templates and word processor
templates. Email filters are also considered to be a part of user software. At times, it is
difficult to differentiate between the user software and the application software.
The other software terminologies are given in Table 1.9.

Table 1.9 Software terminologies

SOFTWARE
DESCRIPTION
TERMINOLOGY

The software has to be loaded into the storage before executing the same.
Software Execution The control gets transferred from the application software through the
system software and all the way to the hardware.

Software quality refers to the whole functionality and features of a software


Software Quality
product that tolerate on its ability to fulfil stated or implicit needs.

Testing refers to the investigation on the software product and give the
Software Testing information to the stakeholders on the quality of the product or service
under test.
Reliability refers to failure-free software operation for a specified time in a
specified environment on which it is supposed to run. It is an important
Software Reliability factor that will decide on the system reliability. Software reliability testing
benefits to determine different problems in the software design and
functionality.
Licence is a legal instrument that governs the use of the software or the
Software Licence redistribution of the same. It also guides the purchaser on its usage and his
rights to do bug fixing and enhancements on the provided software.
Though there is no legal or standard definition for a software patent, there
is a debate on the extent to which a software patent can be granted. One of
Patents
the first software patents was issued for effective memory management of
the simplex algorithm in 1966.
Software organizations could be either a profitable one or a non-profit
Industry and organization. Non-profit ones include Free software foundation, GNU
Organizations project and Mozilla. The well-known software industry giants include
Oracle, SAP, Adobe systems, Symantec and Corel to name a few.

Book 8.indb 24 6/7/2017 1:28:03 PM


Introduction 25

The complexity of the software decides the design and implementation of the same.
Microsoft Word takes more time than Notepad to design and implement due to the
reduced set of features in the Notepad as compared to the Word processor. Different
data structures are used in creating the software. They are arrays, binary trees, hash
tables, linked list, etc. to name a few. Bug-free software is the dream of every coder and
the software industry but the end users and software testers think otherwise.

1.10 INTERNET TERMINOLOGY

Internet refers to interconnected networks. The term Internet refers to the hardware
including the cables, fibre, phone lines, routers, etc., to name a few. Browser is actually
the software part that is used to view the web pages on the display. Microsoft Internet
explorer, Mozilla Firefox, Apple safari and Google chrome are some examples of browsers
used across different operating systems.
Web page refers to the single screen of data that the user sees on loading a website.
Here the term website corresponds to all related web pages for an organization or
individual. The first page of a website is called the home page while the subsequent
pages refer to child pages.
The content of the web pages actually comes from the web server which is a specific
type of computer where web pages are stored and made available for the public to view
and use. HTML (Hypertext Markup Language) is the basic code of web pages. Protocol
refers to the set of rules and HTTP (Hyper Text Transfer Protocol) is the protocol used
in Internet terminology. Figure 1.19 represents the different applications that we use in
our daily life and are based on the Internet as well.

Figure 1.19 Applications based on the Internet.

The URL (Uniform Resource Locator) refers to the address of a web page. The different
parts of a URL can be broken down as follows:
For example: https://en.wikipedia.org/wiki/Main_Page contains different fields
listed as:

Book 8.indb 25 6/7/2017 1:28:03 PM


26 Fundamentals of Computing and Programming

▪▪ http:// corresponds to protocol


▪▪ en.wikipedia.org represents the domain name of the website
▪▪ /wiki/ relates to the folders of the website
▪▪ Main_Page corresponds to the filename of the web page.
The computer network types can be classified according to their working principle
and the application as follows:
▪▪ Nanoscale
▪▪ Near Field Communication
▪▪ Personal Area Network
▪▪ Near-me Network
▪▪ Local Area Network
▪▪ Campus Network
▪▪ Backbone
▪▪ Metropolitan Network
▪▪ Wide Area Network
▪▪ Cloud Network
▪▪ Internet and Interplanetary Internet
The regional Internet registries allocate the IP addresses for different regions and
this include the African Network Information Centre (AfriNIC) for Africa region,
American Registry for Internet Numbers (ARIN) for North America region, Asia-Pacific
Network Information Centre (APNIC) for Asia and the Pacific region, Latin American
and Caribbean Internet Addresses Registry (LACNIC) for Latin America and the
Caribbean region, Réseaux IP Européens – Network Coordination Centre (RIPE NCC)
for Europe, the Middle East, and Central Asia region accordingly.

Printer
The Internet

Switch
Router
Server

Figure 1.20 Building blocks of the Internet.

There are different blocks in building an Internet as represented in Figure 1.20.


The World Wide Web is the primary application used on the Internet by billions

Book 8.indb 26 6/7/2017 1:28:04 PM


Introduction 27

of people and the Internet also provides many other services. The web has also helped
the organizations and the individuals to publish their ideas to a larger set of audience
at greatly reduced time and cost. There is only a little cost or no cost involved in many
cases for publishing a web page, a blog or creating a website.
Email is the best communication service that is available on the Internet and they
carry text, pictures, documents and other files as an attachment with them. They can
also be accessed to multiple email addresses at the same time. Internet telephony is
another commonly used Internet service by a large set of users. Voice over Internet
refers to the protocol that underlies all Internet communications. Ventrilo and Teamspeak
are popular VoIP clients.
Streaming the media like video is the real-time delivery of digital media for the
immediate usage by the end users. Live audio and video productions are provided by
many radio and television broadcasters. Preview, Listen again and classic clips are
different features offered by them. Content availability has also become wider from
specialized technical webcasts to on-demand popular multimedia services.
Digital media streaming increases the network bandwidth demand. For example, to
stream a standard definition (SD) 480p video, it needs 1 Mbit/s link speed, HD 720p
quality requires 2.5 Mbit/s while the top-of-the-line HDX quality requires 4.5 Mbit/s
for 1080p. A webcam that feeds or streams the video frame in real time through a
computer to a computer network are a low cost extension of this phenomenon.
The Internet service providers across the world are responsible for establishing the
worldwide Internet connectivity between individual networks at different scope levels.
The end users belong to the bottom of the routing hierarchy. Tier 1 networks, large
telecommunication companies, etc., belong to the top of the hierarchy.
80 +
78
76
73
70 71
Developed world 67
World globally 63
60 61
Developing world 59
54
50 51
46
40 42 40
+

38 38
36 36
33
30 31 30 30
32
+

27
24 26 24
23
20 21
21
17 18 17
16 15
14 12
10 11 11
12
9
7 8 7 8
5 4 6
2 3 3
0 2
0 1 1
1996 1998 2000 2002 2004 2006 2008 2010 2012 2014
+
Estimate

Figure 1.21 Internet users per 100 inhabitants.


Image Courtesy: https://en.wikipedia.org/wiki/Internet

Book 8.indb 27 6/7/2017 1:28:04 PM


28 Fundamentals of Computing and Programming

The number of Internet users globally rose from 394 million to 1.8 billion until the
year 2009. There are about 1 billion Google searches every day and around 300 million
people are reading blogs in the Internet. Also around 2 billion videos are watched on
YouTube. Two-thirds of the Internet users come from richest countries with 78% of
people from Europe using the same while Americans use it for about 57.4%. English is
the commonly used language in the Internet. Chinese, Spanish, Japanese and German
languages are used next to English.
There are different methods of getting connected to the Internet and this includes
usage of dial up networks through a modem via telephone circuits, fibre optics,
broadband over coaxial cables, Wi-Fi, satellite and through cellular telephone technology
like 4G. The unmetered high-speed connections allow greater flexibility for the Internet
users in working hours and locations. They can be accessed at places like libraries and
cafes. These days, we get internet access points across different public places like airport
halls, coffee shops, malls, etc., to name a few.

KEY POINTS TO REMEMBER

•• A computer is an electronic device that takes input from the user, processes it
using the internal processing units and produces the final output in the form of
information or signals.
•• The four basic types of computer are:
▪▪ Supercomputer
▪▪ Mainframe computer
▪▪ Minicomputer
▪▪ Microcomputer
•• The different characteristics of computer include:
▪▪ Speed
▪▪ Accuracy
▪▪ Diligence
▪▪ Versatility
▪▪ Storage capacity
•• There are a total of five generations of computers till date and the first generation
computers used vacuum tubes as circuitry and magnetic drums for storage
purposes.
•• According to the purpose, computers can be either general-purpose computer or
a specific-purpose computer.
•• Based on the functionality, computers are classified as analog computer, digital
computer and hybrid computer.
•• The Central Processing Unit in the computer is responsible for interpreting
and executing the commands from the hardware and software.

Book 8.indb 28 6/7/2017 1:28:04 PM


Introduction 29

•• The popular CPU manufacturers are Intel and AMD for desktops, laptops and
servers. Apple and Qualcomm are smartphone and tablet CPU makers.
•• The Arithmetic and Logic unit (ALU) is responsible for performing the arithmetic
operations like addition, subtraction, multiplication and division along with the
logical operations like AND, OR, NOT, NOR, XOR as well.
•• A number system is a way for representing the numbers. The different types of
it includes are:
▪▪ Decimal
▪▪ Binary
▪▪ Octal
▪▪ Hexadecimal
•• The radix or base is the number of unique digits to represent numbers in case of
a positional numeral system.
•• Positional number system and non-positional number system are the two types
of number system used in practice.
•• An algorithm is a sequence of actions to be performed including calculation, data
processing and reasoning tasks.
•• Pseudocode is an artificial language that helps the programmers to develop the
algorithms. It is detailed and at the same time readable description of what a
computer program is supposed to do.
•• Flowchart is a graphical representation of a computer program and is represented
by different kinds of boxes connected through an arrow.
•• An oval represents a start or end point in a flowchart. It is the first and the last
box used in most flowcharts.
•• A line is a connector that represents the relationships between the different boxes
and controls the flow of code.
•• A rectangle represents a process in a flowchart. Any sort of computation in the
program is performed in this.
•• Software is a part of a computer system that contains instructions for the machine
to perform. It includes:
▪▪ Computer programs
▪▪ Libraries
▪▪ Related non-executable data
•• High-level programming languages are generally preferred for writing the software
and that is closer to a natural language.
•• A compiler is a software program that helps convert the source code written in
one language to the other. It is carried out to create an executable program.
•• An interpreter is a program that directly executes the instructions without any
necessity to compile them into a machine language program.

Book 8.indb 29 6/7/2017 1:28:05 PM


30 Fundamentals of Computing and Programming

•• Assembly is a low-level programming language. It is converted into an executable


machine code by a utility program referred to as an assembler.
•• The process of finding and resolving the defects that are responsible for stopping
the software from working properly is called debugging.
•• Different aspects of debugging include interactive debugging, control flow,
integration testing, etc.
•• Interactive debugging, Print debugging, Remote debugging, Post-mortem
debugging and delta debugging are the different types of debugging a computer
software.
•• Software quality plays a vital role in selling the software. Buggy software will
create loads of issues for the company thereby losing their value in the market.
•• Microsoft windows, Linux, iOS are some examples of system software widely used
in the industry.
•• System software and application software are the two major types of computer
software used in practice.
•• Examples of application software include:
▪▪ Database programs
▪▪ Word processors
▪▪ Spreadsheets
▪▪ Web browsers
•• Computer software gets loaded into the memory before getting executed.
•• Software licence decides the rights of the end user to use the software and modify
the same for any enhancement and bug fixing purposes.
•• Internet refers to the global computer network providing communication facilities
and different information using standard protocols through interconnected
networks.
•• Internet uses the Internet protocol suite (TCP/IP) to link the different devices
present throughout the world.
•• The Internet has enabled different forms of social interaction and activities and
has seen tremendous growth over the past decade.
•• File sharing is an example for transferring the data across the Internet. A file can
be emailed to customers or friends as an attachment.
•• Security is the major concern in the Internet world. Hardware and software
components are the target of criminals to gain unauthorized control for the purpose
of causing interruptions or to access private information.

Book 8.indb 30 6/7/2017 1:28:05 PM


Introduction 31

EXERCISE

1. What is the major role of computer in the society and working environment?
2. Differentiate between input, output and storage devices in detail along with
examples.
3. What are the different characteristics of the computer?
4. Explain the different components used across different generations of computing
technology.
5. Detail the advantages of using transistors over vacuum tubes along with example.
6. How do you classify computers based on their usage?
7. What is the difference between an analog and digital computer?
8. How is a computer organized?
9. Differentiate between program storage and data storage.
10. What is a bus and how is it useful for data transfer?
11. How do CPU and ALU differ in terms of their functionality?
12. What is a memory and what are the different types of memories in a computer?
13. What are the different types of number systems? Differentiate between them with
examples.
14. Find the binary equivalent of the decimal number (42)10.
15. Calculate the decimal equivalent of the binary number (1111)2.
16. Find the binary equivalent of the octal number (40)8 using the two-step process.
17. Using shortcut method, compute the hexadecimal value of the binary value
(0101010)2.
18. What is meant by an algorithm and how do you classify algorithms?
19. Define pseudocode with an example.
20. Write an algorithm, pseudocode and flowchart to check if a number is prime
number or not.
21. What is a drakon-chart and how is it useful?
22. What is a computer software and what are its different types?
23. What is a flowchart and why it is used?
24. What are the different symbols used in flowchart?
25. What are the tools that are used for drawing the flowcharts?
26. Define the Internet and its uses.
27. What are the different protocols used in the Internet terminology?
28. What is a URL and what are the different parts of it?
29. What is a web page and where is it saved?
30. What is the role of a Internet Service Provider?

Book 8.indb 31 6/7/2017 1:28:05 PM


2 C PROGRAMMING

LEARNING OBJECTIVES

After reading this chapter, the reader would be able to understand:


•• To learn the history of C language.
•• To be familiar with writing a basic C program.
•• To be able to compile and execute a C program in both Windows and Linux OS.
•• To be able to solve mathematical problems involving variables, keywords,
constants, etc.
•• To understand the way various operators work.
•• To be able to distinguish between data types.
•• To write a program that involves decision making and looping.
•• To be familiar with the constructs of a C program.

2.1 INTRODUCTION

C is a sequel to two other languages, namely, BPCL and B. BPCL stands for Basic
Combined Programming Language that Martin Richards developed in 1967. B language
was developed little later in 1970 by Ken Thomson, which was also used in the
development of early versions of UNIX. Later, C was born which has now become a
commonly used programming language. Dennis Ritchie’s hard work and tireless efforts
were reasons behind the evolution of C. Not only B, it was also C language which was
primarily used to build most secured, robust operating system UNIX. Hence, it is no
wonder to learn a language like C that can even be used to create an operating system.
Note: UNIX was not the name given to it. It is basically UNICS—UNiplexed
Information and Computing System.
Having seen the impact that C has created, ANSI (American National Standards
Institute) came up with standards for the language, which is even prevalent today. Of
late, we started addressing C as ANSI C. This book wholly talks about the ANSI standard
C. In the next section, let’s learn the characteristics of the language.

Fundamentals of Computing and Programming

Book 8.indb 32 6/7/2017 1:28:05 PM


C Programming 33

2.2 FUNDAMENTAL RULES

•• Every C statement should end with a semicolon, otherwise it throws error.


•• We cannot club two statements together. Every statement should be split with a
semicolon.
•• The code has to be written in lower case. Using upper case would result in an
error.
•• Keywords should not be used as identifiers.
•• Any function is enclosed within curly braces { }
•• C is a case-sensitive language. This means that ‘A’ is different from ‘a’
•• Single line comments in C language are preceded with //
•• Multiline comments are enclosed between /* and */

2.3 STRUCTURE OF A C PROGRAM

Any C Program is composed of the following parts:


•• Preprocessor Commands (for using header line stdio.h, conio.h, etc. and for
declaring constants)
•• Functions (to modularize the code and for reusability)
•• Variables (to handle inputs and outputs)
•• Statements and Expressions (for performing analytical operations)
•• Comments (for providing readability)
We shall write a sample code to explain these. Please refer to Program 2.1

Program 2.1 Sample C program

Book 8.indb 33 6/7/2017 1:28:06 PM


34 Fundamentals of Computing and Programming

In the above Program 2.1, we started the program with declaring preprocessor
directive <stdio.h> which is used for performing standard input, output functions
like scanf and printf in C.Next, we have declared the main() function which is
the entry point for any program. Then we have opened curly braces to write the actual
piece of code.
Next, we declared two integer variables number1 and number2. First printf()
prints Hi Welcome to C Programming, let’s do Addition to the output window, along
with one line feed. Next printf() and scanf() is meant to receive input for number1
from the user. In the same way, number2 value is also obtained from the user. Finally,
we printed the sum of number1 and number2 and printed it on the output window.
We finish off the program by curly brace!

2.4 COMPILATION AND LINKING PROCESS

2.4.1 With Linux (Same Method for Solaris/Unix/Ubuntu)


Once we are done with the coding, we need to compile it to check for syntactical errors.
In the programming languages like Java, C#, while we type the code, the compiler itself
will highlight the errors in syntax. But in C language, we need to manually compile
before executing it, in this section, we will discuss the ways to do it.
We can use two platforms for compiling and executing a C program, one is Linux
which stands a common practice. Second one is windows platform. We shall see how
to do it in Linux platform now.
We have a simple program to say Hi Let’s learn compilation in program 2.2. To
compile in Linux platform, we have a toolkit called GNU which has GCC compilers,
which is nothing but Gnu C Compiler.
// Name the file as prog1.c and save it. User can use the command ‘vi prog1.c’
to open a file in linux.

Program 2.2 Execution in linux

Before we can actually see the steps to compile, let’s look at some basics.
•• When we do compilation, the compiler verifies the correctness of the program in
syntax perspective. In case our program looks fine in syntax, compilation succeeds
and a file with extension . o (oh) is created which is called object file.

Book 8.indb 34 6/7/2017 1:28:06 PM


C Programming 35

•• Next step is to create an executable file with extension .exe after linking the code
with necessary header files.
Commands for doing all the above steps are listed below.
$ gcc –c prog1.c
In the LINUX environment, if we type the above statement, we just instruct the gcc
compiler to go ahead and compile the program prog1.c. Since the code doesn’t have
any syntax error, the compilation would be successful and thereby creating object file
prog1.o. Then we should generate executable file, by using the below given command
where we perform necessary linking with library files,
$ gcc –o execfile prog1.o
Finally, we execute the program by using the below command
$ ./execfile
Once we press enter, we will see a message on the window, “Hi let’s learn
compilation”. Let’s show the above steps in a diagrammatic representation in Figure
2.1 below.

prog1.c

$gcc -c prog1.c
prog1.o

$gcc -o execfile prog1.o


execfile

./execfile

Figure 2.1 Flow representation of the compilation process.

Well, it is not always necessary to follow the above three steps to execute a program.
It can also be achieved with the below given command as well which saves us a step,
without having to generate object file.
$ gcc –o prog1.c
The above statement will create a file called a.out. when we execute the command
./a.out in the linux prompt, the code gets executed and brings us the results.
Note: If we have multiple c programs in the same directory, the .out file is kept
overwritten. In order to overcome this issue, we can rename the out file as follows
$ gcc –o execfile prog1.c
Once this command is executed, we will get an executable file, which can be run as
./execfile. We are done with LINUX based compilation and execution. Next, we
will look at windows based execution.

Book 8.indb 35 6/7/2017 1:28:06 PM


36 Fundamentals of Computing and Programming

2.4.2 Windows Based Execution


Turbo C Compiler is the most sought after compiler along with Borland C, Dev C++.
We have taken up Turbo C Compiler here. Steps are given below:
•• Save the program extension .c
•• Compile the program using ALT + F9.
•• In case of no errors, execute the program using CTRL+F9. In case of errors, correct
the errors and execute the program.
Note: In software industry, LINUX and gcc compiler is used widely. So start practicing
in it.

2.5 CONSTANTS, VARIABLES, KEYWORDS, IDENTIFIERS AND DELIMITERS

2.5.1 Constants
When something doesn’t change, we call it a constant. In C, if we know that the value
of a variable is not going to change in the program, we can declare it as constants. It
can be of any type, including Octal, hexadecimal, integers or characters.
•• Octal constants are preceded by a zero, for example - 012.
•• Hexadecimal constants are preceded by 0x, for example - 0x1bc.
•• Character constants are enclosed in single quotes, for example, ‘a’, ‘b’, ‘c’.
But few characters like special characters need extra attention. We prefix them with
a backslash. Those characters are termed escape sequences.
Table 2.1 has the escape sequences listed.

Table 2.1 Escape sequences

Book 8.indb 36 6/7/2017 1:28:07 PM


C Programming 37

•• String constants are nothing but a series of characters enclosed in double quotes,
for example – “CONSTANTS”. Please note that, at the end of each string constant,
\0 is appended by default to identify the end of the string.

Defining Constants
We declare constants by using the keyword const. We can declare in following manner.
int const intVar = 10;
const int intVar = 10;
In addition to the above format, we can declare constants using preprocessor directives
as well. We can use #include directive to declare constants. Following are a few examples.
# define UP 100
# define DOWN -100
# define PI 3.14

2.5.2 Variables
In any C program, variables play a vital role in implementing any logic. But before
using a variable, it is mandatory that we declare it. We can declare it in the beginning
of any code block. With respect to functions, local variables are created while we call
the function and are destroyed when the control goes back to the calling statement. A
variable declaration begins with the data type of the variable succeeded by the names
of variables. For instance,
int top, bottom;
where int is the data type and top, bottom are the variables.

C language allows us to assign some values to the variables when we declare it. This
technique is termed declaration cum initialization. This is achieved by assignment
operator (=) and the value to be assigned. Few examples are given below.

int top = 100; /* Maximum Temperature */


int bottom = -20; /* Minimum Temperature */

Fine, with variables, we have two different scopes—local and global variables. Scope
is nothing but till where the variable is accessible.
Variable whose scope gets ended within a block or a function where we declare it is
termed local variables. We always declare local variables at the top of a block, not in
the middle. These local variables are valid or alive only within the block where declared.
Once the control comes out of the block, the variable becomes inaccessible.
Program 2.3. explains the local variable concept.

Book 8.indb 37 6/7/2017 1:28:07 PM


38 Fundamentals of Computing and Programming

Program 2.3 Local variables demo program

This will generate the following output


i is 11
i is 100
i is 11

Global Variables
As the name indicates, when we want some variables to be accessible across any part
of the program, we declare them at the top of a program which is termed global variable.
It should be noted that, the declaration of variables cannot precede preprocessor directives
(for example, #include <stdio.h>). We can declare a local variable in the same
name as global variables. For example, in the following piece of code, we have declared
a global variable called ‘i’ and in the function(), we have declared a local variable

Book 8.indb 38 6/7/2017 1:28:09 PM


C Programming 39

of same name. When control goes to function(), precedence is given to the local
variable value, which is 100. We can see global variables in use in Program 2.4.

Program 2.4 Global variables in C programming.

This will give the following result on execution.


Value of i = 101 from function
Value of i from Main = 2
For security reasons, in recent programming trends, the programmers are asked not
to overuse global variables. One special character for global variables is, when we declare
the variables, it gets automatically initialized with a default value. Table 2.2 describes
the default values for various data types.

Table 2.2 Default initialized values


Data Type Initializer
Int 0
Char ‘\0’
Float 0

2.5.3 Keyword
As mentioned in the introduction, there are a few reserved words for internal processing
purposes which are termed keywords which should not be used as variables. Every
keyword has a meaning associated with it and cannot be overwritten with a different
meaning.
Table 2.3 lists down the keywords in C language. These keywords cannot be used
by the programmer for his own logic like declaring a variable/ function with a reserved
word. One more thing to remember is that it is a practice to write the keywords in
lower case!

Book 8.indb 39 6/7/2017 1:28:10 PM


40 Fundamentals of Computing and Programming

Table 2.3 C Programming keywords

In addition to the above keywords, Table 2.4 lists down a few more keywords which
are supported by a few compliers.

Table 2.4 C Programming keywords – Few more

2.5.4 Identifiers
Identifiers are used to identify elements of a C program. For instance, a variable (int
a =10, where a is an identifier), function (void sum() where sum is an identifier) or
an array (char[] a where a is an identifier). We can declare identifiers with letters,
digits and symbols. But, while declaring identifiers, we need to keep certain things in
mind which are listed below.
a. Any identifier should start with an alphabet (can be lower or upper case) or an
underscore. For example: _temperature
b. Identifiers in ‘C’ are case sensitive. This means that, A and a are not the same,
NAME and name are not the same.
c. We should not declare any identifier from the reserved words, for example, while/
do/ if, etc.
d. Using two underscores successively is not allowed.
Some of the valid identifiers are given in Table 2.5.

Table 2.5 Identifiers – Few examples


X_identifier y_123 degree_celsius _farenheit
Name_C Program_c name sum

2.5.5 Delimiters
Delimiters are used by many programming languages to segment data for better
interpretation. For instance, in the below example, the names are delimited by comma.

Book 8.indb 40 6/7/2017 1:28:11 PM


C Programming 41

Char[] names = {“Sachin”, “Sehwag”,”Gambhir”};


In C, we have the following delimiters
Colon : For naming labels
Semicolon ; For terminating statements
Parenthesis () For building expressions and defining function
Square brackets [] For declaring arrays
Curly braces {} For determining the scope
Hash # For declaring preprocessor directives
Comma , For separating variables

2.6 DATA TYPES

C provides support for a wide variety of data. For instance, character, integer, float, etc.
Each of these data types has its own properties. Each one occupies a different amount
of memory. Let’s look at 3 classifications of the data types in Figure 2.2.

C Data Types

Primitive Derived

Figure 2.2 Data types supported in C programming.

2.6.1 Primary Data Types


These are otherwise termed built-in data type, which means that they are the basic data
types in C which are the building blocks of any program.
Following data types fall under this category.
1. int (integer)
2. float (Floating point representation (Real))
3. double (Double precision real number)
4. char (Character representation) and
5. Void
Table 2.6 details the characteristics of the above data types.

Book 8.indb 41 6/7/2017 1:28:11 PM


42 Fundamentals of Computing and Programming

Table 2.6 Data types

Let us look about these data types in detail.


a. int: whenever we want to refer to a whole number, we declare the variable to
be an integer. The value assigned to an INT variable should not have decimal
points in between. In case if we try doing so, it will result in a truncation. When
we talk about the range which is supported by ‘int’ data type, it purely depends
on word length of the computers. For instance:
•• In a 8-bit computer, the range is –28–1 to 28–1 –1, in other words, –128 to 127.
•• For 16-bit computers it is –216–1 to 216–1 –1 which is –32,768 to + 32,767.
Similarly, we can calculate the range for a 32-or 64-bit computers. Following examples
in Table 2.7 are some valid and invalid values for “int” variables.

Table 2.7 Valid and invalid integer representations

Integer has got so many variants for it. They are:


a. int
b. signed int

Book 8.indb 42 6/7/2017 1:28:13 PM


C Programming 43

c. unsigned int
d. short int
e. long int.
Each of the above data type differs in the range that it can support. Table 2.9 lists
down the range supported by all the primitive data types.
b. float: we saw that integers support whole numbers. Float is just opposite to int,
it is meant for handling floating point numbers, in other words, decimal values.
There are two ways of representing float numbers:
1. exponent
2. decimal
double is similar to float, but it provides supports to a wider range of decimals.
It can support till 14 digits. In other words, its precision support is 14 digits. So,
when we have to deal with a number that doesn’t go with float, declare them as
double. In addition to double, there is something called long double which
provides even bigger precision support. Few compilers in the market do support
long double. Some sample float representations are given below in Table 2.8.

Table 2.8 Valid and invalid float representations

c. char: next to digits, we will now see the char data type. If we want to store a
single character to a variable, we will have to declare it a char variable. If we
have to store a series of characters, then it is termed string. For instance, ‘M’ is
a char type value. “Madam” is a string value. Any character value would occupy
1 byte in the memory. Character values should be enclosed in single quotes. For
example, ‘L’, ‘0’, ‘j’, etc. Whatever be the character, there will be an associated
ASCII value equivalent to it.
For example,
•• Character ‘A’ is equivalent to 65 in ASCII code
•• Character ‘a’ (lower case) is equivalent to 97
•• ‘1’ is equivalent to 49 and so on.
Ranges supported by all the primitive data types are mentioned in Table 2.9.

Book 8.indb 43 6/7/2017 1:28:13 PM


44 Fundamentals of Computing and Programming

Table 2.9 Data type modifiers and ranges

Let us learn through a simple C program to determine the size of different data type
values. Following code 2.5 depicts a sample

Program 2.5 Size of data types

The output of the above code would be as follows in Output 2.1.

Output 2.1 Output for the program 2.5

Book 8.indb 44 6/7/2017 1:28:15 PM


C Programming 45

Having seen the primitive data type, we will see the derived data types.

2.6.2 Derived Data Types


These data types are derived from primitive data types. For example, arrays, structures
and pointers. We will deal with arrays in detail in chapter 3, Pointers in chapter 4 and
about Structures and Unions in chapter 5.

2.7 OPERATORS

In any programming language, operators play a vital role in implementing any operation.
There are different types of operators. This includes the following:

2.7.1 Arithmetic Operators


This includes addition (+), subtraction (–), multiplication (*), division (/) and modulo
(%) operator. Addition operator helps us perform sum operation while subtraction
operator is for performing minus operation. Multiplication is to perform product of
numbers while division is to divide one number by another number. Mod operators
divide one number by another number and give the reminder. Let us look at a program
to see usage of these operators in Program 2.6.

Program 2.6 Arithmetic operators

In the above program, we are getting two numbers from users and perform arithmetic
operators on the same. The output of the above code would be as follows (Output 2.2).

Book 8.indb 45 6/7/2017 1:28:16 PM


46 Fundamentals of Computing and Programming

Output 2.2 Output of Program 2.6

2.7.2 Assignment Operators


There is no C program without assignment operator. So does it mean that we have
already seen this operator? Yes, obviously. Wherever we have used =, we have used
assignment operator. = is called assignment operator. They are a few shorthand operators
associated with the assignment operator. They are as follows.

•• += (for example, a+=b, otherwise written as a= a+b)

•• – = (for example, a-=b, otherwise written as a= a-b)

•• * = (for example, a*=b, otherwise written as a= a*b)

•• /= (for example, a/=b, otherwise written as a= a/b)

•• %= (for example, a%=b, otherwise written as a= a%b)

2.7.3 Logical Operators


AND, OR, NOT are logical operators available in C.
•• AND operator is && - it works on two operands. Only if the two operands are
evaluated to be true, the statement becomes true. If either of them is false, the
expression is evaluated to be false. Truth table is as follows in Table 2.10.

Book 8.indb 46 6/7/2017 1:28:17 PM


C Programming 47

Table 2.10 AND truth table

•• OR operator is || - this too works on two operands. If either of the operands is


evaluated to be true, the statement becomes true. If both of them are false, the
expression is evaluated to be false. OR truth table is given in Table 2.11.

Table 2.11 OR truth table

•• NOT operator is !– It works on one operand. It is used to negate the operand’s


sign. If the operand is true, it makes it false. If the operand is false, this operator
makes it true. Truth table for NOT is as follows in Table 2.12.

Book 8.indb 47 6/7/2017 1:28:19 PM


48 Fundamentals of Computing and Programming

Table 2.12 NOT truth table

A sample program is given in Program 2.7.

Program 2.7 Logical operators

On executing, we get to see the following output. When you see 1, it is equivalent
to TRUE. When you see 0, it is equivalent to FALSE.

Output 2.3 Logical operators

2.7.4 Bitwise Operators


C has 6 bitwise operators to perform operations on bits, which is the short form of
binary digits. The operators are given below.

Book 8.indb 48 6/7/2017 1:28:20 PM


C Programming 49

1. Bitwise AND (&)


2. Bitwise OR (|)
3. Bitwise EXOR (^)
4. Left Shift (<<)
5. Right Shift (>>)
6. One’s complement (~)

Bitwise AND (&)


Let us look at an example:
Let operand1=10; operand2=4.
In order to do a bitwise AND between operand1 and 2, we need to know their binary
equivalent. Operand1’s binary equivalent is 1010 and Operand2’s binary equivalent is
0100. We have to do bitwise AND bit by bit. It means, digit to digit & operation. As
we have seen in binary &&, 1 && 1 is alone 1. Rest of the combinations is all 0.

As we can see, bitwise AND of 10 and 4 is 0.

Bitwise OR (|)
Similar to binary OR, if at least one of the operands is true, expression is evaluated as
true.
Considering the above operands, (operand1=10, operand2=4)

Bitwise EXOR (|)


It is a little bit different than OR and AND. We can observe its nature by looking at the
following truth (Table 2.13).

Book 8.indb 49 6/7/2017 1:28:20 PM


50 Fundamentals of Computing and Programming

Table 2.13 EXOR truth table

Only if both the operands are different, EXOR returns true. Otherwise, it returns false.
Considering the same operand values, (operand1=10 and operand2=4), we perform
EXOR as follows.

Left Shift (<<)


This symbol is used to shift bits of its operand left-hand side by the mentioned number
of bits. For example, 10<<1 shifts ‘10’ by 1 bit left. Diagrammatically, this is explained
as follows in Figure 2.3.

Figure 2.3 Left shift.

For quick calculation of left shift, we can multiply the operand by 2*n where n being
the number of bits to be shifted. In the above example, if we want to shift 10 by 1, it
can be done as 10*2*1 = 20. When n is 0, there needs no shift at all. The number will
be itself.

Book 8.indb 50 6/7/2017 1:28:22 PM


C Programming 51

Right Shift (>>)


This is quite opposite to the left shift, which shifts the operand to right-hand side by
mentioned number of bits. Just like how we have a shortcut for left shift, we have a
shortcut for right shift too. We need to divide the operand by 2*n to shift the operand
by n bits right. For example, (10>>2) will be equal to (10/ (2*2)) which is 2.

One’s Complement (~)


This is a simple operator, which is used to invert bits, (i.e.) 1 becomes 0 and 0 becomes
1. Let us look at an example,
Binary equivalent of 12 is: 0000 0000 0000 1100
If we take one’s complement of 12, it will be equivalent to 1111 1111 1111 0011 
which is fff3.
We can put all the above logic into the program 2.8.

Book 8.indb 51 6/7/2017 1:28:23 PM


52 Fundamentals of Computing and Programming

Program 2.8 Bitwise operators

The output of the Program 2.8 is given in Output 2.4.

Book 8.indb 52 6/7/2017 1:28:26 PM


C Programming 53

Output 2.4 Part I

Output 2.4 Part II

2.7.5 Relational Operators


These operators are meant to check relationship between operands. There are totally 6
relational operators.

Book 8.indb 53 6/7/2017 1:28:29 PM


54 Fundamentals of Computing and Programming

Just like logical operators, relational operators return Boolean result, either true or
false.
For example, if var1=10, var2=33;
•• (a<b)? returns 1
•• (a>b)? returns 0
•• (a==b)? returns 0
•• (a<=b)? returns 1
•• (a>=b) returns 0
•• (a!=b) returns 1
We will look into a program explaining these concepts, using Program 2.9.

Book 8.indb 54 6/7/2017 1:28:31 PM


C Programming 55

Program 2.9 Relational operators – Part I

Program 2.9 Relational operators –Part II

Book 8.indb 55 6/7/2017 1:28:34 PM


56 Fundamentals of Computing and Programming

On executing the above program, we get to see the following (Output 2.5).

Output 2.5 Part I

Book 8.indb 56 6/7/2017 1:28:37 PM


C Programming 57

Output 2.5 Part II

2.7.6 Unary Operators


The operators which take only one operand are called unary operators. Following are
the operators.
•• NOT (!)  
•• Unary Minus (–)  
•• Unary plus (+)
•• Address of operator (&)
•• Indirection/ value of operator (*)
•• One’s complement (~)
•• sizeof() operator
•• casting operator (type_name) expression.
•• Increment operator (++)
•• Decrement operator (--)

Book 8.indb 57 6/7/2017 1:28:39 PM


58 Fundamentals of Computing and Programming

NOT Operator (!)


We have already discussed NOT operator before where we saw that it is used for
inverting the sign of the operand. (i.e.)!0=1 and !1=0.

Unary Minus
This is a simple operator which converts a positive number into a negative number and
negative number into a positive number. For instance, when we prefix a minus before
an integer number, it becomes a negative number.
Examples:
int a=10; int b=-a; this makes b=-10
int a=-10; int b=-a; this makes b=10

Unary Plus
This is opposite to unary minus. It actually doesn’t alter the sign of the operand. It
keeps a positive operand as positive and negative operand as negative. It is not widely
used, but in some places which require us to place + before the value for easy
understanding and readability.

Address of, Indirection Operator


These operators go hand in hand in pointer concepts. & is called address of operator.
* is called indirection operator. When we prefix & with any variable, it means that, we
are accessing its address. Similarly, when we prefix * with any variable, it means that
we are accessing the value stored in the address pointed to.
Example

Program 2.10 Address of, Indirection operator program and output

Book 8.indb 58 6/7/2017 1:28:39 PM


C Programming 59

One’s Complement Operator


We have already discussed this operator in bitwise operators section. To brief it, this
operator is used to invert 0s to 1s and 1s to 0s in a binary value.

Size of() Operator


As the name indicates, we can determine size of any operand using this operator. The
operand can either be a variable or a derived type like a structure or simply a data type.
It will return number of bytes occupied by the operand.
Example

Program 2.11 Size of operator program and output

Type Casting Operator


In general, any expression would go error free when it deals with operands of same
type. If we have to deal with operands of different types, we have to cast them for
bug-free code. There are two types of conversions possible in C.
1. Implicit type conversion
2. Explicit type conversion
Implicit conversion, as the name indicates, in some instances, the compiler itself does
type conversion of variables.

Book 8.indb 59 6/7/2017 1:28:41 PM


60 Fundamentals of Computing and Programming

Example
1. When we have an expression of double variable and float variable, the result will
automatically converted to double.
2. When we have an expression of int variable and short variable, the result will
automatically be converted to int.
Similarly, if we mix up different data types, it gets converted to higher data type
version if the usage is correct. The conversions follow the below given hierarchy below.

Figure 2.4 Conversion hierarchy.

As shown in Figure 2.4,


•• short and char are promoted to int.
•• int is promoted to long.
•• long is promoted to float
•• float is promoted to double.
Explicit conversion is performed using cast operator. Let us look at Program 2.12 to
understand why we need to perform explicit casting.

Program 2.12 Casting need program

Book 8.indb 60 6/7/2017 1:28:41 PM


C Programming 61

When we execute the above program, we expect the answer to be 0.5, but since i and
j both are integer variables, it will produce the error 0 (truncating the decimal part) as
in Output 2.6.

Output 2.6 Improper operation without casting.

When we cast explicitly, the issue will be overcome. It is shown in Program 2.13.

Program 2.13 Casting example

This code will produce the expected result as follows in Output 2.13.

Output 2.7 Output of program 2.13

One thing to be noted in Program 4.6 is that, when we cast one of the operands, the
other operand is automatically converted to float. Also, we cannot perform casting on
LHS of assignment operator.

Increment Operator (++)


This operator is similar to adding 1 to the variable value. (i.e) a++ is similar to a=a+1;
there are two versions of it.
1. Pre-increment — increment of the variable happens first and assignment to the
variable happens next.
2. Post-increment — assignment to the variable happens first and increment
operation of the variable happens next.
Program 2.14 would make this clear.

Book 8.indb 61 6/7/2017 1:28:42 PM


62 Fundamentals of Computing and Programming

Program 2.14 Increment operator

Decrement Operator (--)


This is just opposite to the increment operator. When used with an integer variable, it
decreases the value of variable by 1. Similar to pre-increment and post-increment, we
have pre-decrement and post-decrement reacting just the same way! An example is
given in Program 2.15.

Program 2.15 Decrement operator

2.7.7 Conditional Operator


We have already learnt if-else-else if constructs. Conditional operator works the
same way which is syntactically easier than if-then-else operator. Let us quickly
look at an example in Program 2.16 where we determine larger of the two numbers
using if-else if-else construct.

Book 8.indb 62 6/7/2017 1:28:43 PM


C Programming 63

Program 2.16 If-elseif-else example

Sample output:
If a=10 and b=100, it will print b is greater than a;
•• If a=100 and b=100, it will print a is greater than b;

If a=100 and b=100. It will print a is equal to b.


The same logic can be written simply in one line using conditional operator. Let us
look at the Program 2.17 using conditional operator.

Program 2.17 Conditional operator

Book 8.indb 63 6/7/2017 1:28:45 PM


64 Fundamentals of Computing and Programming

The working of conditional operator is depicted below.

As shown in Program 2.17, we can use nested conditional operator. Please note that
we can assign the evaluation result of conditional operator to variables. An example
code snippet is provided below.
int a=100, b=200;
int val = a>b?1:0; //it assigns 1 if a is greater than b, else, 0 is assigned to a.

2.7.8 Comma Operator


Finally, we are with comma operator. It is seen almost in every program. Most commonly
while declaring multiple variables, and in printf statements where we print more than
one variables, etc.
Refer to the Program 2.18.

Program 2.18 Comma operator example

Output is as follows.

Output 2.8

Book 8.indb 64 6/7/2017 1:28:46 PM


C Programming 65

With this we have seen the basics of all the operators in C. Next section takes you
through operator precedence which is a very important topic when we deal with
expressions with multiple operators.

Precedence of Operators
Table 2.14 describes the precedence plus associativity details.

Table 2.14 Precedence of operators part I

Book 8.indb 65 6/7/2017 1:28:48 PM


66 Fundamentals of Computing and Programming

Table 2.14 Precedence of operators part II

2.8 MANAGING INPUT AND OUTPUT OPERATIONS

Inputs and outputs are integral part of any language program. C is no different. In
almost all the programs, we would have seen #include<stdio.h> as the first line of
the program. This is the file where the functions related to input and output reside.
Stdio is expanded as standard input and output. Stdio.h has the definitions for
printf() and scanf() that we have been using in all the programs. This section lists
down the various formats in which we can use printf() and scanf().
Format specifiers:
In all the printf() and scanf() statements, we have seen %d or %s. These are called
format specifiers. It differs for each data type. It is listed below.
•• For INT  %d or %i
•• For float %f
•• For char  %c
•• For string  %s
We have some special formatting that can be applied to the above format specifiers.
int a;
a = 30;
printf(“%10d\n”,a);
printf(“%010d”,a);
In the above code snippet, the first printf prints 30, with 8 white spaces preceding it.
In the second printf, there will be 8 zeros preceding 30. Like this the reader can try for
float to determine the precision and also with strings to play around with characters.

Book 8.indb 66 6/7/2017 1:28:49 PM


C Programming 67

Just like printf(), we can try formatting scanf() too. The syntax is given below.
%[*][width][length]format-specifier.
For example, scanf(“%79s”,str);

2.9 DECISION MAKING AND BRANCHING

During course of any software development, we will have to check for some conditions.
For instance, if the input number is between 100 and 200 or if the age entered by user
is greater than or equal to 18, etc. In such scenario, when we want to compare some
value with some condition, we make use of decision making and branching technique.
Following are the conditional constructs available in C.
1. if.
2. if – else.
3. Nested if.
4. Switch case.
All of these constructs make use of operators to compare. The operators that can be
used are given in Table 2.15.

Table 2.15 Operators

We shall see the conditional constructs in detail in the upcoming sections. Before
stepping into the conditional construct logic, note that, if we use relational operator in
the conditional constructs, it will return a Boolean value, either true or false.

Book 8.indb 67 6/7/2017 1:28:50 PM


68 Fundamentals of Computing and Programming

2.9.1. if Condition
This is the simplest form of conditional construct. The syntax is very simple as given
below.
if ( the condition to be checked)
- Statement to be executed if the condition is evaluated to
true.
Let’s look at a program to see IF working in Program 2.19.

Program 2.19 If – example program

In this program, we are asking the user to enter mark. If the entered mark is lesser
than 35, it will print Sorry!! The user is not allowed to sit for the next level. The execution
snapshot is present in Output 2.9. Please note that, if there are more than one statement
to be executed in if condition, the statements have to be put inside curly braces. On the
other hand, if there is only one condition, we need not have it in curly braces.

Output 2.9 Output of Program 2.19

2.9.2 if-else Condition


In the above section, if the expression is evaluated to be true, the statements followed
by if condition will get executed. In case if the expression fails, (i.e.) the mark entered
by the user is greater than or equal to 35, then there is no logic to be executed. In real-
world scenarios, having only IF condition will not satisfy our requirements. We need
to have alternative flows for the expressions. if-else is meant to add alternative flow
to the IF part, when the condition in IF part fails. Its syntax is as follows:

Book 8.indb 68 6/7/2017 1:28:52 PM


C Programming 69

if (condition to be evaluated)
{
----Action to be taken if the condition is evaluated to be TRUE-------
}
else
{
----Action to be taken if the condition is evaluated to be FALSE-------
}
Let us look at an example to see it working in Program 2.20.

Program 2.20 if else example

Compared to the previous example, we have an alternative flow in else part in this
example. So, if the value entered by the user is greater than or equal to 35, it will print
Wow!! The user has passed, and allowed to sit for the next level. Execution snapshots are
shown below in Output 2.10.

Output 2.10 if-else example and its output

There is one more form of if-else construct. We call it cascading if-else where
there are multiple ‘else if’ clauses.

Book 8.indb 69 6/7/2017 1:28:53 PM


70 Fundamentals of Computing and Programming

Syntax:
if (condition to be evaluated)
{
----statement to be executed when condition is TRUE-------
}
else if(another condition to be evaluated)
{
----when the condition in if part fails, this part gets
executed when another condition is TRUE.
}
else if(another condition to be evaluated)
{
--when the conditions in if part and first if-else part fails
and the current condition succeeds.
}
.
.
else // if all the above conditions fail,else part will get
executed.
{
}
The following program illustrates this logic.

Book 8.indb 70 6/7/2017 1:28:54 PM


C Programming 71

Program. 2.21 Cascading if else

Sample I/O is shown in Output 2.11.

Output 2.11 Output for Program 2.21

2.9.3 Nested if Condition


Nested if is nothing but if inside another if. For instance,
if(condition to be evaluated) – if #1
if (another condition to be evaluated) -- if #2
if (some other condition to be evaluated) – if#3
.
.
.
else if(some other condition to be evaluated)
else if(some other condition to be evaluated)
else if(some other condition to be evaluated)
else//else part

Book 8.indb 71 6/7/2017 1:28:56 PM


72 Fundamentals of Computing and Programming

This is diagrammatically represented in Figure 2.5.

if some False False


else-if part else part
condition

True True
Statements to
be executed

If False False
some other else-if part else part
condition

True True
Statements to
be executed

if False False
some other else-if part else part
condition

True
True
Statements to
Statements to
be executed
be executed

Figure 2.5 Nested if.

2.9.4 The Switch Case


If there are multiple conditions to check, we normally go for if-else construct. But
as we can observe, having too many if-else will reduce the readability of the code
and also it is not the best practice recommended in industry too. Switch case is the
alternate to the if-else construct. It provides improved readability, much faster
execution than if-else. The syntax is as follows.

Book 8.indb 72 6/7/2017 1:28:56 PM


C Programming 73

In Program 2.22, we can see the way switch works.

Program 2.22 Switch case

Execution snapshot is shown below for various inputs in Output 2.12.

Output 2.12 Output for code 2.5.

Book 8.indb 73 6/7/2017 1:28:59 PM


74 Fundamentals of Computing and Programming

We have a few points to be noted with switch cases.


1. The case label can be of type int or char. (In the previous example, mark was
the case label which is an integer variable!)
2. Case expressions can either be an int or a character or an expression which is
of type int.
For example,
case 100-80+60:
case ‘f’:
3. Every case statement should end with a break statement. If we don’t have a break
statement, all the following cases will get executed. This is termed fall-through.
4. Default can be placed at the beginning or at the end, also, default clause is optional.

2.10 LOOPING STATEMENTS

When we want to do a certain task again and again we achieve this using looping
constructs in C. For instance, when we have to get names of 100 students along with
other details, we declare a loop and do it instead of writing printf()/scanf() 100
times or more. Loops are always preferable because they:
1. consume less time than having to write same statement again and again;
2. reduce the length of the program; and
3. improve readability.
We shall see in detail about looping constructs in the next few sections.

2.10.1 The for Loop


This is the most commonly used loop and simple to use too. Its syntax is given below.
for (initialization; expression to verify; increment/decrement)
{
---statements to be executed repeatedly---
}
For example,

for(i=0;i<5;i++)
{
Printf(“Hi I am in a loop”);
}
Here, we are initializing i to 0 and goes on 5 times till i=4 incrementing 1 every time
printing Hi I am in a loop 5 times. Let us see a working example in Program 2.23.

Book 8.indb 74 6/7/2017 1:28:59 PM


C Programming 75

Program 2.23 For loop

Upon executing the above code, we can see Hello, Welcome to C programming 100
times. A portion of outputis shown in Output 2.13:

Output 2.13 Output of Program 2.23

Note that we do not have to always follow the syntax mentioned above. We can
ignore initialization part/increment-decrement part. Following instance shows that we
have missed out initialization portion. But it should be noted that, we have initialized
the variable somewhere else before the loop executes.
val=100;
for (;val>=95;)
{
<Do something>
Val--; //decrement at the end.
}

Book 8.indb 75 6/7/2017 1:29:02 PM


76 Fundamentals of Computing and Programming

2.10.2 The while Loop


This is similar to for loop, but with some difference. Like for loop, we need to initialize
an iterator variable before the while loop gets executed. Also, before the loop ends, we
need to increment or decrement the iterator variable value. The syntax is given below,
Step1: Initialization variable;
Step2:
while(condition for termination)
{
---statements to be executed---
Increment/decrement initialized variable;
}
Let’s explore this in the following program 2.xs

Program 2.24 Sample program for while loop

Here in the Program 2.24, we have initialized number to be 100 before the loop starts.
In the loop condition, we check if the number is greater than zero. And inside the loop,
we get the value for number from the user and subtract it with the already present
value (in the first iteration it is 100). The loop keeps repeating until the inputted number
is greater than 0. Upon execution, we are getting the below result as shown in Output
2.14.

Book 8.indb 76 6/7/2017 1:29:03 PM


C Programming 77

Output 2.14 Sample output for Program 2.24

As we can observe from the above logic, we cannot determine how many times the
loop gets executed. If in the above example, the user inputs 1 every time, the loop will
get executed 100 times. If the user inputs 2 every time, the loop gets executed 50 times.
So, when we are having a scenario where we are unsure of number of iterations, we
can go for while loop than for loop.

2.10.2.1 The Do-while Loop

It is quite similar to while loop with only one difference. In while loop, before executing
the statements inside the loop, we check for condition. But in do-while loop, the condition
is checked at the end. The syntax is given below.
do
{
.
.
<Statements to be executed>
.
.
} while<condition to be satisfied>;

Having said that do while loop checks for the termination condition at the end of the
loop, it is guaranteed that, the statement inside the loop gets executed at least once.
Following Program 2.25 illustrates this.

Program 2.25 do-while loop

Book 8.indb 77 6/7/2017 1:29:04 PM


78 Fundamentals of Computing and Programming

On executing Program 2.25, we get to see Output 2.15.

Output 2.15 Output of Program 2.25

Note: If we try the above program using a while loop, we will be seeing the results
as follows in Program 2.26.

Program 2.26 While example and its output

Book 8.indb 78 6/7/2017 1:29:05 PM


C Programming 79

2.11 SOLVING SIMPLE SCIENTIFIC AND STATISTICAL PROBLEMS

2.11.1 Finding Area of Circle


The following program finds the area of the circle by getting radius from the user. The
readers are requested to see what happens when %f is replaced by %d in the last
printf() statement in the following code.
#include<stdio.h>
#define PI 3.14
void main()
{
int r;
printf(“Enter radius of the circle:”);
scanf(“%d”,&r);
printf(“\n Area of circle is %f”,PI*r*r);
}

2.11.2 Finding Length of a String


The following code is meant to find the length of the input string. The readers are
requested to try this without using inbuilt strlen() function.
#include<stdio.h>
#include<string.h>
main()
{
char r[100];
printf(“Enter the string”);
scanf(“%s”,r);
printf(“\n Length of the string is %d”, strlen(r));
}

2.11.3 Program to Print a Number Triangle


The readers are requested try center aligned triangle.
#include <stdio.h>
main()
{
int i,j;
for(i=1;i<=5;i++)
{
printf(“\n”);
for(j=1;j<=i;j++)
{
printf(“%d”,j);

Book 8.indb 79 6/7/2017 1:29:05 PM


80 Fundamentals of Computing and Programming

printf(“\t”);
}
}
return 0;
}

2.11.4 Program to Print Number of Odd and Even Numbers


Readers are requested to see if the below logic works in switch case.
#include <stdio.h>
main()
{
int a[10],i,even=0,odd=0;
printf(“Please enter 10 numbers one by one”);
for(i=0;i<=9;i++)
{
printf(“\nNumber %d:”, i+1);
scanf(“%d”,&a[i]);
}
for(i=0;i<=9;i++)
{
if(a[i]%2==0)
even++;
else
odd++;
}

printf(“\n No.of Odd:%d”,odd);


printf(“\n No.of Even:%d”,even);
return 0;
}

2.11.5 Program to Swap Two Numbers


#include <stdio.h>
main()

Book 8.indb 80 6/7/2017 1:29:06 PM


C Programming 81

{
int num1= 10, num2 = 20;
int temp;
printf(“Before swap...\n”);
printf(“num1=%d\n”,num1);
printf(“num2=%d\n”,num2);
temp=num1;
num1=num2;
num2=temp;
printf(“After swap...\n”);
printf(“num1=%d\n”,num1);
printf(“num2=%d\n”,num2);
}

KEY POINTS TO REMEMBER

•• C is a case-sensitive language. A is different from a.


•• Every statement should terminate with a semicolon.
•• We can use header files in the program which holds the inbuilt functions.
•• Stdio.h header file is used for input and output operations, including scanf
and printf.
•• main() function is the entry point of execution for any program.
•• A C program is composed of variables, expressions, decision-making statements,
loops, arrays, etc.
•• Constants can be defined in the preprocessor directive using #define.
•• Variable names cannot be the same as the reserved words.
•• int, float, char are the primitive data types from which derived data types
like structures, array are created.
•• Any expression involving multiple operators are evaluated based on the precedence
of operators.
•• The return type of relational operators is Boolean.
•• Unary operators take only one operand while binary operators take two.
•• Conditional operator has three parts, namely, expression, true part and false part.
•• It is always advisable to use switch case instead of if-else. This improves
readability and speeds up execution.
•• Looping constructs help us repeat the same logic multiple times without having
to code again and again.
•• do-while loop executes all the statements at least once.

Book 8.indb 81 6/7/2017 1:29:06 PM


82 Fundamentals of Computing and Programming

QUESTIONS TO TEST YOUR SKILLS

1. What is the output of the code?


main()
{ printf(“hat\bi”);}
a. hati b. hat\bi
c. hai d. Error
Answer: c. Here the \b escape sequence for back space. It deletes the last character ‘I’
and then replaces it with ‘i’
2. What is the output of the code?
main()
{ printf(“hat\fi”);}
a. hati b. hat\fi
c. error d. ha
Answer: d. Here the \f escape sequence is form feed. It intends the rest of the output
in new form format.
3. What is the output of the code?
main()
{ printf(“chi\rca\rgo”);}
a. chicago b. go
c. cago d. chigo
Answer: b. Here the \r escape sequence is carriage return. It deletes all the previous
outputs of the code.
4. What is the difference between the following codes?
I) main() II) main()
{ printf(“ha\vi”); } { printf(“ha\fi”); }
a. Both give same output but have logical difference
b. First program gives “hai” but the second one displays “ha\fi”.
c. Has no difference
d. First program prints ha while the second program will print with some
spacing difference ha
Answer: a. \v is vertical tab that takes the rest to next line. \f is form feed that takes
the rest to new form input. Both will give same input as ha
5. What is the output of the code?
main()
{ printf(“\\\”);}
a. \\\ b. Compilation error
c. \\ d. Logical error
Answer: b. Here the first ‘ \ ‘ is an escape sequence for backslash. While the third ‘ \’
is for quotes. So the sentence is not terminated.

Book 8.indb 82 6/7/2017 1:29:06 PM


C Programming 83

6. What is the output of the code?


main()
{ printf(“ ’a\’ “);}
a. a’ b. Compilation error
c. ‘a’ d. ‘a\’
Answer: c. The first single quote is treated as a character while the second quote is from
escape sequence.
7. What is the output of the code?
main()
{ printf(“ \h\i “);}
a. \h\i b. Compilation error
c. hi d. Logical error
Answer: c. The illegal escape sequence neglects the escape character ‘\’ and treats h
and I as normal characters.
8. Which of the following will give the output “??” ?
a. printf(“??”); b. printf(“\?\?”);
c. printf(“\??”); d. all the above
Answer: d. First option treats both ‘??’ as characters, while the second one treats both
as escape sequence. The third option has one escape sequence followed by a
character. Thus, all the three options give the expected output.
9. What is the output of the code?
main()
{ printf(“ \123”);}
a. I b. \123
c. 23 d. S
Answer: d. \nnn treats the numbers nnn as octal and converts it to the corresponding
ASCII character. Thus, prints ‘S’.
10. What is the output of the code?
main()
{ printf(“ \x5A”);}
a. Z b. x5A
c. M d. 5A
Answer: a. \xhh treats the numbers hh as hexadecimal and converts it to the corresponding
ASCII character. Thus, prints ‘Z’.
11. What is the output of the code?
void main()
{ int a=8;
int b=a;
printf(“%d %d”,a,b); }
a. 8 8 b. 8 0
c. Error d. 8 garbage_value

Book 8.indb 83 6/7/2017 1:29:06 PM


84 Fundamentals of Computing and Programming

Answer: a. ‘a’ is declared first and assigned to ‘b’ later.


12. What is the output of the code?
void main()
{int a=8;
int b=c=a;
printf(“%d %d %d”,a,b,c); }
a. 8 8 8 b. 8 0 0
c. Error d. 8 garbage_value garbage_value
Answer: c. ‘a’ is declared first. The second declares ‘b’ and assigns the value of ‘a’ to
‘c’ and from there to ‘b’, but ‘c’ is never declared hence throws error.
13. What is the output of the code?
void main()
{int a=8;
int b=a=c;
printf(“%d %d %d”,a,b,c); }
a. 8 8 8
b. 0 0 0
c. Error
d. garbage_value garbage_value garbage_value
Answer: c. ‘a’ is declared first. The second declares ‘b’ and assigns the value of ‘c’ to
‘a’ and from there to ‘b’, but ‘c’ is never declared hence throws error.
14. What is the output of the code?
void main()
{int a=8;
int b=a=4;
printf(“%d %d”,a,b); }
a. 8 8 b. 8 0
c. 4 4 d. 4 0
Answer: c. The second value of ‘a’ overwrites the first value and the same is assigned
to ‘b’.
15. What is the output of the code?
void main()
{int a=8;
int b=a,a=4;
printf(“%d %d”,a,b); }
a. 8 8 b. 8 4
c. 4 4 d. error
Answer: d. Re-declaration of a variable within same scope is not allowed.
16. What is the error in the code?
void main()
{int a=8;

Book 8.indb 84 6/7/2017 1:29:06 PM


C Programming 85

int b=4=a;
printf(“%d %d”,a,b); }
a. Declaration of ‘a’ multiple times is not allowed.
b. Number cannot be a lvalue (left side argument ) for ‘=’
c. Segmentation fault
d. No error
Answer: b. Here ‘a’ is declared only once. In the second statement it is assigned to a
value 4. This causes the error.
17. What is the output of the code?
void main()
{int a=8;
int b;
printf(“%d %d”,a=b,b=a); }
a. 8 8 b. 8 0
c. 0 0 d. 0 8
Answer: a. The output is based on the fact that printf processes the arguments of equal
priority from right to left and then prints them in left to right.
18. What is the output of the code?
void main()
{int a=8;
int b;
printf(“%d %d”,b=a,a=b); }
a. 8 8 b. 8 0
c. 0 0 d. 0 8
Answer: c. The output is based on the fact that printf processes the arguments of equal
priority from right to left and then prints them in left to right.
19. What is the output of the code?
void main()
{int a=8;
int b;
printf(“%d %d”,b=a=3,a); }
a. 8 8 b. 8 3
c. 3 3 d. 3 8
Answer: c. Functions, operations and assignment in arguments takes more priority over
normal arguments. So at first ‘a’ gets 3.
20. What is the output of the code?
void main()
{ int a;
int b;
printf(“%d %d”,b=a=3,a=4); }

Book 8.indb 85 6/7/2017 1:29:06 PM


86 Fundamentals of Computing and Programming

a. 3 4 b. 3 3
c. 4 4 d. error
Answer: b. Both assignment processes have same priority. The value of ‘a’ is assigned
first as 4 and then overwritten as 3, as printf executes from right to left and
prints from left to right.
21. What is the output of the code?
void main()
{ int a;
int b;
printf(“%d %d”,b=a=3); }
a. 3 3 b. 3 0
c. 3 Garbage_value d. 0 0
Answer: c. The first format specifier takes value from the assignment while the second
doesn’t have a value, hence prints some garbage value.
22. What is the output of the code?
void main()
{ int a;
float b;
printf(“%d %f”,b=5.14); }
a. 0 Garbage_value
b. 5 Garbage_value
c. 5.140000 Garbage_value
d. Garbage_value 5.140000
Answer: d. The float value matches itself to the specifier and the undefined specifer
takes the garbage value.
23. What is the output of the code?
void main()
{ int a;
float b;
printf(“%f %d”,a=3,b=5.14); }
a. 0 garbage_value b. 0 0
c. 5.140000 3 d. 3.000000 5
Answer: c. In spite of wrong order the arguments matches to the specifiers by themselves.
24. What is the output of the code?
void main()
{ float b=0.23;
printf(“%f %f”,b=5.14,b); }
a. 5.140000 5.140000
b. 5.140000 .230000
c. Garbage_value Garbage_value
d. 0.230000 0.230000

Book 8.indb 86 6/7/2017 1:29:06 PM


C Programming 87

Answer: b. It just executes from right to left.


25. What is the output of the code?
void main()
{ char d;
printf(“%c”,d); }
a. Garbage_value b. blank space
c. \0 d. None of the above
Answer: d. By default all char variables are initiated with null but on printing nothing
will be printed and the compiler terminates. All other data types initiate to 0.

Book 8.indb 87 6/7/2017 1:29:06 PM


3 ARRAYS AND STRINGS

LEARNING OBJECTIVES

After reading this chapter, the reader would be able to understand:


•• What are arrays?
•• What are the different characteristics of arrays?
•• How do you initialize arrays?
•• How are arrays declared?
•• Difference between one-dimensional and two-dimensional arrays
•• String and string related operations
•• What are string arrays?
•• Write simple programs for sorting, searching and matrix operations
•• What is array of characters?
•• Define string data structure.

3.1 INTRODUCTION

An array is a collection of similar variables that share a single name for access. The
individual array elements are referenced by appending a subscript, in square brackets,
after the name. The subscript itself can be any legitimate C expression that gives an
integer value, even a regular expression. Therefore, a collection of like variables is
called arrays in C. One of the simplest data structures is arrays and it has widespread
applications in embedded systems.
Strings are also similar to arrays with just a little difference. Strings have a variable
number of elements while the array size is fixed. Arrays can contain any data type (char
intshort even other arrays) while strings are generally ASCII characters and are
terminated with a NULL (0) character at the end.
Random access is allowed to access individual array elements. Strings, on the other
hand are usually processed sequentially character by character from start to end. Since
these changes are a matter of semantics instead of specific restrictions imposed by the
syntax of the C programming language, the explanations in this chapter relate equally
to character strings and data arrays. In addition, C programming language has a rich
set of predefined functions to manipulate strings.

Fundamentals of Computing and Programming

Book 8.indb 88 6/7/2017 1:29:06 PM


Arrays and Strings 89

Heap Memory

Fruits String [] array object

String [] array
Index 0 1 2 3 4
reference
null null null null null

Figure 3.1 Arrays and strings.

All arrays contain contiguous memory locations. The lowest address present in the
array corresponds to the first element while the highest address represents the last element.
First Element Last Element

Numbers [0] Numbers [1] Numbers [2] Numbers [3] .......

Figure 3.2 Representation of arrays.

In order to declare an array, a programmer specifies the type of elements along with
the number of elements and is represented as follows:
type name_array [size_array];
A single-dimensional array is represented as above. The size of the array has to be
always greater than zero for the array to hold the elements. Arrays can be initialized
one at a time or they can also be initialized as a group. It is given as follows:
double remain[5] = {900.0, 3.0, 2.4, 6.0, 49.2};
The size of the array can also be omitted in this case and the program will still work.
The elements of the array are accessed by indexing the array name. For example,
double salary = remain[9];
When the above statement gets executed, the 10th element from the above array will
be assigned the value. We have the below program to explain the whole array concept:
#include <stdio.h>
int main () {
int data[ 10 ]; /* data is an array containing 10 integers
*/
int i,j;
/* initialize elements of array data to 0 */
for ( i = 0; i < 10; i++ ) {

Book 8.indb 89 6/7/2017 1:29:06 PM


90 Fundamentals of Computing and Programming

data[ i ] = i + 100; /* set the element at location i to i + 100 */


}
/* output each array element’s value */
for (j = 0; j < 10; j++ ) {
printf(“Element[%d] = %d\n”, j, data[j] );
}
return 0;
}
Program 3.1 Array - A simple example

When the above piece of code gets compiled and executed, the output would be as
follows:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
C supports both single-dimensional as well as multidimensional arrays.
Two-dimensional array is the simplest form of the multidimensional array. We can pass
to the function, a pointer to an array through the name without an index. C program
also allows a function to return an array. Specifying the array name is sufficient to
generate a pointer to the first element of an array.
Every variable is a memory location and they have their address defined which can
be accessed by & operator. The following example prints the address of the variables:
#include <stdio.h>
int main () {
int var1;
char variable2[10];
printf(“The Address of var1 variable: %x\n”, &variable1
);
printf(“The Address of var2 variable: %x\n”, &variable2
);
return 0;
}
Program 3.2 Array and addressing

Book 8.indb 90 6/7/2017 1:29:06 PM


Arrays and Strings 91

When the above code gets executed, the output would be as follows:
The Address of var1 variable: bff4b400
The Address of var2 variable: bff4b3f6
Array might be belonging to any of the data types.
The array size must be a constant value. In arrays, it is always, contiguous memory
locations are used to store array elements in memory. It is always a good practice to
initialize an array to zero or null value while declaring, if we don’t assign any values
to array. If the values are available, they can be directly assigned to them.

3.2 CHARACTERISTICS, INITIALIZATION AND DECLARATION OF ARRAYS

C Array is a group of variables representing the same data type. We can store collection
of data of same data type in an array. Table 3.1 below gives the details about array
declaration, initialization and accessing the members of the array.

Table 3.1 Characteristics of arrays


Array declaration, initialization and Array Example
accessing members
Array declaration syntax: Integer array example:
data_type array_name [arr_size]; int age [5];
int age[5]={0, 1, 2, 3, 4};
age[0]; /*Element 0 is accessed*/
Array initialization syntax:
age[1]; /*Element 1 is accessed*/
data_type array_name [arr_size] =
age[2]; /*Element 2 is accessed*/
(value1, value2, value3,….);
Character array example:
char str[10];
Array accessing syntax: char str[10]={‘B,‘y’,‘e’};
array_name[index]; (or)
char str[0] = ‘B’;
char str[1] = ‘y’;
char str[2] = ‘e;
str[0]; /*B is accessed*/
str[1]; /*y is accessed*/
str[2]; /*e is accessed*/

The memory representation of the array is represented in Figure 3.3:


val[0] val[1] val[2] val[3] val[4] val[5] val[6]
11 22 33 44 55 66 77
88820 88824 88828 88832 88836 88840 88844

Figure 3.3 Array representation and memory details.

The different properties of arrays are discussed below:

Book 8.indb 91 6/7/2017 1:29:06 PM


92 Fundamentals of Computing and Programming

1. In C programming language, it is possible to have array of all data types except


functions and void.
2. In C programming language, array and pointer are two different concepts. They
seem similar because the name of the array gives the address of the first element
and array elements are accessed using pointer arithmetic.
3. A character array set with double quoted string has always the last terminating
element as ‘\0’.
4. Arrays are generally passed as pointer to functions.
5. Like any other variables, arrays can also be allocated memory in any of the three
segments including the data, heap, and stack. Dynamically allocated arrays are
generally allocated the required memory on heap, static or global arrays are
allocated the needed memory on data segment and local arrays are provided with
memory on stack segment.
The C99 standard generally allows variable sized arrays. But, unlike the normal
arrays, the variable sized arrays cannot be initialized. The following program details
the same with an example.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int N = 2;
int array[N][N];
int i=0, j=0;
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
{
array[i][j] = 0;
printf (“%d “, array[i][j]);
}
printf(“\n”);
}
return 0;
}
Program 3.3 Variable sized array

The output of the above program would be


00
00
In case if we try to do the same program with a variable-sized object, then we get
the compilation error as follows:

Book 8.indb 92 6/7/2017 1:29:06 PM


Arrays and Strings 93

int array[N][N] = {0}; // Trying here to initialize all the elements to 0


int i, j;
for (i = 0; i <N; i++)
{
for (j = 0; j <N; j++)
printf (“%d “, array[i][j]);
printf(“\n”);
}
return 0;
}
Program 3.4 Variable sized object

The output of the above program would be:


Compiler Error: Variable-sized object may not be initialized.
In C language, array parameters are treated as pointers and the sizeof operator should
not be used to get the number of elements. We can also assign a struct variable to
another variable of the same type. There is no index out of bound checking in C language
and because of which in the following program, the compiler output would be fine but
at the same time produces an unexpected output.
// This C program compiles fine as index out of bound is not checked in C.

#include<Stdio.h>
int main()
{
int arr[2];
printf(“%d “, arr[3]);
printf(“%d “, arr[-2]);
return 0;
}
Program 3.5 Out of bound check

3.3 ONE-DIMENSIONAL AND TWO-DIMENSIONAL OF ARRAYS

There are two types of C arrays:


•• One-dimensional array
•• Multidimensional array
▪▪ Two-dimensional array
▪▪ Three-dimensional array
▪▪ Four-dimensional array and so on.
A one-dimensional array (or in other words single-dimension array) is a type of linear
array. Accessing the elements of this linear array, involves a single subscript which can
either represent a column or row index.

Book 8.indb 93 6/7/2017 1:29:06 PM


94 Fundamentals of Computing and Programming

The following program is an example for the one-dimensional array in C. programming


language:
#include<stdio.h>
int main()
{
int i;
int array[5] = {10,20,30,40,50};
// Declaring array along with initialization
//To initialize all the elements of the array to 0, use int
array[5]={0};
/* Above array can be initialized using the below method as
well
arr[0] = 100;
arr[1] = 200;
arr[2] = 300;
arr[3] = 400;
arr[4] = 500; */
for (i=0;i<5;i++)
{
// Accessing each variable
printf("The value of array[%d] is %d \n", i, array[i]);
}
}

Program 3.6 One dimensional arrays

The output of the above program would be:


The value of array[0] is 100 The value of array[1] is 200
The value of array[2] is 300 The value of array[3] is 400
The value of array[4] is 500
Two-dimensional array represents array of array. Table 3.2 represents the characteristics
of a two-dimensional array.

Table 3.2 Characteristics of two-dimensional arrays

Array declaration, initialization and accessing Example

Array declaration syntax: Integer array example:


data_type arr_name int array[2][2];
[number_of_rows] int array[2][2] = {3,4, 5, 6};
[number_of_column]; array [0] [0] = 3;
Array initialization syntax: array [0] [1] = 4;
data_type arr_name[2][2] = array [1] [0] = 5;
{{0,0},{0,1},{1,0},{1,1}}; array [1] [1] = 6;

Array accessing syntax:


array_name[index];

Book 8.indb 94 6/7/2017 1:29:07 PM


Arrays and Strings 95

A two-dimensional array can be reflected as a table which will have x number of


rows and y number of columns. Figure 3.4 represents the same. Thus, every element
present in the array a is identified by an element name of the form a[ i ][ j ], where ‘a’
is the name of the array, and ‘i’ and ‘j’ are the subscripts that uniquely identify each
element in ‘a’.
Column 0 Column 1 Column 2 Column 3
Row 0 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]

Row 1 a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]

Row 2 a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]

Figure 3.4 Two-dimensional array representation.

The program detailed below is one of the examples for a two-dimensional array and
the same example can be extended for multidimensional arrays as well.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,j;
// declaring and Initializing array
int array[2][2] = {100,200,300,400};
/* Above array can be initialized as below
array[0][0] = 100; // Initializing array
array[0][1] = 200;
array[1][0] = 300;
array[1][1] = 400; */
for (i=0;i<2;i++)
{
for (j=0;j<2;j++)
{
printf(“Value of array[%d] [%d] :
%d\n”,i,j,array[i][j]);// Accessing variables
}
}
}
Program 3.7 Multi dimensional arrays

The output of the above program would be:


Value of array[0] [0] is 100
Value of array[0] [1] is 200
Value of array[1] [0] is 300
Value of array[1] [1] is 400

Book 8.indb 95 6/7/2017 1:29:07 PM


96 Fundamentals of Computing and Programming

The following example is also for a two-dimensional array:

#include <stdio.h>
int main () {
/* an array is created with 5 rows and 2 columns*/
int array[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int m, n;
/* output of each array element’s value */
for ( m = 0; m < 5; m++ ) {
for ( n = 0; n < 2; n++ ) {
printf(“array[%d][%d] = %d\n”, m,n, array[m][n] );
}
}
return 0;
}

Program 3.8 Two dimensional arrays

The output of the above program would be:


array[0][0]: 0
array[0][1]: 0
array[1][0]: 1
array[1][1]: 2
array[2][0]: 2
array[2][1]: 4
array[3][0]: 3
array[3][1]: 6
array[4][0]: 4
array[4][1]: 8
As explained above in the previous sections, we can have arrays with any number
of dimensions, although it is most likely that many of the arrays you create will be of
either one or two dimensions only.

3.4 STRINGS AND STRING OPERATIONS

Strings are generally one-dimensional arrays of characters or letters that are terminated
by a null character ‘\0’ at the end. Thus, in other words, a null-terminated string holds
the characters that include the string followed by a null.
The next declaration and initialization make a string that consists of the word “Hello”.
In order to hold the null character at the end of the array, the size of the character array
that contains the string will have one more character than the number of characters in
the actual word “Hello.”
char welcome[6] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’};

Book 8.indb 96 6/7/2017 1:29:07 PM


Arrays and Strings 97

The above statement can also be represented as:


char welcome[] = “Hello”;
The memory allocation for the above string is represented in Figure 3.5.
Index 0 1 2 3 4 5

Variable H e l l o \o

Address 0×23451 0×23452 0×23453 0×23454 0×23455 0×23456

Figure 3.5 Memory representation of the string.

From the above discussion, it is clear that there is no necessity to place the null
character explicitly. The C compiler will take care of the same. Program below explains
the same.
#include <stdio.h>
#include <stdlib.h>
int main () {
char welcome[6] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’};
printf(“Welcome message: %s\n”, greeting );
return 0;
}
Program 3.9 Usage of Null terminator

The output of the above program would be:


Welcome message: Hello
The syntax of string definition is hence given by Figure 3.6.

Figure 3.6 Syntax of string definition.

There are a couple of functions that are supported and manipulate the null-terminated
strings. They are detailed in Table 3.3.

Book 8.indb 97 6/7/2017 1:29:07 PM


98 Fundamentals of Computing and Programming

Table 3.3 String functions


S. No. Function Purpose

1 Strcpy(a1, a2); Copies string a2 in to a1

2 Strcat(a1, a2); Concatenates string a2 on to the end of string a1

3 Strlen(a1); Returns the length of the input string a1

4 Strcmp(a1, a2); Compares a1 and a2 and returns the output

5 Strchr(a1, ch); Compares and returns the first occurrence of ch

6 Strstr(a1, a2); Compares and returns the first occurrence of string

The following example explains the different functions used in writing a C program.
#include <stdio.h>
#include <string.h>
int main () {
char string1[15] = “Hai”;
char string2[15] = “Friend”;
char string3[15];
int len ;
/* copy str1 into str3 */
strcpy(string3, string1);
printf(“strcpy(string3, string1) : %s\n”, string3);
/* concatenates str1 and str2 */
strcat(string1, string2);
printf(“strcat(string1, string2): %s\n”, string1);
/* total lenghth of str1 after concatenation */
len = strlen(string1);
printf(“strlen(string1) : %d\n”, len );
return 0;
}
Program 3.10 String functions usage

The output of the above program would be:


strcpy(string3, string1) : Hai
strcat(string1, string2): Hai Friend
strlen(string1) : 9
So, a string is a finite sequence of characters which includes numerals, letters, symbols
and punctuation marks. Length of the string is one of the important characteristics of
a string which represents the number of characters present in the string. The length of
the string can be any natural number from zero till any positive value.

Book 8.indb 98 6/7/2017 1:29:07 PM


Arrays and Strings 99

A string is generally implemented as an array of words that help store a sequence of


elements which are generally characters and uses some character encoding. The
fundamental operations on the string like their creating, copying, concatenation,
matching, identifying the length, etc., refer to string manipulation.

3.5 STRING ARRAYS

A string is an array of characters. A character array also refers to an array of characters


as well. Some string representations use a null terminator while the others use a length
prefix. This is represented in Figure 3.7.

J o h n \0 ...
names[0]
S u e \0 ...
names[1]
...
names[2]

...
...
names[MAX–1] gets() (340,140)

s[0] s[1] s[2] s[3] s[4]

Figure 3.7 An array of strings and string using arrays.

Before operating on the strings, they need to be declared first. They can be declared
using arrays or using pointers as follows.

char s[5]; //using arrays


char *a; //using pointers
Generally, initialization and declaration are done in the same steps as follows:
char a[] = “efgh”;
OR,
char a[20] = “egfh”;
OR,
char a[] = {‘e’, ‘f’, ‘g’, ‘h’, ‘\0’};
OR,
char a[5] = {‘e’, ‘f’, ‘g’, ‘h’, ‘\0’};

Book 8.indb 99 6/7/2017 1:29:07 PM


100 Fundamentals of Computing and Programming

As like using arrays, strings can also be initialized using pointers.

Char *p = “efgh”;
Generally scanf is used to read a string as follows:

#include <stdio.h>
int main()
{
char title[20];
printf(“Enter the name: “);
scanf(“%s”, title);
printf(“Your name is %s.”, title);
return 0;
}

Program 3.11 Scanf to read strings

The output of the above program would be:


Enter the name: Bjarne Stroustrup
Your name is: Bjarne Stroustrup
One of the approaches that is followed to read a full line of text is as follows:
#include <stdio.h>
int main()
{
char title[30], chr;
int j = 0;
printf(“Enter your name: “);
while(ch != ‘\n’) // It will terminate if the user hits enter key
{
chr = getchar();
title[j] = chr;
j++;
}
title[j] = ‘\0’; // At the end, insert the null character
printf(“Your name is: %s”, title);
return 0;
}

Program 3.12 Approach for reading full lines

The above program would take one character at a time until the user hits the enter
key in order to confirm the end of line. The null character is then inserted to make it
as a string at the end.
The other functions like gets() and puts() are also used in C programming
language for the purpose of reading a line of text as follows:

Book 8.indb 100 6/7/2017 1:29:07 PM


Arrays and Strings 101

#include <stdio.h>
int main()
{
char title[30];
printf(“Enter your name: “);
gets(title); //Function that is to read string from user.
printf(“Your Name is: “);
puts(title); //Function that is used to display string.
return 0;
}

Program 3.13 Passing arrays to the function

The output of the above program would be:


Enter your name: John Mathews
Your name is: John Mathews
Strings are just the character arrays. Hence, they can also be passed to a function as
well in the similar way as we pass arrays to functions.

#include <stdio.h>
#include <stdlib.h>
void StringDisplay(char string[]);
int main()
{
char string[50];
printf(“Enter the string: “);
gets(str);
StringDisplay(string); // Passing the string to the function.
return 0;
}
void StringDisplay(char string[]){
printf(“Display the String: “);
puts(str);
}

Program 3.14 Program to calculate sum and average of an array

The output of the above program would be:


Enter the String: Hello World
Display the String: Hello World
In the above program, the input string is passed from the main function to the user
defined function and gets executed there. There are many library functions also available
for the purpose of ease of programming.

3.6 PROGRAMMING EXAMPLES USING ARRAYS AND STRINGS

In this section, we will learn to write simple programs using C programming language.

Book 8.indb 101 6/7/2017 1:29:07 PM


102 Fundamentals of Computing and Programming

3.6.1 C Program to Calculate Sum & Average of an Array


This C Program written below helps calculate the sum & average of a given input array.
It declares an array first followed by adding the elements of the array and then finally
finds the average of the same.

#include <stdio.h>
#define MAX_SIZE_ARRAY 10
void main()
{
int array[MAX_SIZE_ARRAY];
int j=0, number, negative_sum = 0, positive_sum = 0;
float aggregate = 0.0, average;
printf (“Enter the value of N \n”);
scanf(“%d”, &number);
printf(“Enter %d numbers \n”, number);
for (j = 0; j< number; j++)
{
scanf(“%d”, &array[j]);
}
printf(“Input array elements \n”);
for (j = 0; j< number; j++)
{
printf(“%+3d\n”, array[j]);
}
/* Summation starts here */
for (j = 0; j< number; j++)
{
if (array[j] < 0)
{
negative_sum = negative_sum + array[j];
}
else if (array[j] > 0)
{
positive_sum = positive_sum + array[j];
}
else if (array[j] == 0)
{
; /* Do nothing */
}
aggregate = aggregate + array[j] ;
}
average = aggregate / number;

Book 8.indb 102 6/7/2017 1:29:07 PM


Arrays and Strings 103

printf(“\n The sum of all negative numbers = %d\n”, negative_sum);

printf(“The sum of all positive numbers = %d\n”, positive_sum);


printf(“\n The average of all input numbers = %.2f\n”,
average);
}
Program 3.15 Program to delete element from array

The output of the above program would be:


Enter the value of N: 4
Enter 4 numbers:
9
100
40
-10
Input array elements:
+9
+100
+40
-10
The sum of all negative numbers: -10
The sum of all positive numbers: 149
The average of all input numbers: 34.75

3.6.2 C Program to Delete the Specified Integer from an Array


The following program helps in deleting a user specified integer from the given input
array.
#include <stdio.h>
#include<stdlib.h>
void main()
{
int vectors[10];
int i, number, position, element, found = 0;
printf(“Enter how many elements\n”);
scanf(“%d”, &number);
printf(“Enter the elements\n”);
for (i = 0; i < number; i++)
{
scanf(“%d”, &vectors[i]);
}
printf(“Input array elements are\n”);
for (i = 0; i < number; i++)

Book 8.indb 103 6/7/2017 1:29:07 PM


104 Fundamentals of Computing and Programming

{
printf(“%d\n”, vectors[i]);
}
printf(“Enter the element to be deleted\n”);
scanf(“%d”, &element);
for (i = 0; i < number; i++)
{
if (vectors[i] == element)
{
found = 1;
position = i;
break;
}
}
if (found == 1)
{
for (i = position; i < number - 1; i++)
{
vectors[i] = vectors[i + 1];
}
printf(“The resultant vector is \n”);
for (i = 0; i < number - 1; i++)
{
printf(“%d\n”, vectors[i]);
}
}
else
printf(“Element %d is not found in the vector\n”, element);
}

Program 3.16 Program to sort names in alphabetical order

The output of the above program is:


Enter how many elements
4
Enter the elements
123
245
467
734
Input array elements are
123
245
467
734

Book 8.indb 104 6/7/2017 1:29:07 PM


Arrays and Strings 105

Enter the element to be deleted


245
The resultant vector is
123
467
734

3.6.3 C Program to Sort the Names in Alphabetical Order


This C Program helps to sort the given names in an alphabetical order. The program
first accepts the input names from the user and then sorts the given names in an
alphabetical order by using string operation.

#include <stdio.h>
#include <string.h>
void main()
{
char name[12][9], tname[12][9], temp[9];
int i, j, k, number;
printf(“Enter the value of number \n”);
scanf(“%d”, &number);
printf(“Enter %d names n”, \n);
for (k = 0; k< number; k++)
{
scanf(“%s”, name[k]);
strcpy(tname[k], name[k]);
}
for (i = 0; i < number - 1 ; i++)
{
for (j = i + 1; j < number; j++)
{
if (strcmp(name[i], name[j]) > 0)
{
strcpy(temp, name[i]);
strcpy(name[i], name[j]);
strcpy(name[j], temp);
}
}

Book 8.indb 105 6/7/2017 1:29:07 PM


106 Fundamentals of Computing and Programming

printf(“\n----------------------------------------\n”);
printf(“Input Names
Sorted names\n”);
printf(“------------------------------------------\n”);
for (i = 0; i < number; i++)
{
printf(“%s\t\t%s\n”, tname[i], name[i]);
}
printf(“------------------------------------------\n”);
}

Program 3.17 Search operation in an array

The output of the above program would be:


Enter the value of number
5
Enter 5 names
Sam
John
Mary
David
Atarah
----------------------------------------
Input Names Sorted names
------------------------------------------
Sam Atarah
John David
Mary John
David Mary
Atarah Sam
------------------------------------------

3.6.4 C Program to Read an Array and Then Search for a Given Element in the Array
This C program intends to read the array elements and search for an element in the
given array.
#include <stdio.h>
#include <Stdlib.h>
void main()
{
int array[20];
int i, low, mid, high, element, size;
printf(“Enter the array size \n”);
scanf(“%d”, &size);
printf(“Enter the elements of the array \n”);
for (i = 0; i < size; i++)
{

Book 8.indb 106 6/7/2017 1:29:07 PM


Arrays and Strings 107

scanf(“%d”, &array[i]);
}
printf(“Enter the element to be searched \n”);
scanf(“%d”, &element);
/* search begins */
low = 0;
high = (size - 1);
while (low <= high)
{
mid = (low + high) / 2;
if (element == array[mid])
{
printf(“Successfully found the required
element\n”);
return;
}
if (element< array[mid])
high = mid - 1;
else
low = mid + 1;
}
printf(“The given integer cannot be found in the list
\n”);
}
Program 3.18 Transpose operation in Matrix

The output of the above program would be:


Enter the array size
4
Enter the elements of the array
45
280
100
400
Enter the key
280
Successfully found the required element

3.7 MATRIX OPERATIONS

A matrix is defined as a rectangular array of numbers or symbols arranged in rows and


columns.This section explains the programs written in C containing matrix operations.

Book 8.indb 107 6/7/2017 1:29:07 PM


108 Fundamentals of Computing and Programming

3.7.1 C program to Find the Transpose of a Given Matrix


Transpose corresponds to exchange of places. Transpose of a matrix corresponds to a
matrix that is obtained by interchanging each row and corresponding column of the
matrix.

#include <stdio.h>
void main()
{
static int array[10][10];
int i, j, k,l, m, n;
printf(“Enter the matrix order \n”);
scanf(“%d %d”, &m, &n);
printf(“Enter the matrix coefficients\n”);
for (k = 0; k < m; ++k)
{
for (l = 0; l < n; ++l)
{
scanf(“%d”, &array[k][l]);
}
}
printf(“The given matrix is \n”);
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
printf(“ %d”, array[i][j]);
}
printf(“\n”);
}
printf(“Transpose of matrix is \n”);
for (j = 0; j < n; ++j)
{
for (i = 0; i < m; ++i)
{
printf(“ %d”, array[i][j]);
}
printf(“\n”);
}
}

Program 3.19 Calculation of Sum in matrix

The output of the above program would be:


Enter the matrix order:
33

Book 8.indb 108 6/7/2017 1:29:07 PM


Arrays and Strings 109

Enter the matrix coefficients:


1 2 3
4 5 6
7 8 9
The given matrix is:
1 2 3
4 5 6
7 8 9
Transpose of matrix is:
1 4 7
2 5 8
3 6 9

3.7.2 C Program to Find the Sum of Each Row and Each Column of an M×N Matrix
This C Program intends to find the sum of each row and each column of a given M×N
matrix. The program takes an M×N matrix as input. Then the program adds each row
of the matrix and also adds each column of the matrix.

#include <stdio.h>
void main ()
{
static int arr[10][10];
int i, j, k, l, m, n, sum = 0;
printf(“Enter the matrix order \n”);
scanf(“%d %d”, &m, &n);
printf(“Enter the matrix co-efficients\n”);
for (k = 0; k < m; ++k)
{
for (l = 0; l < n; ++l)
{
scanf(“%d”, &arr[k][l]);
}
}
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
sum = sum + arr[i][j] ;
}
printf(“Sum of the %d row is = %d\n”, i, sum);
sum = 0;

Book 8.indb 109 6/7/2017 1:29:07 PM


110 Fundamentals of Computing and Programming

}
sum = 0;
for (j = 0; j < n; ++j)
{
for (i = 0; i < m; ++i)
{
sum = sum + arr[i][j];
}
printf(“Sum of the %d column is = %d\n”, j, sum);
sum = 0;
}
}

Program 3.20 Program to check if two matrices are equal

The output of the above program is:


Enter the matrix order:
22
Enter the matrix co-efficients:
12 24
40 60
Sum of the 0th row is: 36
Sum of the 1st row is: 100
Sum of the 0thcolumn is: 52
Sum of the 1stcolumn is: 84

3.7.3 C Program to Check if Two Matrices are Equal


This C Program checks whether the given 2 matrices elements are equal. The program
first reads the 2 input matrices and then checks whether both the input matrices are
equal. If both the matrices are equal then display the output as they are equal. If both
the matrices are not equal then display that the matrices are different.

#include <stdio.h>
#include <stdlib.h>
void main()
{
int a[10][10], b[10][10];
int i, j, k, l, row1, column1, row2, column2, flag = 1;
printf(“Enter the matrix A order \n”);
scanf(“%d %d”, &row1, &column1);
printf(“Enter the matrix B order \n”);
scanf(“%d %d”, &row2, &column2);
printf(“Enter the matrix A elements \n”);
for (k = 0; k < row1; k++)

Book 8.indb 110 6/7/2017 1:29:07 PM


Arrays and Strings 111

{
for (l = 0; l < column1; l++)
{
scanf(“%d”, &a[k][l]);
}
}
printf(“Enter the matrix B elements \n”);
for (k = 0; k < row2; k++)
{
for (l = 0; l < column2; l++)
{
scanf(“%d”, &b[k][l]);
}
}
/* Comparing two matrices for equality */
if (row1 == row2 && column1 == column2)
{
printf(“The given input matrices can be compared \n”);
for (i = 0; i < row1; i++)
{
for (j = 0; j < column2; j++)
{
if (a[i][j] != b[i][j])
{
flag = 0;
break;
}
}
}
}
else
{
printf(“ Cannot be compared\n”);
exit(1);
}
if (flag == 1)
printf(“Two matrices are equal \n”);
else
printf(“But, two matrices are not equal \n”);
}

The output of the above program is:


Enter the matrix A order:
2 2

Book 8.indb 111 6/7/2017 1:29:08 PM


112 Fundamentals of Computing and Programming

Enter the matrix Border:


2 2
Enter the matrix A elements:
10 20
30 40
Enter the matrix B elements:
50 60
70 80
The given input matrices can be compared
But, two matrices are not equal

KEY POINTS TO REMEMBER

•• An array is defined as a collection of data items, all of the same data type and
also accessed using a common array name.
•• The two basic types of arrays are:
▪▪ Single-dimensional array
▪▪ Multidimensional array
•• Strings are declared in the same was as arrays. Types are:
▪▪ Using arrays
▪▪ Using pointers
•• Arrays in C stores the data under a single variable name with an index.
•• Multidimensional arrays have a finite number of rows and columns to store the
data.
•• An array is also called an array data structure.
•• One dimensional arrays are also called linear arrays as they are stored sequentially
in the memory.
•• Primitive types are the basic data types available within the C programming
language.
•• A data type is a set of data with values having the predefined characteristics.
Examples include:
▪▪ Integer
▪▪ Float
▪▪ Character
▪▪ String
▪▪ Pointer
•• The “string.h” is a header that defines the variable type, one macro and various
functions for the purpose of manipulation of the arrays of characters.

Book 8.indb 112 6/7/2017 1:29:08 PM


Arrays and Strings 113

•• The strcpy function helps copy the string pointed by s2 to the object that references
to s1.
•• A string can be reversed using strrev function. It is defined in “string.h”
header file and used in C programming language mostly.
•• The input function scanf() is used with %s format specifier in order to read a
string input from the user through the terminal.
•• When an array is declared, it is the duty of the compiler to allocate sufficient
amount of memory that is necessary to contain all the array elements.
•• We can declare a pointer of integer type to point to the array ‘array1’ as follows:
int *q;
q = array1;
or q = &array1[0]; // Both are same

•• One of the general purpose standard library of C programming is stdlib.h and


includes functions for memory allocation, process control, etc.
•• Pointers can also be used for the purpose of creating strings. Pointer variables of
char data type are generally treated as strings.
•• The strcmp function always returns an integer that could be:
▪▪ Less than zero
▪▪ Greater than zero
▪▪ Equal to zero
•• The strcat helps in appending a copy of the character string pointed by source
to the end of the character string pointed by the destination.

EXERCISE

1. What is the meant by an array in C programming and how is it useful?


2. What is an array indexing in C programming language?
3. Differentiate between single and multidimensional arrays with examples.
4. How to declare an array in C programming language?
5. How to initialize an array in C programming?
6. Detail the method to insert and print array elements.
7. How do we pass arrays to a function?
8. Write a simple C program to find the largest element of an array.
9. What is the relation between arrays and strings? Explain with examples.
10. What are multidimensional arrays? Give examples.
11. How do we declare strings?
12. How do we initialize strings?
13. How do we use scanf() to read a string?

Book 8.indb 113 6/7/2017 1:29:08 PM


114 Fundamentals of Computing and Programming

14. Explain with a program the method for reading a line of text.
15. Differentiate between gets() and puts() functions.
16. How do we pass strings to functions?
17. What are the different string handling functions.
18. Write a C program to find the frequency of characters in a string.
19. Write a C program to count the number of vowels, consonants and so on.
20. Write a C program to remove all the characters present in a string except the
alphabet.
21. What is the output of this C code?
#include <stdio.h>
void main()
{
int b[3] = {2, 3, 4};
int *p = b;
printf("%p\t%p", p, b);
}

a. Different address gets printed


b. Compilation error
c. Same address gets printed
d. None of the above
22. What is the output of this C code?
#include <stdio.h>
void main()
{
char *t= "hello";
char *q = t;
printf("%c\t%c", 1[q], t[1]);
}
a. Runtime error b. h h
c. l l d. e e
23. Write a C program to return the anagram subsets from a given set of strings.
24. Write a C program to check if the ordered string is present in the input string.
25. How do you print the duplicate characters from the input string. Provide the logic.
26. How do you reverse a string using recursion?
27. Write a C program to convert the numeric string into int.
28. Write a C program to multiply two 3 * 3 matrices.
29. How is a string stored in the memory?
30. What is “String.h”? What is the use of it?

Book 8.indb 114 6/7/2017 1:29:08 PM


Arrays and Strings 115

QUESTIONS TO TEST YOUR SKILLS

1. What is the output of the code?


void main()
{
int a[3]={0,1,2};
printf(“%d”,a);
}
a. 0 b. 1
c. 2 d. Garbage value
Answer: d. Since ‘a’ is an array specifying without index leads it to a different location
and gives garbage value. Array is a collection of variables of same data type.
2. What is the output of the code?
void main()
{
int a[3]=(0,1,2);
printf(“%d”,a[1]);
}
a. 0 b. 1
c. Error d. Garbage value
Answer: c. Arrays cannot be initialised by using parenthesis.
3. What is the output of the code?
void main()
{
int a[3]={3,1,2};
printf(“%d”,a[3]);
}
a. 0 b. Error
c. 2 d. Garbage value
Answer: a. Non-specified memory locations are initialised to default values internally.
4. What is the output of the code?
void main()
{
int a[3]={3,,1,2};
printf(“%d”,a[1]);
}
a. 0 b. Error
c. 1 d. Garbage value
Answer: b. Two consecutive commas is not a valid syntax.
5. What is the output of the code?
void main()
{

Book 8.indb 115 6/7/2017 1:29:08 PM


116 Fundamentals of Computing and Programming

int a[3]={3,1,2};
printf(“%d”,a[5]);
}
a. 0 b. Error
c. 2 d. Garbage value
Answer: a. Locations not initialised are given 0 internally.
6. What is the output of the code?
void main()
{
int a[]={3,1,2};
printf(“%d”,a[7]);
}
a. 0 b. Error
c. 2 d. Garbage value
Answer: d. Arrays declared without any specified length are dynamic and don’t initialise
memory location. So here the far location leads to garbage value.
7. What is the output of the code?
void main()
{
int a[3]={3,1,2};
printf(“%d”,a[-1]);
}
a. 0 b. Error
c. 2 d. Garbage value
Answer: a. Non-specified memory locations are initialised to 0. Another important fact
is ‘GCC’ doesn’t give array index out of bound error.
8. What is the output of the code?
void main()
{
int a[3]={3,1,2};
printf(“%d”,a[23435]);
}
a. 0 b. Error
c. 2 d. Garbage value
Answer: b. The fact holds good for small index, while larger index causes segmentation
fault. It is compiler dependant because the memory limitation for program is
varying. The error is because the large value crosses the memory limit.
9. What is the output of the code?
void main()
{
int a[3]={ };
printf(“%d”,a[2]);
}

Book 8.indb 116 6/7/2017 1:29:08 PM


Arrays and Strings 117

a. 0 b. Error
c. 2 d. Garbage value
Answer: a. Even though array is just declared and not initialised the value gets 0.
10. What is the output of the code?
void main()
{
int a[3]={null};
printf(“%d”,a[3]);
}
a. 0 b. Error
c. 2 d. Garbage value
Answer: b. Null is not a valid keyword.
11. What is the output of the code?
void main()
{
int a[3]={1 2 3};
printf(“%d”,a[2]);
}
a. 3 b. Error
c. 2 d. Garbage value
Answer: b. Space doesn’t separate the entries. It expects a separator like comma. Comma
in between the numbers makes it illegal.
12. What is the output of the code?
void main()
{
float a[3]={};
printf(“%d”,a[3]);
}
a. 0.000000 b. Error
c. 2.000000 d. Garbage value
Answer: a. Default value of float is 0.000000
13. What is the output of the code?
void main()
{
float a[3]={1,2,3};
printf(“%f”,a[2]);
}
a. 0 b. 0.000000
c. 3.000000 d. Garbage value
Answer: c. Internal conversion makes 3 into 3.000000.

Book 8.indb 117 6/7/2017 1:29:08 PM


118 Fundamentals of Computing and Programming

14. What is the output of the code?


void main()
{
float a[3]={1,2.34, ‘b’};
printf(“%f”,a[2]);
}
a. 0.000000 b. Error
c. 98.00000 d. Garbage value
Answer: c. Even though an array is a collection of data of same data types, it tries to
convert all the given entries into the specified data type. The ASCII of ‘b’ is
98 and results in 98.000000
15. What is the output of the code?
void main()
{
char a[3]={1,2.34, ‘b’};
printf(“%d”,a[1]);
}
a. 0 b. Error
c. 2 d. Garbage value
Answer: d. On the attempt of converting the float into char results in some garbage
symbol.
16. What is the output of the code?
void main()
{
int a[3]={1,2,3,null};
printf(“%d”,a[3]);
}
a. 0 b. Error
c. 2 d. Garbage value
Answer: b. Null is not a valid keyword
17. What is the output of the code?
void main()
{
int a[3];
printf(“%d”,a[2]);
}
a. 0 b. Error
c. 1 d. Garbage value
Answer: a. Default value of int is 0.

Book 8.indb 118 6/7/2017 1:29:08 PM


Arrays and Strings 119

18. What is the output of the code?


void main()
{ int a[3];
a[1]=5,a[2]=3;
printf(“%lu”,a[1]);}
a. 0 b. 5
c. Error d. None of the above
Answer: b. Arrays initialising can also be done for multiple values in a single statement.
19. What is the output of the code?
void main()
{
int a[ ][ ]={};
printf(“%d”,a[1][1]);
}
a. 0 b. Error
c. 2 d. Garbage value
Answer: b. While declaring a multidimensional array the scalar cannot be completely
left free.
20. What is the difference between the codes?
void main() void main()
{ {
int a[4][3]; int a[4][3]={ };
printf(“%d”,a[2][3]); printf (“%d”, a[2][3]);
} }
a. No difference
b. They give same output but are logically different
c. They are completely different and give different output
d. They are logically same and gives different output.
Answer: c. In the first program the two-dimensional array is declared but not initiated
even with null so the output is some garbage value. While the second program
initialises the same array to null. This gives the output as 0. Unlike single-
dimensional array unless it is initialised to null it will take 0.

Book 8.indb 119 6/7/2017 1:29:08 PM


4 FUNCTIONS: AN IN-DEPTH ANALYSIS
AND UNDERSTANDING

LEARNING OBJECTIVES

After reading this chapter, the reader would be able to understand:


•• What a function in C programming is all about?
•• Why a function is needed and where functions can be used?
•• What is an user defined function and how is it handy?
•• How to declare a function?
•• Difference between call by value and call by reference.
•• Concept of recursion.
•• What a pointer is all about?
•• What a null pointer is?
•• How and where a void pointer is used?
•• Usage of arrays with pointers.

4.1 INTRODUCTION

Every programmer who uses C would have already come across writing at the least
one program would have used a function. main() is the function that all the C programs
have for sure. Hence, the reader has been already introduced to the function concept
through the sample programs and concepts dealt in this book in the previous chapters.
This chapter aims at getting a better clarity on the function and its internal details.
Reader is provided with clear examples and explanations for each of them to make the
understanding better.
Experts say that functions are the basic constructs in a C program. When someone
asks why to use function, the straightforward answer is: usage of functions shall improve
modularity, readability, understandability and debugging also becomes easier.
A function can be defined as a set of statements grouped together to perform certain
tasks. Each and every C program shall have at least one function, which we referred to
earlier called main ().

Contribution by Dr. Shriram K Vasudevan, Dept. of CSE, Amrita School of Engineering, Amrita University,
Coimbatore, India.

Fundamentals of Computing and Programming

Book 8.indb 120 6/7/2017 1:29:08 PM


Functions: An In-depth Analysis and Understanding 121

An example is always useful and handy while reading any concept. Same is the case
here. A simple scenario is taken and basics of the functions are explained. The reader
should go through the code 4.1 carefully which has been explained clearly. The program
is meant to add numbers, i.e., addition of two numbers, many times in a code.

#include<stdio.h>
int main()
{
// Variable declaration
int a, b, c, d, e, f, sum;

// Iteration – 1 for first set of inputs.


// get inputs from the user.
scanf(“%d %d”, &a, &b);
// add the numbers. Store the result in sum.
sum = a + b;
// Use the calculated value
printf(“%d\n”, sum);

// Iteration -2 for second set of inputs.


scanf(“%d %d”, &c, &d);
sum = c + d;
printf(“%d\n”, sum);
// Iteration -3 for second set of inputs.
scanf(“%d %d”, &e, &f);
sum = e + f;
printf(“%d\n”, sum);
return 0;
// End of program
}

Program 4.1 Addition of two numbers – thrice

From the above code, the reader can understand that the code shall ask the user to
enter 2 numbers thrice, one after another and then perform the addition operation. The
effective number of lines of the code is 18 in this case. Also, the same piece of code has
been used in three places for addition, which the reader can observe. If the same process
has been done 10 times, the same piece of code shall be used in 10 different places in
the same code. Hence, this is seen as an inefficient and incompetent approach of coding.
Here is where the concept of functions would help.
This case was simple of addition of two numbers and did not have much of the hassle
in writing code or execution of the same. Considering a scenario like railway ticket
booking or a movie booking, the case would be much more complex and the number
of lines would be unimaginable. Then, it would become difficult for someone to
manage the code or to debug the code. In such scenarios, the code length should be as

Book 8.indb 121 6/7/2017 1:29:08 PM


122 Fundamentals of Computing and Programming

minimal as possible. Reason for someone to be cautious about having lesser number of
lines of code is presented below:
1. Readability of the program gets reduced, when the number of lines grows.
2. Debugging capability gets harder and tougher. It is almost double the work for
the debugger if the code length is raised unnecessarily.
3. No benefit can be obtained by the reusability factor, all the codes written should
be reusable.
So, what is the strategy to tackle the above threats? The only available option in front
of us is the functions. Usage of function shall make the life easier. There are two kinds
of function. One could be factory built, i.e., supported by the compiler itself. Another
version is user defined. The function which the user builds is referred to as user defined
function. Factory built or the built-in functions are readily available for the user to make
use of it or call whenever needed. One simple example we can refer here is the function
printf () or scanf(). We never care or know who has written it. But, we consume
it as and when needed. The attention shall be given in this chapter towards the user
defined functions and the reader shall be introduced with the same through examples.
In a short way, the following are the advantages one would get through the functions
being used in the code.
1. Increased and improved reusability: Whenever there is a need to use same set
of instructions, repeatedly, it becomes inevitable to use functions. This will not
enforce the programmer to write the same piece of code again and again. Instead,
he can reuse the pre-written code, just like using printf or scanf whenever
needed. This would certainly promote and increase the modularity and reusability
by leaps and bounds.
2. More comfortable debugging: When someone has used function concept, if
there is a correction to be done in the code, it would be easier to make the change
at one place instead of multiple places. When someone uses functions, if the
correction is carried out in a place, it would get reflected in other places without
giving a hefty task for the programmer to do.
3. Creation of library functions: If someone wishes to build a function and in the
event of it to be used as common function which everyone can use, like printf
(), it can also be done and the reader can understand this after reading this
chapter.

4.2 DECLARATION: FUNCTION HAS TO BE DECLARED THIS WAY (PROTOTYPE)

One can remember how the variable has to be declared before use in C programming.
Similar rule has to be used here for the functions. One has to declare a function before
using it. Else, the compiler shall not be aware of the function and would throw an error.
The declaration shall be made inside the main() or outside the main(). The syntax is
presented below for reference.

Book 8.indb 122 6/7/2017 1:29:08 PM


Functions: An In-depth Analysis and Understanding 123

Syntax:
<return_type> function_name (types_of_ parameters)
A function must return a value. Any function in fact, shall be returning a value. It
can be of any type. To make it simple, a function must return a value of any type. For
an instance, if sum of 10 numbers is calculated, the return would be only type integer,
int. It can be any type like char or float. One point has to be noted here. If the function
has to return nothing, it should be declared ‘void’.
Naming convention is very important with respect to functions. One should just think
a name which is relevant to the task to be done. For example, if the function is meant
to add two integers one can name it as add_func (). The reader is introduced with
few function declaration examples.
Examples:
void sum(int,int);
int sum(int,int);
floatavg(int []);  passing an array variable.
char gender(struct student);  passing a structure variable.
void swap(int,int);
sum(int,int); If no return value is mentioned, default data type- ‘int’ is used.

Note: Function declaration statement is also known as function prototype..! Every


function shall be having function prototype. Reader can see Code 4.2 to understand
prototype.

4.2.1 Function Call


Every function has to be named before use. Take an example of a person with a name
John. How will someone call that person? Through the name John. Same is the case
here. When you name a function, you need to call the function by the same name. When
you call a person you should call Mr. or Dr. or Prof. appropriately. Similarly, every
functional call should have the return type and the parameter type should be mentioned
clearly.
At this time, it is very important to know how many arguments can be passed to a
function. It is 256. Maximum 256 arguments can be passed to a function.
Examples of a function call (reader has to relate this with previous declarations)
answer=sum(10,20). Reader has to note that sum() returns an int (integer) value. The
programmer should collect the returned value in an integer variable answer. All the
functions have a return value and type of the same has to be mentioned as discussed
earlier.
One more example would help the reader.
•• Average=avg(a) a is an integer array. Average is a float variable.
•• Sex=gender(s)s is a structure variable. Sex is a char variable.

Book 8.indb 123 6/7/2017 1:29:08 PM


124 Fundamentals of Computing and Programming

4.2.2 Function Definition


We have come to the important part of the learning. Defining the function is that. Well,
what is the function definition? Every function has to do something. And defining that
logic is referred as function definition. A simple example is presented with the function
name add(). The code is actually self-explanatory. One can understand this easily.

voidadd (int x,int y)


{
intz;
z=x+y;
printf(“The sum value is: %d”,z);
}

4.3 WHAT IS CALL BY REFERENCE? WHAT IS CALL BY VALUE?

A C function can be called by two different ways. One can be Call by Value and other
is Call by Reference. Both have thier importance and value. Two programs are drafted
below, one after another to explain the reader the importance of both the methods.

4.3.1 Call by Value


In the call by value, the value of the variable itself (i.e. copy) is passed to the function
as a parameter. Here, the copy of the value shall be taken as an argument and shall be
passed to the called function. Hence, one can easily understand the fact behind. The
arguments which are sent are the copy and they occupy memory in addition. The terms
to be used here are formal parameters and actual parameters. One can understand what
formal parameter is and what actual parameter is with the following example.
#include<stdio.h>
// This is the function prototype. One should understand the reason behind.
void swap(int a, int b);
int main()
{
int a = 2, b = 3;
// Function is called here and this called call by value.
printf The Default Values = %d a and b = %d”, a, b);
swap(a, b);
getchar ();
}
// here, one can see, a, b are becoming x and y. This is copy.
void swap(int x, int y)

Book 8.indb 124 6/7/2017 1:29:08 PM


Functions: An In-depth Analysis and Understanding 125

{
inttmp;
tmp = x;
x = y;
y = tmp;
printf(“ \n The values after the swap a = %d and b = %d”, x, y);
}
Program 4.2 Call by value – 2 numbers swapped

Here in the above code, the actual arguments a, b are copied as x, y which are referred
as formal arguments. The program shall get the copy of a and b to x and y here which
is referred as call by value. The value is transferred to another variable.
• The result is presented below after the execution:

Result for the Program 4.2

To summarize what actually happened here in call by value, the following points are
narrated:
•• A copy of the value shall be given to the function definition. One should understand
this clearly. It is a copy which has to be sent.
•• The function definition absolutely is related to the copy of the original value and
there is no action on the original value. The entire deal is done on the copy of the
value and nothing else.
•• Any change which has happened is with the copy alone. Original value remains
the same in the memory.

4.3.2 Call by Reference


There is a change here when compared to the previous method. This method deals with
the reference, i.e., the address. The address of the variable is passed as an argument
instead of the copy of the variable. In fact, the formal parameter and actual parameter
is connected and any change in one of those will affect the other too. Well, to make it
simple, both the formal and actual parameters are the same. They share the same address
space. To make it simple, one would not pass the copy of the value instead address of
the variable shall be shared. The code is presented below as Program 4.3 for the reference
of the reader.

Book 8.indb 125 6/7/2017 1:29:08 PM


126 Fundamentals of Computing and Programming

#include<stdio.h>
// This is the function prototype. One should understand the reason behind.
void swap(int *a, int *b);

int main()
{
int a = 2, b = 4;
// Function is called here and this called call by value.
printf(“\n The Default Values = %d a and b = %d”, a, b);
swap(&a, &b);
// Here the reader can observe that address is also included as part of the call.
getchar ();
}

void swap(int *x, int *y)


{
inttmp;
tmp = *x;
*x = *y;
*y = tmp;
printf(“ \n The values after the swap a = %d and b = %d”, *x, *y);
}

Program 4.3 Call by reference – address is a part of the code here

Result for the Program 4.3

The result for Code 4.3 has been presented above. To make it concise, one can read
the following points about the call by reference.
•• Address of the variable is passed here which is different from call by value.
•• The value of the actual parameter gets modified by the formal parameter, i.e., both
share the same memory space.

4.4 RECURSION AND ITS IMPORTANCE

Recursion is an important concept in C Programming which is a frequently asked


question even in the interviews. What is recursion? Simple. Let us see the same with
examples. The function can call itself is referred as recursion. Where do we find the
applications for the recursion functions? The options are plenty. Wherever there is a

Book 8.indb 126 6/7/2017 1:29:08 PM


Functions: An In-depth Analysis and Understanding 127

mathematical operation like Fibonacci series, it would be easy to go with the


recursion concept.
An example with just a skeleton is presented below to make the reader understand
what recursion is. Reader shall be presented with a complete code shortly with recursion
being carried out.

void example_recurse ( ) {
example_recurse ( ) ; // This is recursion, A function calls itself.
}
int main ( )
{
example_recurse ( ); // Function call, this is a traditional stuff.
}
A code for the factorial through recursion is presented below for the reader’s reference.
Reader shall be provided with technical explanation on the same.

#include <stdio.h>
intfactorial_calculation(int i) {

if(i <= 1) {
return 1;
}
return i * factorial_calculation(i - 1);
// This is what we can refer as recursion! A function called by itself.
}
int main() {
int i = 5;
printf(“Factorial
is presented here %d is %d\n”, i, factorial_calculation(i));
// This is a function call. i.e. we can call the function as we do regularly.
getchar ();
return 0;
}

Program 4.4 Recursion example

The execution results are presented below as a screenshot.

Execution result for the Program 4.4

The reader would have observed that the factorial_calculation function is called from
itself. This is referred to as recursion. It made the execution and logic easier than
traditional calculation method .

Book 8.indb 127 6/7/2017 1:29:09 PM


128 Fundamentals of Computing and Programming

One question for the readers to answer. What would be the output of the following
code? Can you guess?
void recursion()
{
printf (“\n I love India”);
recursion(); // This is recursion!
}
int main()
{
recursion(); // Function call
return 0;
}

Program 4.5 A simple program for the readers

The answer is really interesting and awesome. This code will print I love India up
till the stack size limit. It can’t keep printing the text forever.

Execution result for Program 4.5

One more example shall be very handy here for the reader. Most of the books or
articles shall be citing the Fibonacci series example and we are also following the legacy.
The code for Fibonacci series is presented below with recursion being used as part.
Readers on carefully going through shall understand the scenario.

Book 8.indb 128 6/7/2017 1:29:09 PM


Functions: An In-depth Analysis and Understanding 129

#include <stdio.h>
// This is the function to be recursively called.
intfibonacci_series(int x) {
if(x == 0) {
return 0;
}

if(x == 1) {
return 1;
}
returnfibonacci_series(x-1) + fibonacci_series(x-2); // this is called recursion.
// This makes the life easier!
}

int main() {

int x;

for (x = 0; x< 5; x++) { // here, we print fibonacci series for 5.


printf(“%d\t\n”, fibonacci_series(x));
}

return 0;
}

Program 4.6 Fibonacci series for recursion

The output for the above code shown in Program 4.6 gives the following output.

Execution result for Program 4.6

Readers can try n number of examples using this logic. Recursion shall be surely
asked as a question in any interview or written tests. It is a good practice to really use
recursion wherever possible!

Book 8.indb 129 6/7/2017 1:29:09 PM


130 Fundamentals of Computing and Programming

4.5 POINTER AND ITS IMPORTANCE

Pointer is a well-known topic for all. People have given a wrong projection about
pointers as it is difficult to learn and to understand. Actually, pointers are not difficult.
They are easier than any other topic and more interesting in deed. This complete section
shall elaborate about the pointers, its pros and cons, internal concepts, etc. clearly with
examples. Readers are encouraged to try all these in the compiler and to see what
happens. Let us ask a few questions here. One by one, we shall reveal the answer.

Why someone has to use pointers?


Readers were introduced with call by reference concept sometime back in this same
chapter. What happened there? Without copying the variables, we could easily complete
the task. Pointers only enabled this. One can access the content of a variable through
its address. There are many operations which demand address to be accessed to work
on the content. In all those cases, pointers become inevitable. No program in the data
structures shall be possible without pointers.

How to define a pointer?


A pointer is also a variable. It can hold an address inside. It is a container holding an
address. A pointer shall be having a type. It can hold the address of the same type. For
instance, a pointer of type integer shall hold the address of an integer variable. If a
pointer is of type char, it can hold the address of a character variable. A pointer can be
declared exactly like a variable declaration, but there has to be asterisk (*) in front.
For instance, reader shall be introduced with following declaration:
1. int *j; // This is an integer pointer.
2. char *k; // This is a character pointer.
3. float *l; // This is a float pointer.
The declaration of the pointer is the next step to be carried out. Initializing pointers
have a lot of similarity with variable initialization. But, reader should understand that,
pointers are meant for storing address. Hence, an ampersand (&) is to be used. One
should remember that & is referred as address of operator. An example is presented
below.
int x = 10;
float y = 20.0
i = &x;
j = &y;
k = NULL;
This above piece of code will initialize pointer “i” with address of variable x;
Meanwhile, initialize pointer “j” with address of variable y. And, here the reader
has a new term NULL. It is assigned to the pointer k. NULL is assigned to a pointer

Book 8.indb 130 6/7/2017 1:29:09 PM


Functions: An In-depth Analysis and Understanding 131

and it is referred as NULL pointer. Null pointer usage is explained shortly and it is a
necessary practice for a programmer to use.

x 10 20.0 y

i j k 0 (NULL)

1000 1004 1008

Figure 4.1 Pointer example.

It is always an excellent practice to assign NULL to a pointer during the declaration


time itself. Else, the pointer may hold some random content (say, garbage) inside it. If
assigned with NULL it will not have any garbage. While assigning the address, the
NULL content will be overwritten with the apt content. The following code snippet
shall help the reader in understanding the effect of using NULL Pointer.

4.5.1 A Code with Null Pointer


An easy way to get NULL pointer into the code is to use the keyword NULL in the
code. The NULL is definied in the files stdio.h, stdlib.h. The usage of NULL
pointer is presented in below code 4.7.

# include <stdio.h>
int main()
{
int *p; // This is the pointer P.
p = NULL; // This is how we assign NULL to a pointer.
printf (“\n The value of P is %u”, p);
return 0;
}

Program 4.7 Usage of NULL pointer

The result of the usage of NULL Pointer is presented below.

Execution result for the code 4.7

Book 8.indb 131 6/7/2017 1:29:09 PM


132 Fundamentals of Computing and Programming

4.5.2 Void Pointer – An Interesting and Important Concept


One who has learnt the concept of pointer must learn the void pointer. It is like icing
over the cake. It is a special type of pointer. It is very versatile one and can point to
any data type. Meaning which, it can hold the address of an integer, float or a char. It
is not too rigid about whose address does it hold. Only point to be careful about void
pointer is, since it does not know what type of data address it is holding, type casting
has to be done to make it work fine. Reader shall understand what type casting is
through this example code presented below which also explains the usage of void
pointer.
# include <stdio.h>
int main ()
{
int a = 5;
double b = 3.233;
void *vp; // void pointer, see the way how it has been declared.
vp = &a;
printf (“\n a = %d”, *((int *)vp)); // Here, it becomes integer pointer.
vp = &b;
printf (“\n b = %f”, *((double *)vp)); // Here, it becomes double pointer.
return 0;
}

Program 4.8 Usage of void pointer

The code above reveals the fact that the pointer vp is called void pointer and it can
hold the address of an integer a initially. For the compiler to understand that, the address
which is about to be stored is address of an integer, the type casting is carried out.
Similarly, the next time, address of a double is assigned and type casting is done to
make the compiler understand the address assigned is address of the type double. If
two different pointers had been used, it would have occupied 4 bytes + 4 bytes of
memory. Also, it would be difficult to tackle many pointers. Now, here, it is just one
pointer what we have in hand which does the work precisely. The output of the above
code is presented below for the reference for the reader.

Execution result for the code 4.8

If we have not used void pointer, we would have been in a position to use two
pointers. Assume a situation where one has to use 10 pointers. 10 * 4 = 40 bytes of

Book 8.indb 132 6/7/2017 1:29:10 PM


Functions: An In-depth Analysis and Understanding 133

memory is wasted and it would have been just 4 bytes if void pointer is used. Reader
is strongly encouraged to use void and null pointers in all the codes wherever they are
using pointers. It is a strongly recommended practice from the industry.

4.5.3 Accessing the Pointer Variable’s Contents


How will someone access the normal variable? Through its name. Similarly, how to
access the pointer variable? Simple. With an asterisk in the front. Take an example here.
Consider the printf statement “printf (“%u”, *q);”. This statement shall print the
content of the pointer variable q. Here, we preferred %u. For printing the address,
programmers always prefer %u. The reader has to understand this. User “*” for printing
the content of the pointer variable. To print the address use “&”. “*” is referred as
value of operator while “&” is referred as the address of operator.
A small piece of code is presented below to understand the above conveyed inputs.
Readers are prompted to read through the code carefully.
# include <stdio.h>
int main ()
{
intvar = 99; // A simple variable with 99 assigned to it.
int *p = NULL; //This is a NULL Pointer. Means, assigning 0 to it.
char *c = NULL;
float *f = 0;
p = &var; // Address is assigned to pointer.
printf (“\n Printing variable = %d”,var);
printf (“\n Printing using pointer (*) = %d”,*p);
printf (“\n Address of var = %u”,&var); // We are using %u to print the address.
printf (“\n Address of pointer p = %u”,&p);
printf (“\n Address of pointer c = %u”,&c);
printf (“\n Address of pointer f = %u”,&f);
getchar ();
return 0;
}

Program 4.9 Pointer scenario – An understand

The execution result of above is presented below (Code 4.9) for the better under-
standing of the reader.

Execution result for the code 4.9

Book 8.indb 133 6/7/2017 1:29:10 PM


134 Fundamentals of Computing and Programming

4.5.4 Multiple Indirection


This is an interesting topic of discussion and would certainly raise eyebrows of the
reader. There are cases like pointer to a pointer, pointer to a pointer to a pointer, etc.
The first one is cited as 2 levels and the second one is cited as 3 levels. To get the 2
level pointers accomplished, one should use two * (asterisks) and in 3 level one should
use three asterisks. One can see the code below which shall make the reader understand
the concept better.

# include <stdio.h>
int main ()
{
int var = 99;
int *q;
q = &var;
int **q1;
q1 = &q;
int ***q2;
q2 = &q1;
printf (“\n Address of the variable var: %u”, &var);
printf (“\n The content of q is: %u”, *q);
printf (“\n The content of q1 is: %u”, *q1);
printf (“\n Var = %d”, var); //Printing the variable.
printf (“\n Var = %d (using q1)”,*(*q1));
printf (“\n Var = %d (using q2)”,*(*(*q2)));
getchar ();
return 0;
}

Program 4.10 Pointer to a pointer, pointer to a pointer to a pointer

Execution result for the code 4.10.

Reader can understand the functioning of the pointer through this simple example
and the execution output.

Book 8.indb 134 6/7/2017 1:29:10 PM


Functions: An In-depth Analysis and Understanding 135

4.5.5 Compatibility Among Pointers


The below given discussion we are about to have is an interesting one and will certainly
provoke the thoughts of the reader. Readers can go through the code presented below
and can identify the fault in the code. The fault is made with a purpose and reader on
identifying the same would understand the reason for the intentional fault.
#include<stdio.h>
int main()
{
char d[5];
d=5.99;
getch();
return 0;
}

Program 4.11 A code with intentional mistake

The result the compilation would give is an error, i.e., compilation fault.

Execution result of the code 4.11

One can understand the mistake from the error message. Here, there is a character
array declared in the code. Then, an integer value is assigned to the same. How can the
integer value get fit into the character array? It is something like a person having a
ticket for sleeper class trying to sit in someone else’s reserved ticket. Why is this
discussed here? Simple. The same guidelines are to be followed for pointers. A pointer
of type integer can have only the address of the integer variable. Else, it would be a
failure. One example would bring clarity to the reader better.
#include<stdio.h>
int main()
{
int *p;
float *q;
floatnum = 2.000;
p = &num;
q = &num;
printf (“\n When used with integer pointer: %f”, *p);
printf (“\n When used with float pointer: %f”, *q);
getchar();
return 0;
}

Program 4.12 A code to understand pointer incompatibilities

Book 8.indb 135 6/7/2017 1:29:11 PM


136 Fundamentals of Computing and Programming

Here, if the reader looks in, the float value is assigned to the integer pointer and then
it is assigned properly to the float pointer. Will the code compile? Yes, it would compile
and it will certainly throw warning to alert the programmer stating that there is an
incompatible assignment, please have a look. If it is ignored, the execution result will
be erroneous. Both the warning and execution results are presented below for better
understanding.

Warning message for the code 4.12

Execution result for the code 4.12.

Reader was introduced with the concept of void pointers sometime back in the same
chapter. If the above-mentioned irregularity is to be sorted out, one must use it. Else,
the results will be unexpected and definitely will not be in favour.

4.5.6 A Pointer Advantage


There are situations where one or more entities may want to use the same variable, i.e.,
one particular variable is to be accessed by many functions at the same point in time.
This can be achieved through the pointers. Readers can go through the below given
piece of code to understand this scenario.

#include<stdio.h>
int main()
{
intvar=20, *p1, *p2;
p1 = &var;
p2 = &var;
printf (“\n var = %d (Here, pointer p1 is used)”, *p1);
printf (“\n var = %d (Here, pointer p2 is used)”, *p2);
var = 25;
printf (“\n var = %d (After the change, through p1)”, *p1);
printf (“\n var = %d (After the change, through p2)”, *p2);
getchar ();
return 0;
}
Program 4.13 Two pointers to access same memory location

Book 8.indb 136 6/7/2017 1:29:11 PM


Functions: An In-depth Analysis and Understanding 137

Here, reader can observe that the pointers p1 and p2 both point to the same memory
location. Once the value is changed, and when it is accessed through the pointer p1 or
p2, the effect will remain the same. The variable had 20 initially and then it is updated
as 25. P1 and p2 are both used to point the same variable. The output is presented
below.

Execution result for the code 4.13

Here, one can see from the results that by using p1 or p2 one can access the same
address and this can be used appropriately at places.

4.6 ARRAYS WITH POINTER

An example is always useful and here is the same. Arrays with pointers are the best
concept to learn. It may appear little difficult initially. But, it is not so. Here, we start
with a simple example to fetch the content of the array and to print it.

#include <stdio.h>
int main ()
{
int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// An array here with 10 integers in.
int i;
for (i = 0; i < 10; i++) {
printf(“array[%d] = %d\n”, i, array[i] );
// See the way one can navigate from first element to last element.
}
return 0;
}

Program 4.14 An array with ten integers and printing the content

Book 8.indb 137 6/7/2017 1:29:11 PM


138 Fundamentals of Computing and Programming

When the above code is executed, one would get the following output.

Execution result for the code 4.14

Now, there could be a situation where one has to have an array of pointers. If the
above code (4.14) is connected with this requirement, the following code can be drafted.
There may be a situation when we want to maintain an array, which can store pointers.
What if someone thinks of combining the above code with the prescribed scenario? The
result is the code presented below.

#include <stdio.h>
const int Array_Count = 10;
int main ()
{
int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// An array here with 10 integers in.
int i, *ptr[Array_Count];
for ( i = 0; i <Array_Count; i++) {
ptr[i] = &array[i]; /* assign the address of integer. */
}
for ( i = 0; i <Array_Count; i++) {
printf(“Value of Array[%d] = %d\n”, i, *ptr[i] );
// Reader has to see the way the pointer is used here. Array and pointer together.
}
return 0;
}

Program 4.15 An array with pointer

Book 8.indb 138 6/7/2017 1:29:11 PM


Functions: An In-depth Analysis and Understanding 139

Execution result for the code 4.15

Reader would have now understood the usage of pointer with array.

KEY POINTS TO REMEMBER

•• Functions are used with the motto of improving modularity, reusability.


•• The declaration, definition, function call are the major stakeholders of any function.
In other words, a function is incomplete without these three in place.
•• Actual parameters are those which present in function calls, i.e., the actuals. Formal
parameters are the dummy variables present inside the function definition. They
are the copy of the actuals.
•• The argument to the function can be passed as call by value or call by reference.
Call by value is copy of the variable whereas call by reference is the address of
the variables.
•• Every function must return a value and if it does does not return anything, it
should be declared void.
•• Function which calls itself is called recursive function.
•• A pointer is a container holding the address of some variable.
•• A pointer must be of the same type as the data whose address is to be stored.
•• Null and void pointers are two good practices to be followed in the coding.

EXERCISE

1. What is a function? Why someone has to use function?


2. Write a simple C code to perform division operation without using function
concept. Now, write the same code through the functions concept.
3. What are the basic rules one should keep in mind when using functions?
4. Is there any consideration to be given for naming the functions? Clarify.

Book 8.indb 139 6/7/2017 1:29:12 PM


140 Fundamentals of Computing and Programming

5. How is call by value different from call by reference? Explain with clear example.
6. What is the difference between function declaration and function definition?
Explain with an example.
7. What is recursion? Why is it important? Where can someone use recursion?
8. What is a pointer and how is it useful?
9. How exactly is NULL pointer used in programming?
10. What is void pointer and where is it used?
11. How can someone connect array to a pointer?
12. How can someone use a pointer to increase the accessibility of a shared variable?
13. Write a code using call by reference to identify if a given input is odd or even.
14. Write a code using pointers to add two numbers.
15. Write a simple code to swap two numbers using pointers.

INTERVIEW READINESS QUESTIONS

1. What is the output of the code?


void fun()
{ printf(“hai”);}
void main()
{ fun(); }
a. hai b. fun hai
c. Error d. None of the above
Answer: a. ‘fun()’ is a user defined function. ‘void’ is the return type. It can be
specified based on the return value of the function. ‘void’ means returns
nothing. If any arguments are required it should be specified inside ( ). When
the function is called all the details like current address, current answer all are
stored in the stack which will be used for the control to come back.
2. What is the output of the code?
intsqr(int c)
{ return c*c;}
void main()
{ int a=8,b;
b=sqr(a);
printf(“%d”,b);}
a. 64 b. Garbage value
c. Error d. None of the above
Answer: a. int is the return type since the number returned is integer. The value
returned will be given to the statement where the function is called. ‘return’
is the keyword to return that value.

Book 8.indb 140 6/7/2017 1:29:12 PM


Functions: An In-depth Analysis and Understanding 141

3. What is the output of the code?


intsqr(int c);
void main()
{ int a=8,b;
b=sqr(a);
printf(“%d”,b);}
intsqr(int c)
{ return c*c;}
a. 64 b. Garbage value
c. Error d. None of the above
Answer: a. This works in the same way. The first statement is called function declaration
or prototype. It informs the compiler that such a function is going to be defined
after main. Some compilers require this or else will throw error. And if the
function is defined before ‘main()’ as in the previous case, then declaration
may be skipped.
4. What is the output of the code?
intsqr(int c);
void main()
{ int a=8,b;
b=sqr(a);
printf(“%d”,b);}
intsqr(int d)
{ return d*d;}
a. 64 b. Garbage value
c. Error d. None of the above
Answer: a. The arguments in the function declaration are dummy variables and may
be changed during definition. It will just map the data type of the arguments.
5. What is the output of the code?
intsqr(int );
void main()
{ int a=8,b;
b=sqr(a);
printf(“%d”,b);}
intsqr(int d)
{ return d*d;}
a. 64 b. Garbage value
c. Error d. None of the above
Answer: a. The argument names in the declaration may be skipped as it is a dummy.
6. What is the output of the code?
intsqr(int );
void main()
{ int a=8,b;

Book 8.indb 141 6/7/2017 1:29:12 PM


142 Fundamentals of Computing and Programming

b=sqr(a);
printf(“%d”,b);}
intsqr(int )
{ return c*c;}
a. 64 b. Garbage value
c. Error d. None of the above
Answer: c. The argument names in the definition may not be skipped as it is not a
dummy.
7. What will be the error thrown by the code?
intsqr(int );
void main()
{ int a=8,b;
b=sqr(a);
printf(“%d”,b);}
intsqr(int )
{ return c*c;}
a. ‘c’ undeclared (first use in this function)
b. Parameter name omitted in ‘int sqr(int )’
c. Both ‘a’ and ‘b’
d. None of the above
Answer: c. As the name is skipped accessing it throws the undeclared error.
8. What is the output of the code?
intsqr(char c);
void main()
{ int a=8,b;
b=sqr(a);
printf(“%d”,b);}
intsqr(int c)
{ return c*c;}
a. 64 b. Garbage value
c. Error d. None of the above
Answer: c. The argument name can be changed between the declaration and definition,
but the data types cannot be changed.
9. What will be the error thrown by the code?
intsqr(char c);
void main()
{ int a=8,b;
b=sqr(a);
printf(“%d”,b);}
intsqr(int c)
{ return c*c;}

Book 8.indb 142 6/7/2017 1:29:12 PM


Functions: An In-depth Analysis and Understanding 143

a. ‘c’ undeclared (first use in this function)


b. Conflicting types for ‘sqr’
c. Invalid definition of ‘sqr’ with argument ‘int’
d. None of the above
Answer: b. The declaration will be given more priority. It will be saved inside first and
then the definition will be mapped to it.
10. What is the output of the code?
void main()
{ int a=8,b;
b=sqr(a);
printf(“%d”,b);}
intsqr(int c)
{ return c*c;}
intsqr(char c);
a. 64 b. Garbage value
c. Error d. None of the above
Answer: a. In GCC this doesn’t have a problem. And the declaration done at the last is
also useless. In some compiler this may give error of missing function ‘sqr’ as
it is not declared before ‘main’.
11. What is the output of the code?
voidsqr(char c);
void main()
{ int a=8,b;
b=sqr(a);
printf(“%d”,b);}
intsqr(int c)
{ return c*c;}
a. 64 b. Garbage value
c. Error d. None of the above
Answer: c. The return types between the declaration and definition cannot be changed.
12. What will be the error thrown by the code?
voidsqr(char c);
void main()
{ int a=8,b;
b=sqr(a);
printf(“%d”,b);}
intsqr(int c)
{ return c*c;}
a. Conflicting types for ‘sqr’ in ‘int sqr(int c)’
b. Void value not ignored as it ought to be ‘b=sqr(a)’
c. Conflicting types for ‘sqr’ in ‘void sqr(int c)’
d. Both ‘a)’ and ‘b)’

Book 8.indb 143 6/7/2017 1:29:12 PM


144 Fundamentals of Computing and Programming

Answer: d. Always declaration will be of primary reference than definition. As the


declaration is of void type ‘b)’ comes.
13. What is the output of the code?
voidsqre(char c);
void main()
{ int a=8,b;
b=sqr(a);
printf(“%d”,b);}
intsqr(int c)
{ return c*c;}
a. 64
b. Garbage value
c. Error, confliction function name
d. None of the above
Answer: a. Here the declaration of function ‘sqre’ is separate and the function ‘sqr’
is saved separately. So doesn’t conflict. And it is not necessary that all declared
function must be defined.
14. What is the output of the code?
voidsqre(char c);
void main()
{ int a=8,b;
sqre(a);
printf(“%d”,b);}
intsqr(int c)
{ return c*c;}
a. 64 b. Garbage value
c. Error d. None of the above
Answer: c. “(.text+programaddress ): undefined reference to ‘sqre’ collect2: error: ld
returned 1 exit status.” All this is due to missing function definition of ‘sqre’.
15. What is the output of the code?
voidsqr
{ printf(“hai”);}
void main()
{ int a=8,b;
b=sqr;
printf(“%d”,b);}
a. 64 b. Garbage value
c. Error d. None of the above
Answer: c. Expected ‘=’, ‘,’ ‘;’, ‘asm’ or ‘__attribute’ before ‘{‘.

Book 8.indb 144 6/7/2017 1:29:12 PM


Functions: An In-depth Analysis and Understanding 145

16. What is the output of the code?


void main()
{ int a=8,b;
b=sq(a);
printf(“%d”,b);}
a. 64 b. Garbage value
c. Error d. None of the above
Answer: c. Undefined reference to ‘sq’. ld returned 1 exit status.
17. What is the output of the code?
intsq(int c);
void main()
{ int a=8,b;
b=sq(a);
printf(“%d”,b);}
a. 64 b. Garbage value
c. Error d. None of the above
Answer: c. Undefined reference to ‘sq’. ld returned 1 exit status.
18. What is the output of the code?
intsq(int c){ };
void main()
{ int a=8,b;
b=sq(a);
printf(“%d”,b);}
a. 0 b. Garbage value
c. Error d. None of the above
Answer: d. ‘8’ will be printed. This prints the value that is passed as argument as the
function block is empty.
19. What is will be the error thrown by the code?
intsq(int c);
void main()
{ int a=8,b;
b=sq( );
printf(“%d”,b);}
a. ld returned 1 exit status. Undefined reference to sq
b. Too few arguments for sq
c. Expected expression before ‘;’ in ‘sq(int c);’
d. None of the above
Answer: b. First the function call is matched with the function prototype only then the
body of the function is searched.

Book 8.indb 145 6/7/2017 1:29:12 PM


5 STRUCTURES AND UNIONS

LEARNING OBJECTIVES

After reading this chapter, the reader would be able to understand:


•• What is a structure in a C programming language?
•• Define structures and unions.
•• How are structures different from unions?
•• How are structures declared?
•• Explain the need for structure data type.
•• How to have structure within a structure?
•• Write simple programs using structures and unions.
•• What are preprocessor directives?
•• How to use type definitions with structures?
•• Infix operator and pointer to structures.

5.1 INTRODUCTION

In the programming language like C, structures are generally used to group together
various types of variables under the common name. For example, you could generate
a structure called “telephone”: which is made up of a string (that is used to hold the
person name which is a string) and an integer (that is used to hold the number of the
telephone).
Take a look at the example:
struct telephone
{
char *person_name;
inttel_number;
};

Fundamentals of Computing and Programming

Book 8.indb 146 6/7/2017 1:29:12 PM


Structures and Unions 147

Structure Union

Figure 5.1 Structure and union.


Image Courtesy: http://techdifferences.com

Figure 5.1 represents a structure and a union. Structure uses the keyword “struct”
while the union uses the keyword “union”. Though this is the primary difference between
them, we will also discuss in detail about the other similarities and differences as follows.
With the declaration of the structure as defined above, you have created a new type,
called telephone. In order to use the type telephone, you have to create a type telephone
variable. Take a look at the following example.

#include<stdio.h>
#include<stdlib.h>
struct telephone
{
char *person_name;
inttel_number;
};
int main()
{
struct telephone index;
return 0;
}
Program 5.1 A simple structure program

In order to access the members of the above structure telephone, we must use a dot
operator between the above structure name and the variable name used. Take a look at
the next example:

#include<stdio.h>
#include<stdlib.h>
struct telephone

Book 8.indb 147 6/7/2017 1:29:12 PM


148 Fundamentals of Computing and Programming

{
char *person_name;
inttel_number;
};
int main()
{
struct telephone catalog;
catalog.name = “James Bond”;
catalog.number = 54321;
printf(“Name of the person: %s\n”, catalog.name);
printf(“The Telephone number: %d\n”, catalog.number);
return 0;
}
Program 5.2 Usage of dot operator in structure

A union is also similar to a structure in which all members are present and the only
difference being they are stored at the same address instead of different address as in
the case of structures. The different members of a union can only be accessed one at a
time due to this limitation.
The union data type was originally developed in order to prevent memory
fragmentation. The union data type helps prevent fragmentation by creating a standard
size for certain types of data. The keyword “union” is used in this type of data structure.
As like with structures, the union members can also be accessed with the . and ->
operators. Take a look at the example:

#include<stdio.h>
typedef union defunion
{
double PI;
int A;
}DEFUNION;
int main()
{
DEFUNION digits;
digits.PI = 3.14;
digits.A = 50;
return 0;
}

Program 5.3 A simple Union example

A union is hence a special data type that is available in C programming language


and also allows to store different types of data in the same memory location without
creating a need for different memory locations.

Book 8.indb 148 6/7/2017 1:29:12 PM


Structures and Unions 149

Structure Unions

struct Emp union Emp


{ {
charX; //size 1 byte charX;
oat Y; //size 4 byte oat Y;
} e; } e;

Memory Sharing

X Y X &Y

e (structure variable) e (union variable)


5 bytes
4 bytes allocates storage
equal to largest one

Figure 5.2 Differences in structure and union.

A union can be defined with many members as needed, but only one member can
contain a value at any given time. Unions offer an effectual way of using the same
memory location for multiple purposes.

5.2 STRUCTURE DECLARATION

In C programming language, we can group some of the user defined or primary data
types together and form another solid way of storing complex information which is
called structure. The important points about structure are listed as follows:
•• Struct is the keyword that is used to declare structure.
•• Different members of the structure are bounded within opening and closing braces.
•• No space is reserved for the declaration of structure.
•• It is nothing but the “Map / Template / Shape” of the structure.
•• Very first time when the variable is created or the instance is created, the memory
is created as well.
There are different ways of declaring the structure variable as detailed below:
Method 1: Declaration can be made immediately after Structure Template
struct date
{
intday;
char month[10];
int year;
}today;
// ‘today’ is actually the name of the Structure variable

Method 2: Declare variables using struct Keyword after the structure as follows:
struct date
{
intday;

Book 8.indb 149 6/7/2017 1:29:13 PM


150 Fundamentals of Computing and Programming

char month[10];
int year;
};
struct date today;
// Here“today” refers to the name of variable and “date” refers to the name of structure.

Method 3: Declaring Multiple Structure Variables as follows:


struct Book
{
intpapers;
char name[25];
int year;
}book_a,book_b,book_c;

After closing the curly, we can declare multiple variables separated by comma
directly. These are the different ways of declaring.
Sizeof operator is generally used to find the size of any variable or data type in C
programming language. Though size of operator is an easy method of calculating the
size but following program will detail you the different method to calculate size of
structure without using sizeof operator.

#include<stdio.h>
#include<stdlib.h>
struct {
int number1,number2;
}z[2];

void main()
{
intstart,last;
start = &z[1].number1;
last = &z[0].number1;
printf(“\nSize of Structure : %d Bytes”,start-last);
}
Program 5.4 Size of the structure

Suppose, if there is a need to store the gender of the person, then instead of using
the complete byte we can manipulate single bit for this purpose. We can use Single bit
as a flag. The person’s gender can be stored and accessed as [M/F]. This can be achieved
by setting the flag bit 1 as “Male” and 0 as “Female”.
•• Bits are used to pack several data objects in to a single memory word.
•• Boolean values can be stored using flags ( T / F ).
•• Bit fields is the method to define a structure of packed information.

Book 8.indb 150 6/7/2017 1:29:13 PM


Structures and Unions 151

The structure below helps in realizing the same with an example as follows:

structdatabits
{
int a1 : 1;
int a2 : 1;
int a3 : 1;
int a4 : 4;
int a5 : 9;
}data1;

We have allocated specific number of bits for every member in the above example.
Memory can be better utilized through this approach. Dot operator is used to access
the individual structure member. Tag name followed by a dot along with the structure
member helps in accessing each data member of the structure.

5.3 NEED FOR STRUCTURE DATA TYPE

Several data items of the same kind can be represented or saved using arrays. In the
similar way, structure is another user defined data type available in C that allows to
combine data items of different kinds and hence different from arrays.
A record is represented through a structure. If you want to keep track of your
books in a library, you will have to track the attributes like:
•• Title of the book
•• Author name
•• Subject
•• Book ID used to identify.
The format of the struct statement is as follows:

struct [optional structure tag] {


member definition;
member definition;
...

member definition;
}

For the purpose of declaration, we use:

structLibrary_Books {
char book_title[50];

Book 8.indb 151 6/7/2017 1:29:13 PM


152 Fundamentals of Computing and Programming

char author_ name[50];


char subject_book[100];
intbook_i d;
} book;

Program 5.5 A better example

To access any structure member, the member access operator (.) is used. The member
access operator (dot operator) is coded as a period between the variable name of the
structure and the structure member that we wanted to access. The below given example
details the same:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
structTechBooks {
char book_title[40];
char book_author[40];
char book_subject[60];
intbook_id;
};
int main( ) {
structTechBooks Book1; /* Declare Book1 of type Book */
structTechBooks Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.book_title, “C plus plusProgramming”);
strcpy( Book1.book_author, “BjameStroustrup”);
strcpy( Book1.book_subject, “C plus plusProgramming
Tutorial”);
Book1.book_id = 7506519;
/* book 2 specification */
strcpy( Book2.book_title, “Mobile Billing”);
strcpy( Book2.book_author, “Jochen H Schiller”);
strcpy( Book2.book_subject, “Tutorial on Mobile Billing”);
Book2.book_id = 7506811;
/* print Book1 info */
printf( “Book 1 title : %s\n”, Book1.book_title);
printf( “Book 1 author : %s\n”, Book1.book_author);
printf( “Book 1 subject : %s\n”, Book1.book_subject);
printf( “Book 1 book_id : %d\n\n”, Book1.book_id);

Book 8.indb 152 6/7/2017 1:29:13 PM


Structures and Unions 153

/* print Book2 info */


printf( “Book 2 title : %s\n”, Book2.book_title);
printf( “Book 2 author : %s\n”, Book2.book_author);
printf( “Book 2 subject : %s\n”, Book2.book_subject);
printf( “Book 2 book_id : %d\n”, Book2.book_id);
return 0;
}

Program 5.6 Passing structure as an argument

The output of the above program would be:


Book 1 title :C ++ Programming
Book 1 author :BjameStroustrup
Book 1 subject :C plus plusProgramming Tutorial
Book 1 book_id :7506519

Book 2 title :Mobile Billing


Book 2 author :Jochen H Schiller
Book 2 subject :Tutorial on Mobile Billing
Book 2 book_id :7506811
You can pass a complete structure as an argument to the function in the same way
as we pass any other pointer or variable to the function. The below given example
details the same:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Books {
char book_title[40];
char book_author[40];
char book_subject[60];
intbook_id;
};

/* function declaration as below*/


voidprintBookDetails( struct Books book );

int main( ) {

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


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

Book 8.indb 153 6/7/2017 1:29:13 PM


154 Fundamentals of Computing and Programming

/* book 1 specification */
strcpy( Book1.book_title, “C plus plusProgramming”);
strcpy( Book1.book_author, “BjameStroustrup”);
strcpy( Book1.book_subject, “C plus plusProgramming Tutorial”);
Book1.book_id = 7506519;

/* book 2 specification */
strcpy( Book2.book_title, “Mobile Billing”);
strcpy( Book2.book_author, “Jochen H Schiller”);
strcpy( Book2.book_subject, “Tutorial on Mobile Billing”);
Book2.book_id = 7506811;

/* print Book1 info */


printBookDetails( Book1 );

/* Print Book2 info */


printBookDetails( Book2 );

return 0;

voidprintBookDetails( struct Books book ) {

printf( “Book title : %s\n”, book.book_title);


printf( “Book author : %s\n”, book.book_author);
printf( “Book subject : %s\n”, book.book_subject);
printf( “Book book_id : %d\n\n”, book.book_id);
}

The output of the above program would be:


Book 1 title :C ++ Programming
Book 1 author :BjameStroustrup
Book 1 subject :C ++ Programming Tutorial
Book 1 book_id :7506519

Book 2 title :Mobile Billing


Book 2 author :Jochen H Schiller
Book 2 subject :Tutorial on Mobile Billing
Book 2 book_id :7506811
Pointers can be defined to structures in the similar way as you define pointer to any
other variable in a C programming language −
struct Books *struct_pointer;

Book 8.indb 154 6/7/2017 1:29:13 PM


Structures and Unions 155

Now, you can store the structure variable address in the above defined pointer
variable. In order to find the structure variable address, place the ‘&’; operator before
the structure’s name as follows:
struct_pointer = &Book1;
To access the structure members using a pointer to that structure, the → operator is
used as follows:
struct_pointer->title;
We will rewrite the above example using structure pointers as follows:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Books {
char book_title[50];
char book_author[50];
char book_subject[100];
intbook_id;
};
/* function declaration */
voidprintBookDetails( struct Books *book );
int main( ) {
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.book_title, “C plus plusProgramming”);
strcpy( Book1.book_author, “BjameStroustrup”);
strcpy( Book1.book_subject, “C plus plusProgramming Tutorial”);
Book1.book_id = 7506519;
/* book 2 specification */
strcpy( Book2.book_title, “Mobile Billing”);
strcpy( Book2.book_author, “Jochen H Schiller”);
strcpy( Book2.book_subject, “Tutorial on Mobile Billing”);
Book2.book_id = 7506811;
/* print Book1 info by passing address of Book1 */
printBookDetails(&Book1 );

Book 8.indb 155 6/7/2017 1:29:13 PM


156 Fundamentals of Computing and Programming

/* print Book2 info by passing address of Book2 */


printBookDetails(&Book2 );
return 0;
}
voidprintBookDetails( struct Books *book ) {
printf( “Book title : %s\n”, book->book_title);
printf( “Book author : %s\n”, book->book_author);
printf( “Book subject : %s\n”, book->book_subject);
printf( “Book book_id : %d\n\n”, book->book_id);
}
Program 5.7 Structure pointers

The output of this program would be also:


Book 1 title :C ++ Programming
Book 1 author :BjameStroustrup
Book 1 subject :C plus plusProgramming Tutorial
Book 1 book_id :7506519

Book 2 title :Mobile Billing


Book 2 author :Jochen H Schiller
Book 2 subject :Tutorial on Mobile Billing
Book 2 book_id :7506811
This is how we define a structure and access its members for processing the data.
Pointers and functions are used in structures as well which are similar to other
programming types.

5.4 STRUCTURE WITHIN A STRUCTURE

A nested structure in C programming language is nothing but a structure that is present


within the structure. One structure along with its members can be declared inside the
other structure as we declare structure members inside a structure.
The structure variables that are used in this case can be a normal structure variable
or a pointer variable for data access. The following concepts can be learnt in this section.
•• Structure within structure in C using normal variable
•• Structure within structure in C using pointer variable.
This program given below explains on how to use structure within structure in C
using normal variable. “student_school_detail’ structure in this example is
declared inside “student_detail” structure. Both structure variables used in this
example are normal structure variables.

Book 8.indb 156 6/7/2017 1:29:13 PM


Structures and Unions 157

#include <stdio.h>
#include <string.h>
structstudent_school_detail
{
intschool_id;
charschool_name[50];
};
structstudent_detail
{
int id;
charstudent_name[25];
floatstudent_percentage;
// structure within structure
struct student_ school_detailclg_data;
}stu_data;
int main()
{
structstudent_detailstu_data = {1, “Sanju”, 80.6, 82256,”St.Peters school”};
printf(“ Student Id is: %d \n”, stu_data.id);
printf(“ Name is: %s \n”, stu_data.student_name);
printf(“ Percentage is: %f \n\n”, stu_data.student_percentage);

printf(“School Id is: %d \n”, stu_data.clg_data. school_id);


printf(“School Name is: %s \n”, stu_data.clg_data. school_name);
return 0;
}
Program 5.8 Structure within structure

The output of the above program would be hence:


StudentId is: 1
Name is: Sanju
Percentage is: 80.600000
School Id is: 82256
School Name is: St. Peters school
Structure can also be used within the structure in C programming language using
the pointer variable as detailed in the below given example. This program details on
how to use structure within structure in C programming using the pointer variable
instead of the normal variable. “student_school_detail’ structure is declared inside
“student_detail” structure in this example. One pointer structure variable and one
regular structure variable is used in this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
structstudent_school_detail

Book 8.indb 157 6/7/2017 1:29:13 PM


158 Fundamentals of Computing and Programming

{
intschool_id;
charschool_name[50];
};
structstudent_detail
{
int id;
char name[20];
float percentage;
// structure within structure
structstudent_school_detailclg_data;
}stu_data, *stu_data_ptr;
int main()
{
structstudent_detailstu_data = {1, “Sanju”, 80.6, 82256,”St.Peters school”};
stu_data_ptr = &stu_data;
printf(“ Student Id is: %d \n”, stu_data_ptr->id);
printf(“ Name is: %s \n”, stu_data_ptr->name);
printf(“ Percentage is: %f \n\n”, stu_data_ptr->percentage);
printf(“ School Id is: %d \n”, stu_data_ptr->clg_data.school_id);
printf(“ SchoolName is: %s \n”, stu_data_ptr->clg_data.school_name);
return 0;
}

Program 5.9 One more example

The output of the above program would be as follows:


StudentId is: 1
Name is: Sanju
Percentage is: 80.600000
School Id is: 82256
School Name is: St.Peters school
Hence, structure written inside another structure is generally called nesting of two
structures. The nested structures are allowed in C programming language without any
issues. We can also write one structure inside another structure as the member of another
structure.

5.5 UNION

In C programming language, we have discussed so far about structures. Syntactically


unions are similar to structure. The syntax of both structure and union are almost similar.
Let us discuss some important features of them as below:
•• Union and structure are almost similar
union student
{

Book 8.indb 158 6/7/2017 1:29:13 PM


Structures and Unions 159

intstud_roll;
charstud_name[4];
intstud_marks;
}stud1;

struct student
{
intstud_roll;
charstud_name[4];
intstud_marks;
}stud1;

•• Multiple members of different types are collected together under the same name
intstud_roll;
charstud_name[4];
intstud_marks;
•• All the members of the union occupy the same memory region as shown in
Figure 5.3.
roll

Byte 1 Byte 2 Byte 3 Byte 4

name

Marks

Figure 5.3 Memory area occupied by union.

•• Only one member of the union will be active at any point of time. Suppose if we
are accessing one of the union data members, then we cannot access another union
data member as each data member shares same memory. Hence, by means of
using union, we can save lot of space.
uniontag_name
{
union_member1name;
union_member2name;
union_member3name;
..
..
..
union_membername;
}instance;

Book 8.indb 159 6/7/2017 1:29:13 PM


160 Fundamentals of Computing and Programming

The other interesting facts about union and structure are:


•• Data members that compose a union, will all share the same storage area.

•• Each data member within a structure are assigned its own unique storage area.

•• Thus, unions are used to observe memory.

•• Unions are useful for application containing multiple members, where values are
not required to be assigned to all the members at any given time.
Pointer which stores address of union is called pointer to union. This is given as
follows:
union teams a1; //Declaring union variable in this statement
union teams *ptr; //Declaring union pointer variable in this line
ptr = &a1; //Assigning address to union pointer in this line
One sample program using the above concept is given below:

#include<stdio.h>
#include <stdlib.h>
union teams {
char *name;
int members;
char captain[25];
};
int main()
{
union teams a1,*ptr = &a1;
a1.name = “India”;
printf(“\nTeam : %s”,(*ptr).name);
printf(“\nTeam : %s”,ptr->name);
return 0;
}
Program 5.10 Pointer and Union

The output of the above program would be:


Team = India
Team = India
While accessing the union, we can have access only a single data member at any
given time. We can access single union member using following two operators:
•• Using the DOT Operator

•• Using the ARROW Operator

Book 8.indb 160 6/7/2017 1:29:13 PM


Structures and Unions 161

Table 5.1 Differences in normal and pointer variable method of accessing


Using normal variable Using pointer variable
Syntax: Syntax:
union tag_name union tag_name
{ {
data type variable_name1; data type variable_name1;
data type variable_name2; data type variable_name2;
data type variable_name3; data type variable_name3;
}; };
Example: Example:
union student_tag union student_tag
{ {
int stud_mark; int stud_mark;
char stud_name[10]; char stud_name[10];
float stud_average; float stud_average;
}; };
Declaring union using pointer variable:
Declaring union using normal variable:
union student *progress_report,
union student progress_report;
rep;
Initializing union using normal variable: Initializing union using pointer variable:
union student progress_report = union student rep = {90, “Vani”, 78.6};
{90, “Vani”, 78.6}; report = &rep;
Accessing union members using normal Accessing union members using pointer
variable: variable:
progress_report.mark; progress_report -> mark;
progress_report.name; progress_report -> name;
progress_report.average; progress_report -> average;

Table 5.1 helps to understand on how to form a C union, union declaration, initializing
and accessing the union members.

5.6 PROGRAMS USING STRUCTURES AND UNIONS

In this section, we will explain writing programs using structures and unions. We will
use a union when your “item” can be one of the many different items in the list but
use only one at a time and we use a structure when your “item” should be a group of
other items.

5.6.1 Program to Store Information of Students Using Structure


#include <stdio.h>
#include <stdlib.h>
struct student
{

Book 8.indb 161 6/7/2017 1:29:13 PM


162 Fundamentals of Computing and Programming

charstud_name[60];
intstud_roll;
floatstud_marks;
} stud[10];

int main()
{
int i;
printf(“Enter student information:\n”);
// storing the student information
for(i=0; i<10; ++i)
{
stud[i].stud_roll = i+1;
printf(“\nForstudent roll number%d,\n”,stud[i].roll);
printf(“Enter the student name: “);
scanf(“%s”,stud[i].stud_name);
printf(“Enter the student marks: “);
scanf(“%f”,&stud[i].stud_marks);
printf(“\n”);
}
printf(“Displaying the student Information:\n\n”);
// displaying student information
for(i=0; i<10; ++i)
{
printf(“\nRoll number of the student is: %d\n”,i+1);
printf(“Name of the student: “);
puts(stud[i].stud_name);
printf(“Student Marks: %.1f”,stud[i].stud_marks);
printf(“\n”);
}
return 0;
}
Program 5.11 Program to store student information

The output of the above program is:


Enter student information:
For student roll number 1,
Enter the student name: Sam
Enter the student marks: 79
For student roll number2,
Enter name: Mary
Enter marks: 54

Book 8.indb 162 6/7/2017 1:29:13 PM


Structures and Unions 163

.
.
.
Displaying Information:

Roll number of the student is: 1


Name of the student: Sam
Student Marks: 79
.
.
.

5.6.2 Program to Sort Array of Structure in C Programming


#include <stdio.h>
#include <stdlib.h>
#define M 50
struct state {
charcitizen_name[50];
long int total_population;
floattotal_literacyRate;
floattotal_ income;
} st[M]; /* array of structure */
int main() {
int i, b, ml, mi, maximumLiteracyRate, maximumIncome;
float rate;
ml = mi = -1;
maximumLiteracyRate = maximumIncome = 0;
printf(“Enter the number of states:”);
scanf(“%d”, &b);
for (i = 0; i < b; i++) {
printf(“\nEnterthe state %d details :”, i);
printf(“\nEnter the state name : “);
scanf(“%s”, &st[i].citizen_name);
printf(“\nEnterthe total population : “);
scanf(“%ld”, &st[i].total_population);
printf(“\nEnterthe total literary rate : “);
scanf(“%f”, &rate);
st[i].total_literacyRate = rate;
printf(“\nEnterthe total income : “);
scanf(“%f”, &st[i].total_income);

Book 8.indb 163 6/7/2017 1:29:13 PM


164 Fundamentals of Computing and Programming

}
for (i = 0; i < b; i++) {
if (st[i].literacyRate>= maximumLiteracyRate) {
maximumLiteracyRate = st[i].total_literacyRate;
ml++;
}
if (st[i].income >maximumIncome) {
maximumIncome = st[i].total_income;
mi++;
}
}
printf(“\nThe State with highest literary rate is :%s”, st[ml].total_name);
printf(“\nThe State with highest income is :%s”, st[mi].total_name);
return (0);
}
Program 5.12 Sorting array of structure

The output of the above program is:


Enter the number of states:3

Enter the state 0 details:


Enter the state name: Odisha
Enter the total population: 5000
Enter the total literary rate: 70
Enter the total income: 9000

Enter the state 1 details:


Enter the state name: Gujarat
Enter the total population: 2000
Enter the total literary rate: 82
Enter the total income: 7000

Enter the state 2 details:


Enter the state name: Tamilnadu
Enter the total population: 9000

Enter the total literary rate: 88


Enter the total income: 6000

The state with highest literacy rate is: Tamilnadu


The state with highest income is: Odisha

Book 8.indb 164 6/7/2017 1:29:13 PM


Structures and Unions 165

5.6.3 Program to Use Structure Within Union and Display the


Contents of Structure Elements
#include <stdio.h>
#include <stdlib.h>
#include<conio.h>
void main() {
struct student {
charstud_name[30];
charstud_sex;
intstud_rollno;
floatstud_percentage;
};
union details {
struct student st;
};
union details set;

printf(“Enter the details of the student:”);


printf(“\nEnterthe name of the student: “);
scanf(“%s”, set.st.stud_name);
printf(“\nEnterthe student roll no : “);
scanf(“%d”, &set.st.stud_rollno);

flushall();
printf(“\nEnterthe student sex : “);
scanf(“%c”, &set.st.stud_sex);
printf(“\nEnter the student percentage :”);
scanf(“%f”, &set.st.stud_percentage);

printf(“\nThe student details are : \n”);


printf(“\Student name : %s”, set.st.stud_name);
printf(“\nStudentRollno : %d”, set.st.stud_rollno);
printf(“\nStudentSex : %c”, set.st.stud_sex);
printf(“\nStudentPercentage : %f”, set.st.stud_percentage);

getch();
}
Program 5.13 Usage of structure within union

The output of the above program would be:


Enter the details of the student:
Enter the name of the student: David
Enter the student roll no: 21
Enter the student sex: M

Book 8.indb 165 6/7/2017 1:29:13 PM


166 Fundamentals of Computing and Programming

Enter the student percentage: 69


The student details are:
Student Name: David
Student Rollno: 21
Student Sex: M
Student Percentage: 69.000000

5.6.4 Program to Use Unions for Maintaining the Student Record


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
unionstudent_tag
{
charstud_name[30];
charstud_subject[30];
floatstud_percentage;
};
int main()
{
unionstudent_tag record1;
unionstudent_tag record2;

// assigning values to record1 union variable


strcpy(record1.stud_name, “Teju”);
strcpy(record1.stud_subject, “Science”);
record1.stud_percentage = 94.50;

printf(“\nUnion record1 values example\n”);


printf(“ Name : %s \n”, record1.stud_name);
printf(“ Subject : %s \n”, record1.stud_subject);
printf(“ Percentage : %f \n\n”, record1.stud_percentage);
// assigning values to record2 union variable
printf(“\nUnion record2 values example\n”);
strcpy(record2.stud_name, “Rani”);
printf(“ Name : %s \n”, record2.stud_name);

strcpy(record2.stud_subject, “Chemistry”);
printf(“ Subject : %s \n”, record2.stud_subject);

record2.stud_percentage = 87.50;
printf(“ Percentage : %f \n”, record2.stud_percentage);
return 0;
}
Program 5.14 Student record with Union

Book 8.indb 166 6/7/2017 1:29:13 PM


Structures and Unions 167

The output of the above program would be:

Union record1 values example


Name :
Subject :
Percentage : 94.500000;

Union record2 values example


Name :Rani
Subject :Chemistry
Percentage : 87.500000

5.6.5 Program to Use Structures for Maintaining the Employee Record


#include <stdio.h>
struct Employee
{
charemp_name[20];
intemp_ssn;
floatemp_salary;
struct date
{
int date;
int month;
int year;
}doj;
}emp = {“Vijay”,3000,2000.50,{23,7,1989}};

int main(int argc, char *argv[])


{
printf(“\nEmployee Name : %s”,emp.emp_name);
printf(“\nEmployee SSN : %d”,emp.emp_ssn);
printf(“\nEmployee Salary : %f”,emp.emp_salary);
printf(“\nEmployee DOJ : %d/%d/%d”, \
emp.doj.date,emp.doj.month,emp.doj.year);
return 0;
}
Program 5.15 Employee record with structure

The output of the above program would be:


Employee Name : Vijay
Employee SSN : 3000
Employee salary : 2000.500000
Employee DOJ : 23/7/1989

Book 8.indb 167 6/7/2017 1:29:13 PM


168 Fundamentals of Computing and Programming

5.7 PREPROCESSOR DIRECTIVES

Source code is processed by a program called preprocessor before a C program is


compiled in a compiler. This process is called preprocessing. Commands used in
preprocessor are known as preprocessor directives and they always begin with “#”
symbol. Below is the list of preprocessor directives that C programming language offers
for coding. Let’s take a look at the following example:
#include <stdio.h>
#define DEF_MACRO1
#define DEF_MACRO2
int main(void)
{
#ifdefDEF_MACRO1 //This will test whether DEF_MACRO1 is defined.
printf(“\nDEF_MACRO1 Defined\n”);
#endif
#ifdefDEF_MACRO2 // This will test whether DEF_MACRO2 is defined.
printf(“\nDEF_MACRO2 Defined\n”);
#endif
return 0;
}
Program 5.16 Preprocessor directives usage

The above program defines two macros DEF_MACRO1 and DEF_MACRO_2. The
macros are without values and the output would be both macros presence.

Table 5.2 Preprocessor directives


Preprocessor Syntax/Description
Syntax: #define
Macro This macro called #define helps define constant value
and can be any of the basic data types.
Syntax: #include <file_name>
The source code of the file “file_name” is included in
Header file inclusion
the main program at the specified place using this
directive.
Syntax: #ifdef, #endif, #if, #else, #ifndef
Set of commands are included or excluded in source
Conditional compilation
program before compilation with respect to the
condition.
Syntax: #undef, #pragma
#undef is used to undefine a defined macro variable.
Other directives used
#Pragma is used to call a function before and after
main function in a C program.

Book 8.indb 168 6/7/2017 1:29:13 PM


Structures and Unions 169

Below given program is a sample for usage of preprocessor directive.


#include <stdio.h>
#define length 90
#define digit 3.14
#define letter ‘B’
#define letter_sequence “CBA”
#define backslash_character ‘\?’
void main()
{
printf(“value of length : %d \n”, length );
printf(“value of digit : %f \n”, digit );
printf(“value of letter : %c \n”, letter );
printf(“value of letter_sequence : %s \n”, letter_sequence);
printf(“value
of backslash_character : %c \n”, backslash_character);
}
Program 5.17 Preprocessor directives usage - an example

The output of the above program would be:


value of length : 90
value of digit : 3.140000
value of letter : B
value of letter_sequence : CBA
value of backslash_character : ?
Pre-processor directives are represented in Figure 5.4.

Preprocessor directives

File inclusion Macro substitution Miscellaneous


directive directive conditional directives
directives
#include #define #pragma
#if #error
#elif #line
#else
#endif
#ifdef
#ifndef
Operators in preprocessor #undef

#
##

Figure 5.4 Preprocessor directives.

Book 8.indb 169 6/7/2017 1:29:14 PM


170 Fundamentals of Computing and Programming

There are two types of macros. They are:


•• Object-like macros
•• Function-like macros
The object-like macro is an identifier that is normally replaced by value. It is widely
used in order to represent numeric constants. For example:
#define PI 3.1415 // Defines the value of PI and used across places in the code.
One example of object-like macro is as follows:
#include <stdio.h>
#define PI 3.1415
main()
{
printf(“%f”,PI);
}
The output of the above program would be: 3.14000
The function like macro on the other hand will look like a function call.
#define MIN(c,d) ((c)<(d)?(c):(d))
Here MIN represents the macro name. Example for function like macro would be as
follows:
#include <stdio.h>
#define MIN(c,d) ((c)<(d)?(c):(d))
void main() {
printf(“Minimum between 20 and 30 is: %d\n”, MIN(20,30));
}
The output of the above program would be:
Minimum between 20 and 30 is: 20

KEY POINTS TO REMEMBER

•• Structured programming is a software design model aimed at refining the clarity,


development time and quality of a computer program by making wide use of
subroutines, block structures, for and while loops.
•• Structures, unions and bit fields are some significant aspects of a programming
language like C.
•• A struct in the C programming language (and many other similar languages) is
a composite data type declaration.
•• A structure field can sometimes contain another structure, or even a set of structures
called nested structures.
•• Structures can also be declared inside the main which is not a problem. More the
number of objects would consume more memory and needs to be taken care.

Book 8.indb 170 6/7/2017 1:29:14 PM


Structures and Unions 171

•• ‘typedef’ is a keyword that is used in C language in order to assign alternative


names to existing types.
•• Structures are applied where an “object” is composed of other objects, like a point
object containing two integers, namely, the ‘a’ and ‘b’ coordinates.
•• An array or an array data structure is a type of data structure that consists of a
set of elements (values or variables), and each identified by at least one key or
array index.
•• Unions are normally used in situation where an object can be one of the many
items but only one at a time can be used, such as a type-less storage system.
•• Sometimes when the structure member variables represent some flags that store
either 0 or 1, bit fields are used to conserve memory.
•• Bit fields allow for efficient packaging of data in the memory based on the need.
•• While structures are widely used in the programming for their need, unions and
bit fields are moderately less used but that does not reduce their importance in
the programming.
•• Embedded systems programming mostly requires manipulation at bit level and
bit fields are quite useful there.
•• Any array behaves like a built-in data types and holds data of same type while
structures on the other hand are of different data types.
•• A macro is generally an abbreviated name that is provided to a piece of software
code or sometimes a value.
•• The #if preprocessor directive found in the C programming language evaluates
the expression or condition. If the condition is found to be true, it executes the
code.
•• The #else preprocessor directive assesses the condition or expression if condition
of #if is false. It is generally used with #if, #ifdef, #elifand #ifndef directives.
•• The #ifdef preprocessor directive will check if the macro is defined by #define. If
yes, it executes the code.
•• The #error preprocessor directive indicates the presence of error in the program.
The compiler during compilation will give the fatal error if #error directive is
found and it also skips further compilation process.
•• A macro can be defined through compilation statement as well from the command
line.
•• There is no concept of “struct” in OOP. The definition of structures depends on
the programming language used. For instance, in C++ classes and structs are the
same, but struct members are public while the class members are private by defaults
and they maintain compatibility with C structs.

Book 8.indb 171 6/7/2017 1:29:14 PM


172 Fundamentals of Computing and Programming

EXERCISE

1.
What is the difference between a structure and union? Explain with examples.
2.
How is a structure declared?
3.
What is the need for structure data types?
4.
How do we find the size of the structure?
5.
Is it possible to have a structure inside another structure? Explain with example.
6.
Explain the ‘union’ concept with examples.
7.
What are preprocessor directives?
8.
What is meant by array of structures?
9.
Is it possible to write functions inside a structure?
10.
Differentiate between arrays and structures.
11.
What is a typedef and how is it useful?
12.
Write a small program to find the maximum of two numbers using macros.
13.
Write a C program to hold the village people names and their electricity bill status
using structures.
14. Write a C program to print the thermometer reading in centigrade or Fahrenheit
using unions.
15. Explain the difference between a structure and a class in C++ program.
16. Brief the usage of bit fields.
17. What are the different elements of the bit field?
18. What is meant by array of arrays?
19. Give some applications where unions can be used.
20. Explain the memory concept with reference to structures and unions.
21. Which of the following structure declaration will throw an error?
A.structtemp{}s;
main(){}
B. structtemp{};
struct temp s;
main(){}
C. struct temp s;
struct temp{};
main(){}
D. None of the above mentioned.
22. How do you access union members?
23. What is the output of this C code?
void main()
{
struct student
{

Book 8.indb 172 6/7/2017 1:29:14 PM


Structures and Unions 173

int no;
char name[20];
};
struct student s;
s.no = 8;
printf(“%d”, s.no);
}
24. Calculate the number of bytes in memory taken by the below given structure:
struct test
{
int k;
char c;
};
25. What is a type-less storage system?
26. What is the use of undef?
27. Explain the preprocessor directive #error with example.
28. Differentiate between typedef and #define
29. Which operator connects the structure name and its member name?
30. Can another structure be a structure member? Explain with example.

QUESTIONS TO TEST YOUR SKILLS

1. What is the output of the code?


struct s
{int a;
}b;
void main ( )
{ b.a = 4;
printf(“%d ”,b.a); }
a. 4 b. 0
c. Error d. Unpredictable behaviour
Answer: a. Structure, referred as ‘struct’, is a collection of variables of different data
types, which may be common and used repeatedly for various instances. Here
‘b’ is an instance. Here the ‘.’ in ‘b.a’ is the member operator used to access
the corresponding variable.
2. What is the output of the code?
struct s
{int a;
}b,c;
void main ( )
{ b.a = 4;
c.a=4;
printf(“%d %d”,b.a,c.a); }

Book 8.indb 173 6/7/2017 1:29:14 PM


174 Fundamentals of Computing and Programming

a. 4 4 b. 0 0
c. Error d. Unpredictable behaviour
Answer: a. Here ‘b’ and ‘c’ are multiple instances for the struct.
3. What is the output of the code?
struct s
{int a; };
void main ( )
{ struct s b,c;
b.a = 4;
c.a=4;
printf(“%d %d”,b.a,c.a); }
a. 4 4 b. 0 0
c. Error d. Unpredictable behaviour
Answer: a. This is another method of creating instances to a structure.
4. What is the output of the code?
struct s
{int a; };
void main ( )
{ struct s b;
printf(“%d ”,b.a); }
a. 0 b. Error
c. Unpredictable behaviour d. Compiler dependent
Answer: c. Struct variables are not initialised with 0. Unless they are accessed they rest
in some random memory with some garbage value.
5. What is the output of the code?
struct s
{int a; };
void main ( )
{ s b;
b.a = 4;
printf(“%d ”,b.a); }
a. 4 b. 0
c. Error d. Unpredictable behaviour
Answer: c. Struct is a user defined data type. So declaring an instance without struct
keyword makes it unknown to the compiler.
6. How many errors will be thrown by the code?
struct s
{int a;};
void main ( )
{ s b;
b.a = 4;
printf(“%d ”,b.a); }

Book 8.indb 174 6/7/2017 1:29:14 PM


Structures and Unions 175

a. 1 b. 2
c. 3 d. Compiler dependent
Answer: c. The declaration of ‘b’ will be throwing “unknown type name ‘s’ ”. So the
instance is not created. Hence, all the statements where the instance is used
throws error.
7. What will be the error thrown by the code?
struct s
{ int a;}
void main ( )
{ struct s b;
b.a = 4;
printf(“%d ”,b.a); }
a. Expected expression or ‘;’ before ‘void main()’
b. Expected ‘;’, identifier or ‘(‘ before ‘void main()’
c. No error
d. None of the above
Answer: b. The ending semicolon is mandatory for ‘struct’ as it marks the end of the
block.
8. What will be the error thrown by the code?
void main ( )
{ struct s b;
b.a = 4;
printf(“%d ”,b.a); }
a. Invalid type ‘struct s’
b. ‘struct s’ not defined
c. Invalid type for ‘b’
d. None of the above
Answer: d. Storage size of ‘b’ isn’t known. When the ‘struct’ is not defined in the
program. The compiler treats that the ‘struct’ is defined in some scope that is
not accessible by the current scope instance.
9. What will be the error thrown by the code?
struct s
{int a;} ;
void main ( )
{ struct s b;
a = 4;
printf(“%d ”,b.a); }
a. ‘a’ undeclared
b. Invalid initialisation of structure variable
c. No error
d. None of the above

Book 8.indb 175 6/7/2017 1:29:14 PM


176 Fundamentals of Computing and Programming

Answer: a. The compiler knows ‘a’ only as a structure variable. So can never be used
separately.
10. What will be the error thrown by the code?
struct s
{int a=4;} ;
void main ( )
{ struct s b;
printf(“%d ”,b.a); }
a. Invalid usage of structure variable
b. Assigning value to structure variable, with no instance created
c. No error
d. None of the above
Answer: d. Expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘_ _attributre_ _’ before ‘;’ in ‘int a=4’. As said before
same Struct variable will hold different values for different instances. So even
common values cannot be initialized directly.
11. What is the output of the code?
struct s
{int a; };
void main ( )
{ struct s b;
b.a = 4;
printf(“%lu ”,sizeof(b)); }
a. 4 b. 8
c. Error d. Compiler dependent
Answer: a. The struct has only one variable of size four. So the size of the structure
instance is the same, 4 bytes.
12. What is the output of the code?
struct s
{int a;
char c; };
void main ( )
{ struct s b;
b.a = 4;
b.c= ‘d’;
printf(“%lu ”,sizeof(b)); }
a. 4 b. 8
c. 5 d. Compiler dependent
Answer: d. In GCC this gives 8. In other compilers it may give 5. This depends also on
the architecture of the compiler. Here in GCC it gets padded automatically.
For any variable the size of the largest variable is allocated, even if it needs
lesser memory. The adding of additional memory to make up that length is
called padding. It basically tries to allocate a register as a whole. Which is 8
bytes.

Book 8.indb 176 6/7/2017 1:29:14 PM


Structures and Unions 177

13. What is the output of the code?


struct s
{int a;
char c[3]; };
void main ( )
{ struct s b;
b.a = 4;
strcpy(b.c,“hai”);
printf(“%lu ”,sizeof(b)); }
a. 4 b. 8
c. 5 d. None of the above
Answer: b. This is based on the padding explained above.
14. What is the output of the code?
struct s
{int a;
char c[5]; };
void main ( )
{ struct s b;
b.a = 4;
strcpy(b.c,“hai”);
printf(“%lu ”,sizeof(b)); }
a. 4 b. 12
c. 5 d. None of the above
Answer: b.
15. What is the output of the code?
struct s
{int a;
double c; };
void main ( )
{ struct s b;
b.a = 4;
b.c=32.332323;
printf(“%lu ”,sizeof(b)); }
a. 12 b. 8
c. 16 d. None of the above
Answer: c. One register for double value and another register for int.
16. What is the output of the code?
union s
{int a;
}b;
void main ( )
{ b.a = 4;
printf(“%d ”,b.a); }

Book 8.indb 177 6/7/2017 1:29:14 PM


178 Fundamentals of Computing and Programming

a. 4 b. 0
c. Error d. Unpredictable behaviour
Answer: a. ‘union’ is also a cluster of variables of different data type, similar to ‘struct’.
But technically there are some changes only the usage is similar.
17. What is the output of the code?
union s
{int a; };
void main ( )
{ union s b;
b.a = 4;
printf(“%d ”,b.a); }
a. 4 b. 0
c. Error d. Unpredictable behaviour
Answer: a. The alternative way for declaring the instance.
18. What is the output of the code?
union s
{ float a; };
void main ( )
{ union s b;
b.a = 45.454;
printf(“%d ”,b.a); }
a. 45.454000 b. Error
c. Unpredictable behaviour d. None of the above
Answer: d. It gives 45.453999. The storage architecture if union instance makes the
change.
19. What will be the error thrown by the code?
union s
{int a; };
void main ( )
{ s b;
b.a = 4;
printf(“%d ”,b.a); }
a. Request for member ‘a’ of something that is not a structure or union
b. Unknown type name ‘s’
c. Both ‘a)’ and ‘b)’
d. Compiler dependent
Answer: c. The declaration of ‘b’ will be throwing “unknown type name ‘s’ ”. As the
declaration has an error, accessing that also throws error. So totally 3 errors,
‘a)’ once and ‘b)’ twice.
20. What is the output of the code?

Book 8.indb 178 6/7/2017 1:29:14 PM


Structures and Unions 179

union s
{int a; };
union e
{ float a; };
void main ( )
{ union s b;
b.a = 4.35;
union e v=b;
printf(“%d ”,v.a); }
a. 4 b. 0
c. Error d. Unpredictable behaviour
Answer: c. Invalid initializer ‘union e v=b’.
21. What will be the error thrown by the code?
union s
{int a; };
union e
{ float a; };
void main ( )
{ union s b;
b.a = 4.35;
union e v;
v=b;
printf(“%d ”,v.a); }
a. Invalid initialization ‘v=b’
b. Invalid assignment ‘v=b’
c. No error
d. None of the above
Answer: d. Incompatible types when assigning to type ‘union e’.
22. What is the output of the code?
union s
{int a; };
union e
{ float a; };
void main ( )
{ union s b;
b.a = 4.35;
union e v;
v.a=9;
printf(“%lu %lu ”,sizeof(v),sizeof(b)); }
a. 4 4 b. Error
c. Unpredictable behaviour d. Compiler dependent
Answer: d. Even the size of ‘int’ and ‘float’ are dependent on the compiler and processor
architecture. For a normal GCC compiler in a 64-bit processor ‘a)’ is the answer.

Book 8.indb 179 6/7/2017 1:29:14 PM


180 Fundamentals of Computing and Programming

23. What is the output of the code?


union s
{int a; };
union e
{ float a; };
void main ( )
{ union s b;
b.a = 4.35;
union e v;
printf(“%lu %lu ”,sizeof(v),sizeof(b)); }
a. 4 4 b. 4 0
c. Error d. None of the above
Answer: a. The value of the ‘union’ member may or may not be initialised. But once it
is declared, the space is allocated. Thus, size of ‘v’ is not 0.
24. What is the output of the code?
union s
{ int a;
float e;};
void main ( )
{ union s b;
b.a = 4;
printf(“%lu”,sizeof(b)); }
a. 4 b. 8
c. Error d. None of the above
Answer: a. The size of the union instance is the size of the largest member.
25. What is the output of the code?
union s
{ int a;
float e;};
void main ( )
{ union s b;
b.a = 4;
b.e=9.86;
printf(“%d”, b.a); }
a. 4 b. 0
c. Error d. None of the above
Answer: b. The ‘union’ instance has a special architecture. It can hold values until the
size of maximum member. Once the capacity is reached and still values are
given to it, it will just overwrite the old value with the new one.
26. What is the output of the code?
union s
{ int a;

Book 8.indb 180 6/7/2017 1:29:14 PM


Structures and Unions 181

float e;};
void main ( )
{ union s b;
b.a = 4;
b.e=9.86;
printf(“%f”, b.e); }
a. 9.86 b. 0.00
c. Error d. None of the above
Answer: d. Its ‘9.86000000’. But this works normally as the member ‘e’ has just over
written ‘a’.
27. What is the output of the code?
union s
{ char a1;
char a2;
char a3;
float e;};
void main ( )
{ union s b;
b.a1 = ‘a’;
b.a2 = ‘b’;
b.a3 = ‘c’;
printf(“%c %c %c”, b.a1,b.a2,b.a3); }
a. a b c b. Unpredictable behaviour
c. Error d. None of the above
Answer: d. Its ‘c cc’. The instance is of size 4. So it can hold 1 float value or 1 character
values. Also all the 4 character values will be made internally mapping to the
same address.
28. What is the output of the code?
union s
{ char a1;
char a2;
char a3;
float e;};
void main ( )
{ union s b;
b.a1 = ‘a’;
b.a3 = ‘b’;
b.a2 = ‘c’;
printf(“%c %c %c”, b.a1,b.a2,b.a3); }
a. b bb b. Unpredictable behaviour
c. Error d. None of the above
Answer: d. Its again ‘c cc’. The values assigned last will be retained. No matter which
member is initialised.

Book 8.indb 181 6/7/2017 1:29:14 PM


182 Fundamentals of Computing and Programming

29. What is the output of the code?


union s
{ char a1;
char a2;
char a3;
float e;};
void main ( )
{ union s b;
b.a1 = ‘a’;
printf(“%c %c %c”, b.a1,b.a2,b.a3); }
a. a aa b. Unpredictable behaviour
c. Error d. None of the above
Answer: a. All ‘char’ members will be associated to the same character. So even if the
member is not initialised, it will get the common value.
30. What is the output of the code?
union s
{ char a1;
char a2;
char a3;
float e;};
void main ( )
{ union s b;
b.e=85.56;
b.a1 = ‘a’;
printf(“%c %c %c”, b.a1,b.a2,b.a3); }
a. a aa b. Unpredictable behaviour
c. Error d. None of the above
Answer: a. Once the first character is given in, all ‘char’ members will map to the same
character. No partial holding the old value.

Book 8.indb 182 6/7/2017 1:29:14 PM


APPENDIX: C IN TWO MINUTES

Output Statement printf(“specifier”,value);


Input Statement scanf(“specifier”,&variable);
Declaration Type Variable Name;
Specifiers and Data types
Format specifier Supported data types
char
%c
unsigned char
short
unsigned short
%d
int
long
float
%e or %E
double
%f float
float
%g or %G
double
%hi short
%hu unsigned short
short
unsigned short
%i
int
long
%l or %ld or %li long
%lf double
%Lf long double
unsigned int
%lu
unsigned long
%lli, %lld long long
%llu unsigned long long

Fundamentals of Computing and Programming

Book 8.indb 183 6/7/2017 1:29:14 PM


184 Fundamentals of Computing and Programming

Format specifier Supported data types


short
unsigned short
%o int
unsigned int
long
%p void *
%s char *
unsigned int
%u
unsigned long
short
unsigned short
%x or %X int
unsigned int
long
Not for any variable, but will not
%n
throw errors
Not for any variable, but will not
%%
throw errors

Data types and their size


Data type Range Size
char -127 to +127 1 byte
unsigned char 0 to 255 1 byte
short -32,767 to 32,767 2 byte
unsigned short 0 to 65,535 2 byte
int -2,147,483,847 to +2,147,483,847 4 bytes
unsigned int 0 to 4,294,967,295 4 bytes
long -2,147,483,847 to +2,147,483,847 4 bytes
unsigned long 0 to 4,294,967,295 4 bytes
-9,223,372,036,854,775,807 to
long long 8 bytes
+9,223,372,036,854,775,807
unsigned long long 0 to 18,446,744,073,709,551,615 8 bytes
float 1.2E-38 to 3.4E+38 4 bytes
double 2.3E-308 to 1.7E+308 8 bytes
long double 3.4E-4932 to 1.1E+4932 10 bytes

Book 8.indb 184 6/7/2017 1:29:14 PM


Appendix: C In Two Minutes 185

Operators and precedence


Operator Description Associativity
() Parentheses (function call) (see Note 1) left-to-right
[] Brackets (array subscript)
. Member selection via object name
-> Member selection via pointer
++ -- Postfix increment/decrement (see Note 2)
++ -- Prefix increment/decrement right-to-left
+- Unary plus/minus
!~ Logical negation/bitwise complement
(type) Cast (convert value to temporary value of type)
* Dereference
& Address (of operand)
sizeof Determine size in bytes on this implementation
* / % Multiplication/division/modulus left-to-right
+ - Addition/subtraction left-to-right
<< >> Bitwise shift left, Bitwise shift right left-to-right
< <= Relational less than/less than or equal to left-to-right
> >= Relational greater than/greater than or equal to
== != Relational is equal to/is not equal to left-to-right
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
= Assignment right-to-left
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment
, Comma (separate expressions) left-to-right

Conditional Statements:
Statement Syntax
Goto Goto label;
If If(condition) {block}
If(condition) {block}
If…else
else {block}

Book 8.indb 185 6/7/2017 1:29:14 PM


186 Fundamentals of Computing and Programming

Statement Syntax
If(condition) {block}
else If(condition) {block}
If…else Ladder
else If……
else {block}
(condition)?
Ternary
{true_vlock} : {false_block};
Switch (variable)
{ case 1: {block}
break;
Switch case 2 : {block}
break;
//till case n
defauilt: {block} }
break; to end a loop or exit a local
Break
block
continue; //to continue the next
Continue
iteration of a loop

Looping statement
Statement Syntax
label: {block}
Unconditional loop
goto label;
For (initialize control variable ;condition; increment control
For variable )
{block}
While while(condition) {block}
do
Do…while {block}
while(condition)

Function declaration:
[Return Type] function_name [(list of parameters])
{block}
//content enclosed by [ ] are optional and can be skipped
Array:
Type variable[size]
Type variable[ ] = {elements}

Book 8.indb 186 6/7/2017 1:29:14 PM


Appendix: C In Two Minutes 187

DMA:
Statement Syntax
malloc() Pointer_Variable = malloc(size)
calloc() Pointer_Variable = calloc(no of blocks, size)
free free(pointer_variable)
realloc Pointer_Variable = Realloc(Pointer_Variable, size)

User defined Data Types


Type Syntax
Type def typedef base_type new_name;
Enum enum identifier {value1,value2, value 3,…}

Structure and Union


Struct name Union name
{ variables}; {variables};

Book 8.indb 187 6/7/2017 1:29:14 PM


INDEX

A Computer system, basic components of 3


Algorithms 17 Computer, characteristics of 3
AND truth table 47 basic information 4
Arithmetic operators 45 generations 5
Array 88, 101 organization 10
characteristics of 91 types of 8
declaration of 91 Conditional operator 62
representation of 89 Constants 36
with pointers 137 D
Assignment operators 46 Data types 41
B Decimal number system 14
Binary to decimal conversion 15 Decimal to binary conversion 15
Binary to hexadecimal conversion 16 Decimal to other base system 14
Bitwise AND (&) 49 Decision making 67
Bitwise EXOR (|) 49 Declaration 122
Bitwise operators 48 Decrement operator (--) 62
Bitwise OR (|) 49 Delimiters 40
Branching 67 Derived data types 45
C Do-while loop 77
C program, structure of 33 E
compilation and linking process 34 EXOR truth table 50
fundamental rules 33 F
to calculate sum & average of an array 102 Fibonacci series 129
to delete the specified integer from an Flowchart 20
array 103 building blocks in 21
to read an array 106 For loop 74
to sort the names in alphabetical order 105 Function 120
C programming 32 definition 124
Call by reference 125 Function call 123
Call by value 124 G
Code with null pointer 131 Global variables 38
Comma operator 64
H
Compilers 23
Hexadecimal number system 14
Computer hardware-software architecture 22
Hexadecimal to binary conversion 17
Computer network types 26
Computer software 22, 23

Book 8.indb 189 6/7/2017 1:29:14 PM


190 Index

I Pointer variable method 161


Identifiers 40 Pointer variable’s contents 133
if Condition 68 Preprocessor directives 169
if-else Condition 68 Primary data types 41
Increment operator (++) 61 Programming examples 101
Indirection operator 58 Pseudocode 17
Initialization arrays 91 R
Input 66 Radix in number systems 14
Internet terminology 25 Recursion 126
Internet, building blocks of 26 Relational operators 53
Interpreters 23 Right shift (>>) 51
K S
Keyword 39 Single system bus 13
L Single-dimensional array 89
Left shift (<<) 50 Size of() operator 59
Logical operators 46, 48 Software
Looping statements 74 applications 24
M terminologies 24
Matrix operations 107 Software application 23, 24
to find column of M×N matrix 109 String arrays 99
to find the sum of each row 109 String operations 96
to find the transpose of a given Strings 88, 101
matrix 108 Structure 147
Moore’s law 5 Structure
Multiple indirection 134 data type 151
Nested if condition 71 declaration 149
N within a structure 156
Non-decimal to binary conversion 16 Switch case 72
Normal variable method 161 T
NOT operator (!) 58 Two-dimensional array 93
NOT truth table 48 characteristics of 94, 98
Number systems 13 Type casting operator 59
O U
Octal number system 14 Unary minus 58
Octal to binary conversion 16 Unary operators 57
One’s complement (~) 51 Unary plus 58
One’s complement operator 59 Union 147, 158
One-dimensional array 93 URL (Uniform Resource Locator) 25
Operators 45 V
precedence of 65 Valid and invalid float representations 43
Or truth table 47 Valid and invalid integer representations 42
Output operations 66 Variables 37
P Void pointer 132
Pidgin code 18 W
Platform software 24 Web page 25
Pointers 130 While loop 76
compatibility among 135

Book 8.indb 190 6/7/2017 1:29:14 PM


Fundamentals of Computing and Programming provides not only theoretical knowledge, but TM

also practical aspects to make the student industry-ready. Each chapter is presented in a
unique way with a lot of examples, sample programs and, most importantly, comprehensive
interview readiness questions in the last section, which will not only help revisit the concepts,
but also make sure that the student can face the interviewer in this prescribed area without
fear and hesitation.
The book starts with the fundamentals, characteristics of computers, generations,
organisation and architecture of computers, number systems, software classification, the
Internet, and so on. This chapter is aimed at giving the student a platform for the subject and
to set the mood for further reading. The language chosen is simple and understandable.
Chapter 2 deals with C programming, its introduction, fundamental rules and guidelines,
process of compilation and linking, variables, naming conventions, operators, etc. All these
topics have examples to substantiate the learning process. Chapter 3 discusses arrays and
string operations quite comprehensively while chapter 4 is all about functions and pointers.
Chapter 5 discusses the structures and unions with coverage also given to the preprocessor
directives. Each chapter other than chapter 1 has interview questions as part of it.

INTRODUCTION TO COMPUTERS
Introduction • Characteristics of Computers • Computer Generations • Classification of Computers
• Basic Computer Organisation • Number Systems • Algorithm • Pseudocode • Flowchart • Computer
Software • Types of Software • Internet Terminology

C PROGRAMMING BASICS
Introduction to C Programming • Fundamental Rules • Structure of a C Program • Compilation and
Linking Processes • Constants, Variables, Keywords, Identifiers, Delimiters • Declaring and Initialising
Variables • Data Types • Operators and Expressions • Managing Input and Output Operations
• Decision Making and Branching • Looping Statements • Solving Simple Scientific and Statistical
Problems.

ARRAYS AND STRINGS


Arrays • Characteristics, Initialisation • Declaration • One-Dimensional and Two-Dimensional Arrays
• String • String Operations • String Arrays • Simple Programs • Sorting • Searching • Matrix Operations
(Addition, Subtraction and Multiplication).

FUNCTIONS AND POINTERS


Function • Definition of Function • User-defined Functions • Declaration of Function • Call by Reference
• Call by Value • Recursion • Pointers • Definition • Initialisation • Pointers Arithmetic • Pointers and
Arrays • Example Problems.

S. Karthik • B. Chellaprabha • T. Kalaikumaran


STRUCTURES AND UNIONS
Defining Structures and Unions • Structure Declaration • Need for Structure Data Type • Structure
within a Structure • Union-Programs using Structures and Unions • Preprocessor Directives.

Dr. S. Karthik is Dean and Professor, Dept. of CSE, SNS College of Technology, Coimbatore. S. Karthik
Dr. B. Chellaprabha is Head – Academics, Dept. of CSE, SNS College of Technology, Coimbatore.
Dr. T. Kalaikumaran is Head and Professor, Dept. of CSE, SNS College of Technology, Coimbatore. B. Chellaprabha
978-93-89633-46-7 T. Kalaikumaran
Distributed by:

9 789389 633467
TM

You might also like