Sanet.st-fundamentals of Computing and Programming
Sanet.st-fundamentals of Computing and Programming
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.
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
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
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
S. Karthik
B. Chellaprabha
T. Kalaikumaran
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
LEARNING OBJECTIVES
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.
Output Devices
System
Unit
Mango
Pulp
Mango
Churning Shake
Sugar
Process Output
Milk
Input
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
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.
Processing Unit
e.g. CPU
Storage Device
e.g. DVD, Pen drive
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.
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
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 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
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
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.
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.
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.
FIRST
SECOND
THIRD
FOURTH
FIFTH
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.
Computer
Microcomputer
Minicomputer
Mainframe computer
Supercomputer
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
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.
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.
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.
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.
Processor
Control Unit
Data path
Arithmetic
Logic Unit Memory
Output Input
Program Data
Units Units
Registers Storage Storage
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.
CPU Clock
CPU
Timer /
Counter Memory I/O Interface
Memory
Clock
Timer USART
I/O Interface
Memory
Other Peripherals
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.
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
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.
Control Bus
Address Bus
Data 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.
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.
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.
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.
3 (58)10
In this example, the decimal equivalent of the binary value (111010)2 is (58)10.
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.
3 (101000)2
In this example, the binary equivalent of the octal value (50)8 is (101000)2.
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 310510
2 (35)16 0011201012
3 (00110101)2
In this example, the binary equivalent of the hexadecimal value (35)16 is (00110101)2.
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:
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
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.
1.8 FLOWCHARTS
START
No
Is Mixer Plug in
plugged in? Mixer
Yes
No
Replace
Burnt motor?
Motor
Yes
Repair Mixer
STOP
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.
There are also other kinds of symbols or shapes used but are not common in usage.
They are listed below:
▪▪ 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.
User
Application Software
System Software
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
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
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.
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.
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.
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.
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.
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:
Printer
The Internet
Switch
Router
Server
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
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.
•• 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.
•• 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.
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?
LEARNING OBJECTIVES
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.
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!
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.
•• 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
./execfile
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.
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.
•• 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.
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.
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
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.
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!
In addition to the above keywords, Table 2.4 lists down a few more keywords which
are supported by a few compliers.
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.
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.
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
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.
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.
Let us learn through a simple C program to determine the size of different data type
values. Following code 2.5 depicts a sample
Having seen the primitive data type, we will see the derived data types.
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:
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).
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.
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)
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.
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.
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.
On executing the above program, we get to see the following (Output 2.5).
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.
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.
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.
When we cast explicitly, the issue will be overcome. It is shown in Program 2.13.
This code will produce the expected result as follows in Output 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.
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;
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.
Output is as follows.
Output 2.8
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.
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.
Just like printf(), we can try formatting scanf() too. The syntax is given below.
%[*][width][length]format-specifier.
For example, scanf(“%79s”,str);
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.
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.
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.
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.
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.
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.
There is one more form of if-else construct. We call it cascading if-else where
there are multiple ‘else if’ clauses.
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.
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
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.
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.
Upon executing the above code, we can see Hello, Welcome to C programming 100
times. A portion of outputis shown in Output 2.13:
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.
}
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.
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.
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.
Note: If we try the above program using a while loop, we will be seeing the results
as follows in Program 2.26.
printf(“\t”);
}
}
return 0;
}
{
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);
}
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); }
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
LEARNING OBJECTIVES
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.
Heap Memory
String [] array
Index 0 1 2 3 4
reference
null null null null null
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
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++ ) {
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
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.
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.
#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
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 ]
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
#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;
}
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’};
Variable H e l l o \o
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
There are a couple of functions that are supported and manipulate the null-terminated
strings. They are detailed in Table 3.3.
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
J o h n \0 ...
names[0]
S u e \0 ...
names[1]
...
names[2]
...
...
names[MAX–1] gets() (340,140)
Before operating on the strings, they need to be declared first. They can be declared
using arrays or using pointers as follows.
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;
}
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:
#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;
}
#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);
}
In this section, we will learn to write simple programs using C programming language.
#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;
{
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);
}
#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);
}
}
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”);
}
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++)
{
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
#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”);
}
}
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;
}
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;
}
}
#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++)
{
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”);
}
•• 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.
•• 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
EXERCISE
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);
}
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]);
}
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.
LEARNING OBJECTIVES
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.
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;
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
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.
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.
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.
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.
{
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:
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.
#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 ();
}
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.
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;
}
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 .
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;
}
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.
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.
#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;
return 0;
}
The output for the above code shown in Program 4.6 gives the following output.
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!
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.
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)
# 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;
}
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.
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
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.
The execution result of above is presented below (Code 4.9) for the better under-
standing of the reader.
# 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;
}
Reader can understand the functioning of the pointer through this simple example
and the execution output.
The result the compilation would give is an error, i.e., compilation fault.
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 = #
q = #
printf (“\n When used with integer pointer: %f”, *p);
printf (“\n When used with float pointer: %f”, *q);
getchar();
return 0;
}
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.
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.
#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
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.
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.
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
When the above code is executed, one would get the following output.
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;
}
Reader would have now understood the usage of pointer with array.
EXERCISE
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.
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;}
LEARNING OBJECTIVES
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;
};
Structure Union
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
{
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;
}
Structure Unions
Memory Sharing
X Y X &Y
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.
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;
char month[10];
int year;
};
struct date today;
// Here“today” refers to the name of variable and “date” refers to the name of structure.
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.
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.
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:
structLibrary_Books {
char book_title[50];
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);
#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;
};
int main( ) {
/* 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;
return 0;
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 );
#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);
{
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;
}
5.5 UNION
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
name
Marks
•• 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;
•• Each data member within a structure are assigned its own unique storage area.
•• 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
Table 5.1 helps to understand on how to form a C union, union declaration, initializing
and accessing the union members.
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.
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
.
.
.
Displaying Information:
}
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
flushall();
printf(“\nEnterthe student sex : “);
scanf(“%c”, &set.st.stud_sex);
printf(“\nEnter the student percentage :”);
scanf(“%f”, &set.st.stud_percentage);
getch();
}
Program 5.13 Usage of structure within union
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
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.
Preprocessor directives
#
##
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
{
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.
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); }
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
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.
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?
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.
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.
Conditional Statements:
Statement Syntax
Goto Goto label;
If If(condition) {block}
If(condition) {block}
If…else
else {block}
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}
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)
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.
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