0% found this document useful (0 votes)
196 views

Computer Programming

Uploaded by

Diksha Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
196 views

Computer Programming

Uploaded by

Diksha Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 344

MASTER OF

COMPUTER APPLICATIONS
COMPUTER PROGRAMMING

MCA612/MCA617

Kiran Gurbani
CHANDIGARH UNIVERSITY
Institute of Distance and Online Learning
Course Development Committee
Chairman
Prof. (Dr.) R.S. Bawa
Vice Chancellor, Chandigarh University, Punjab

Advisors
Prof. (Dr.) Bharat Bhushan, Director, IGNOU
Prof. (Dr.) Majulika Srivastava, Director, CIQA, IGNOU
Programme Coordinators & Editing Team
Master of Business Administration (MBA) Bachelor of Business Administration (BBA)
Co-ordinator - Prof. Pragya Sharma Co-ordinator - Dr. Rupali Arora
Master of Computer Applications (MCA) Bachelor of Computer Applications (BCA)
Co-ordinator - Dr. Deepti Rani Sindhu Co-ordinator - Dr. Raju Kumar
Master of Commerce (M.Com.) Bachelor of Commerce (B.Com.)
Co-ordinator - Dr. Shashi Singhal Co-ordinator - Dr. Minakshi Garg
Master of Arts (Psychology) Bachelor of Science (Travel & Tourism Management)
Co-ordinator - Dr. Samerjeet Kaur Co-ordinator - Dr. Shikha Sharma
Master of Arts (English) Bachelor of Arts (General)
Co-ordinator - Dr. Ashita Chadha Co-ordinator - Ms. Neeraj Gohlan
Master of Arts (Mass Communication and Bachelor of Arts (Mass Communication and
Journalism) Journalism)
Co-ordinator - Dr. Chanchal Sachdeva Suri Co-ordinator - Dr. Kamaljit Kaur
Academic and Administrative Management

Prof. (Dr.) Pranveer Singh Satvat Prof. (Dr.) S.S. Sehgal


Pro VC (Academic) Registrar
Prof. (Dr.) H. Nagaraja Udupa Prof. (Dr.) Shiv Kumar Tripathi
Director – (IDOL) Executive Director – USB
© No part of this publication should be reproduced, stored in a retrieval system, or transmitted in any form
or by any means, electronic, mechanical, photocopying, recording and/or otherwise without the prior
written permission of the author and the publisher.

SLM SPECIALLY PREPARED FOR


CU IDOL STUDENTS

Printed and Published by:


Himalaya Publishing House Pvt. Ltd.,
E-mail: [email protected], Website: www.himpub.com

For: CHANDIGARH UNIVERSITY


Institute of Distance and Online Learning
COMPUTER PROGRAMMING PRACTICAL

Course Code: MCA617 Credits: 1

Course Objectives:
 To develop programming logic, use of programming instructions, syntax and program
structure.
 To analyze the foundation of complex programming languages like C++ etc.
 To practice the techniques for the development and application of problem-solving skills.

Syllabus
1 C Basics and Control structure:
1. Write a program that reads two nos. from key board and gives their addition, subtraction,
multiplication, division and modulo
2. The distance between two cities (In KM) is input through key board. Write a program to
convert and print this distance in meters, feet, inches and centimeters.
3. Write a C program to perform post and pre-increment, post and pre-decrement operations.
4. Write a program which implements the working of all Bit-wise operators
5. Write a program to select and print the largest of the three nos. using Nested-If-Else
statement.
6. Write a program to perform arithmetic operations using switch case.
7. Write a program to find sum of all integers greater than 100 & less than 200 and are
divisible by 5.
8. Write a C program to implement

x x2 x3
ex  1    ,
1! 2! 3!
2. Arrays, Strings, Functions and Structure:
1. Write a program to perform various matrix operations, Addition, Subtraction,
Multiplication, Transpose using switch-case statement
2. Programs based on string handling
3. Write a program using function to implement Pascal Triangle

4. Write a program that used user defined function Swap ( ) and interchange the value of
two variable.
5. Write a function prime that return 1 if it’s argument is prime and return 0 otherwise
6. Define a structure type, personal, that would contain person name, date of joining and
salary. Using this structure, write a program to read this information for one person
from the key screen.
7. Define a structure called cricket that will describe the following information: (a) Player
name (b) Team name (c) Batting average

3. Pointers and DMA:


1. Write a program using pointer and function to determine the length of string.
2. Write a program using pointer to compare two strings.
3. Write a program using pointer to concatenate two strings.
4. Write a program using pointer to copy one string to another string.
5. Write a program using pointer to read an array if integer and print element in reverse
order.
6. Write a program that uses a table of integers whose size will be specified interactively
at run time.
7. Write a program to store a character string in block of memory space created by malloc
and then modify the same to store a large string.

4. C Pre-Processor and File management:


1. Write a program which reads diameter and height of a cone and calculate its volume
using macros.
2. A program to illustrate reading files contents.
3. A program to illustrate the use of fgets( )
4. A program to illustrate the use of fputc ( ) and fputs( )

Text Books:
1. Balaguruswamy (2017 ).Programming in ANSI C. New Delhi: McGraw-Hill.
2. Kanetkar, Y. (2014), Programming in C ANSI standard. New Delhi: BPB Publications.
3. Gottfried (2005).Programming with C. New York: Tata McGraw-Hill.

Reference Books:
1. Harrow K., Jones J. (1996). Problem Solving with C. London: Pearson Education.
2. Jeri R., Hanly, Koffman E.P. (2000). Problem Solving and Program Design in C. 3rd
Ed. Boston: Addison Wesley.
CONTENTS

Unit 1: Introduction to Computer and Programming 1 – 28

Unit 2 Fundamentals of C 29 – 60

Unit 3 Operators and Expressions 61 – 98

Unit 4 Decision and Loop Control structure 99 – 133

Unit 5 Arrays 134 - 144

Unit 6 Strings 145 - 158

Unit 7 Functions 159 - 190

Unit 8 Pointers 191 – 216

Unit 9 Structure 217 – 243

Unit 10 Dynamic Memory Allocation 244 – 259

Unit 11 C Preprocessor 260 – 271

Unit 12 File Management 272 – 302

Practical Unit 1 C Basics and Control Structure 303 – 310

Practical Unit 2 Arrays, Strings, Functions and Structure 311 – 324

Practical Unit 3 Pointers and DMA 325 – 332

Practical Unit 4 C Pre-Processor and File Management 333 – 336


Introduction to Computer and Programming 1

UNIT 1 INTRODUCTION TO COMPUTER AND


PROGRAMMING

Structure:
1.0 Learning Objectives
1.1 Introduction
1.2 Basic Block Diagrams
1.3 Interconnection between Functional Components
1.4 Algorithm Flowcharts
1.5 Machines and Knowledge about Problem Solving
1.6 Stages of Program Development Process
1.7 Importance of Discipline in Programming
1.8 Summary
1.9 Key Words/Abbreviations
1.10 Learning Activity
1.11 Unit End Questions (MCQ and Descriptive)
1.12 References

1.0 Learning Objectives


After studying this unit, you will be able to:
 Define computer
 Draw the block diagram of computer
 Explain functioning of different components of computer
 Describe algorithm and flowcharts

CU IDOL SELF LEARNING MATERIAL (SLM)


2 Computer Programming

 Describe the machines related to problem solving


 Discuss the knowledge and concepts of problem solving
 Explain problem development steps
 Elaborate the importance of discipline in problem solving

1.1 Introduction
Being a modern-day kid you must have used, seen, or read about computers. This is because
they are an integral part of our everyday existence. Be it school, banks, shops, railway stations,
hospital or your own home, computers are present everywhere, making our work easier and faster
for us. As they are such integral parts of our lives, we must know what they are and how they
function. Let us start with defining the term computer formally.

Types of Computers:
Computers can be generally classified by size and power as follows, though there is considerable
overlap:
 Personal computer: A small, single-user computer based on a microprocessor.
 Workstation: A powerful, single-user computer. A workstation is like a personal
computer, but it has a more powerful microprocessor and, in general, a higher-quality
monitor.
 Minicomputer: A multi-user computer capable of supporting up to hundreds of users
simultaneously.
 Mainframe: A powerful multi-user computer capable of supporting many hundreds or
thousands of users simultaneously.
 Supercomputer: An extremely fast computer that can perform hundreds of millions of
instructions per second.

Supercomputer and Mainframe


Supercomputer is a broad term for one of the fastest computers currently available.
Supercomputers are very expensive and are employed for specialized applications that require
immense amounts of mathematical calculations (number crunching). For example, weather

CU IDOL SELF LEARNING MATERIAL (SLM)


Introduction to Computer and Programming 3

forecasting requires a supercomputer. Other uses of supercomputers scientific simulations (animated)


graphics, fluid dynamic calculations, nuclear energy research, electronic design, and analysis of
geological data (e.g., in petrochemical prospecting). Perhaps the best known supercomputer
manufacturer is Cray Research.
Mainframe was a term originally referring to the cabinet containing the central processor unit
or “main frame” of a room-filling Stone Age batch machine. After the emergence of smaller
“minicomputer” designs in the early 1970s, the traditional big iron machines were described as
“mainframe computers” and eventually just as mainframes. Nowadays a Mainframe is a very large
and expensive computer capable of supporting hundreds, or even thousands, of users simultaneously.
The chief difference between a supercomputer and a mainframe is that a supercomputer channels
all its power into executing a few programs as fast as possible, whereas a mainframe uses its power
to execute many programs concurrently. In some ways, mainframes are more powerful than
supercomputers because they support more simultaneous programs. But supercomputers can execute
a single program faster than a mainframe. The distinction between small mainframes and
minicomputers is vague, depending really on how the manufacturer wants to market its machines.

Minicomputer
It is a midsize computer. In the past decade, the distinction between large minicomputers and
small mainframes has blurred, however, as has the distinction between small minicomputers and
workstations. But in general, a minicomputer is a multiprocessing system capable of supporting
from up to 200 users simultaneously.

Workstation
It is a type of computer used for engineering applications (CAD/CAM), desktop publishing,
software development, and other types of applications that require a moderate amount of computing
power and relatively high quality graphics capabilities. Workstations generally come with a large,
high-resolution graphics screen, at large amount of RAM, built-in network support, and a graphical
user interface. Most workstations also have a mass storage device such as a disk drive, but a special
type of workstation, called a diskless workstation, comes without a disk drive. The most common
operating systems for workstations are UNIX and Windows NT. Like personal computers, most
workstations are single-user computers. However, workstations are typically linked together to
form a local-area network, although they can also be used as stand-alone systems.

CU IDOL SELF LEARNING MATERIAL (SLM)


4 Computer Programming

N.B.: In networking, workstation refers to any computer connected to a local-area network. It


could be a workstation or a personal computer.

Personal Computer
It can be defined as a small, relatively inexpensive computer designed for an individual user.
In price, personal computers range anywhere from a few hundred pounds to over five thousand
pounds. All are based on the microprocessor technology that enables manufacturers to put an entire
CPU on one chip. Businesses use personal computers for word processing, accounting, desktop
publishing, and for running spreadsheet and database management applications. At home, the most
popular use for personal computers is for playing games and recently for surfing the Internet.
Personal computers first appeared in the late 1970s. One of the first and most popular personal
computers was the Apple II, introduced in 1977 by Apple Computer. During the late 1970s and
early 1980s, new models and competing operating systems seemed to appear daily. Then, in 1981,
IBM entered the fray with its first personal computer, known as the IBM PC. The IBM PC quickly
became the personal computer of choice, and most other personal computer manufacturers fell by
the wayside. P.C. is short for personal computer or IBM PC. One of the few companies to survive
IBM’s onslaught was Apple Computer, which remains a major player in the personal computer
marketplace. Other companies adjusted to IBM’s dominance by building IBM clones, computers
that were internally almost the same as the IBM PC, but that cost less. Because IBM clones used
the same microprocessors as IBM PCs, they were capable of running the same software. Over the
years, IBM has lost much of its influence in directing the evolution of PCs. Therefore, after the
release of the first PC by IBM the term PC increasingly came to mean IBM or IBM-compatible
personal computers, to the exclusion of other types of personal computers, such as Macintoshes. In
recent years, the term PC has become more and more difficult to pin down. In general, though, it
applies to any personal computer based on an Intel microprocessor, or on an Intel-compatible
microprocessor. For nearly every other component, including the operating system, there are several
options, all of which fall under the rubric of PC.
Today, the world of personal computers is basically divided between Apple Macintoshes and
PCs. The principal characteristics of personal computers are that they are single-user systems and
are based on microprocessors. However, although personal computers are designed as single-user
systems, it is common to link them together to form a network. In terms of power, there is great

CU IDOL SELF LEARNING MATERIAL (SLM)


Introduction to Computer and Programming 5

variety. At the high end, the distinction between personal computers and workstations has faded.
High-end models of the Macintosh and PC offer the same computing power and graphics capability
as low-end workstations by Sun Microsystems, Hewlett-Packard, and DEC.

Personal Computer Types


Actual personal computers can be generally classified by size and chassis / case. The chassis
or case is the metal frame that serves as the structural support for electronic components. Every
computer system requires at least one chassis to house the circuit boards and wiring. The chassis
also contains slots for expansion boards. If you want to insert more boards than there are slots, you
will need an expansion chassis, which provides additional slots. There are two basic flavours of
chassis designs – desktop models and tower models — but there are many variations on these two
basic types. Then come the portable computers that are computers small enough to carry. Portable
computers include notebook and subnotebook computers, hand-held computers, palmtops, and PDAs.

Tower Model
The term refers to a computer in which the power supply, motherboard, and mass storage
devices are stacked on top of each other in a cabinet. This is in contrast to desktop models, in which
these components are housed in a more compact box. The main advantage of tower models is that
there are fewer space constraints, which makes installation of additional storage devices easier.

Desktop Model
A computer designed to fit comfortably on top of a desk, typically with the monitor sitting on
top of the computer. Desktop model computers are broad and low, whereas tower model computers
are narrow and tall. Because of their shape, desktop model computers are generally limited to three
internal mass storage devices. Desktop models designed to be very small are sometimes referred to
as slimline models.

Notebook Computer
An extremely lightweight personal computer. Notebook computers typically weigh less than
6 pounds and are small enough to fit easily in a briefcase. Aside from size, the principal difference
between a notebook computer and a personal computer is the display screen. Notebook computers
use a variety of techniques, known as flat-panel technologies, to produce a lightweight and non-
bulky display screen. The quality of notebook display screens varies considerably. In terms of

CU IDOL SELF LEARNING MATERIAL (SLM)


6 Computer Programming

computing power, modern notebook computers are nearly equivalent to personal computers. They
have the same CPUs, memory capacity, and disk drives. However, all this power in a small package
is expensive. Notebook computers cost about twice as much as equivalent regular-sized computers.
Notebook computers come with battery packs that enable you to run them without plugging them
in. However, the batteries need to be recharged every few hours.

Laptop Computer
A small, portable computer — small enough that it can sit on your lap. Nowadays, laptop
computers are more frequently called notebook computers.

Subnotebook Computer
A portable computer that is slightly lighter and smaller than a full-sized notebook computer.
Typically, subnotebook computers have a smaller keyboard and screen, but are otherwise equivalent
to notebook computers.

Hand-held Computer
A portable computer that is small enough to be held in one’s hand. Although extremely
convenient to carry, hand-held computers have not replaced notebook computers because of their
small keyboards and screens. The most popular hand-held computers are those that are specifically
designed to provide PIM (personal information manager) functions, such as a calendar and address
book. Some manufacturers are trying to solve the small keyboard problem by replacing the keyboard
with an electronic pen. However, these pen-based devices rely on handwriting recognition
technologies, which are still in their infancy. Hand-held computers are also called PDAs, palmtops
and pocket computers.

Palmtop
A small computer that literally fits in your palm. Compared to full-size computers, palmtops
are severely limited, but they are practical for certain functions such as phone books and calendars.
Palmtops that use a pen rather than a keyboard for input are often called hand-held computers or
PDAs. Because of their small size, most palmtop computers do not include disk drives. However,
many contain PCMCIA slots in which you can insert disk drives, modems, memory, and other
devices. Palmtops are also called PDAs, hand-held computers and pocket computers.

CU IDOL SELF LEARNING MATERIAL (SLM)


Introduction to Computer and Programming 7

PDA
Short for personal digital assistant, a handheld device that combines computing, telephone/
fax, and networking features. A typical PDA can function as a cellular phone, fax sender, and
personal organizer. Unlike portable computers, most PDAs are pen-based, using a stylus rather
than a keyboard for input. This means that they also incorporate handwriting recognition features.
Some PDAs can also react to voice input by using voice recognition technologies. The field of PDA
was pioneered by Apple Computer, which introduced the Newton MessagePad in 1993. Shortly
thereafter, several other manufacturers offered similar products. To date, PDAs have had only
modest success in the marketplace, due to their high price tags and limited applications. However,
many experts believe that PDAs will eventually become common gadgets.
PDAs are also called palmtops, hand-held computers and pocket computers.

1.2 Basic Block Diagrams

Input-Process-Output Model
Computer input is the data entered by the user for the storage, processing, and manipulation and
the output obtained after processing it, based on user’s instructions is called information. Raw
facts and figures which can be processed using arithmetic and logical operations to obtain information
are called data.

Fig. 1.1: Input-Process-Output Model

The processes that can be applied to data are of two types —


 Arithmetic operations —  Examples  include  calculations  like  addition,  subtraction,
differentials, square root, etc.

CU IDOL SELF LEARNING MATERIAL (SLM)


8 Computer Programming

 Logical operations — Examples include comparison operations like greater than, less
than, equal to, opposite, etc.
The corresponding figure for an actual computer looks something like this —

Memory Section

Fig. 1.2: Basic Parts of a Computer

The basic parts of a computer are as follows —


 Input Unit —   Devices  like  keyboard  and  mouse  that  are  used  to  input  data  and
instructions to the computer are called input unit.
 Output Unit —  Devices  like  printer  and visual  display  unit that  are  used to  provide
information to the user in desired format are called output unit.
 Control Unit — As the name suggests, this unit controls all the functions of the computer.
All devices or parts of computer interact through the control unit.
 Arithmetic Logic Unit —  This  is  the  brain  of  the  computer  where  all  arithmetic
operations and logical operations take place.
An arithmetic logic unit (ALU) is a major component of the central processing unit of a
computer system. It does all processes related to arithmetic and logic operations that need to be
done on instruction words. In some microprocessor architectures, the ALU is divided into the
arithmetic unit (AU) and the logic unit (LU).
An ALU can be designed by engineers to calculate any operation. As the operations become
more complex, the ALU also becomes more expensive, takes up more space in the CPU and dissipates
more heat. That is why engineers make the ALU powerful enough to ensure that the CPU is also
powerful and fast, but not so complex as to become prohibitive in terms of cost and other
disadvantages.

CU IDOL SELF LEARNING MATERIAL (SLM)


Introduction to Computer and Programming 9

An arithmetic logic unit is also known as an integer unit (IU).


The arithmetic logic unit is that part of the CPU that handles all the calculations the CPU may
need. Most of these operations are logical in nature. Depending on how the ALU is designed, it can
make the CPU more powerful, but it also consumes more energy and creates more heat. Therefore,
there must be a balance between how powerful and complex the ALU is and how expensive the
whole unit becomes. This is why faster CPUs are more expensive, consume more power and dissipate
more heat.
The main functions of the ALU are to do arithmetic and logic operations, including bit shifting
operations. These are essential processes that need to be done on almost any data that is being
processed by the CPU.
ALUs routinely perform the following operations:
 Logical Operations: These include AND, OR, NOT, XOR, NOR, NAND, etc.
 Bit-Shifting Operations: This pertains to shifting the positions of the bits by a certain
number of places to the right or left, which is considered a multiplication operation.
 Arithmetic Operations: This refers to bit addition and subtraction. Although
multiplication and division are sometimes used, these operations are more expensive to
make. Addition can be used to substitute for multiplication and subtraction for division.
 Memory: All input data, instructions and data interim to the processes are stored in the
memory. Memory is of two types – primary memory and secondary memory. Primary
memory resides within the CPU whereas secondary memory is external to it.
Control unit, arithmetic logic unit and memory are together called the central processing
unit or CPU. Computer devices like keyboard, mouse, printer, etc. that we can see and touch are
the hardware components of a computer. The set of instructions or programs that make the computer
function using these hardware parts are called software. We cannot see or touch software. Both
hardware and software are necessary for working of a computer.

1.3 Interconnection between Functional Components


A computer consists of input unit that takes input, a CPU that processes the input and an
output unit that produces output. All these devices communicate with each other through a common

CU IDOL SELF LEARNING MATERIAL (SLM)


10 Computer Programming

bus. A bus is a transmission path, made of a set of conducting wires over which data or information
in the form of electric signals, is passed from one component to another in a computer. The bus can
be of three types – Address bus, Data bus and Control Bus.
Following figure shows the connection of various functional components:

Fig. 1.3: Interconnection between Functional Components

The address bus carries the address location of the data or instruction. The data bus carries
data from one component to another and the control bus carries the control signals. The system bus
is the common communication path that carries signals to/from CPU, main memory and input/
output devices. The input/output devices communicate with the system bus through the controller
circuit which helps in managing various input/output devices attached to the computer.

Characteristics of Computer
To understand why computers are such an important part of our lives, let us look at some of its
characteristics —

CU IDOL SELF LEARNING MATERIAL (SLM)


Introduction to Computer and Programming 11

 Speed — Typically, a computer can carry out 3-4 million instructions per second.
 Accuracy — Computers exhibit a very high degree of accuracy. Errors that may occur
are usually due to inaccurate data, wrong instructions or bug in chips – all human errors.
 Reliability — Computers can carry out same type of work repeatedly without throwing
up errors due to tiredness or boredom, which are very common among humans.
 Versatility — Computers can carry out a wide range of work from data entry and ticket
booking to complex mathematical calculations and continuous astronomical
observations. If you can input the necessary data with correct instructions, computer
will do the processing.
 Storage Capacity — Computers can store a very large amount of data at a fraction of
cost of traditional storage of files. Also, data is safe from normal wear and tear associated
with paper.

Advantages of Using Computer


Now that we know the characteristics of computers, we can see the advantages that computers
offer:
 Computers can do the same task repetitively with same accuracy.
 Computers do not get tired or bored.
 Computers can take up routine tasks while releasing human resource for more intelligent
functions.

Disadvantages of Using Computer


Despite so many advantages, computers have some disadvantages of their own —
 Computers have no intelligence; they follow the instructions blindly without considering
the outcome.
 Regular electric supply is necessary to make computers work, which could prove difficult
everywhere especially in developing nations.

CU IDOL SELF LEARNING MATERIAL (SLM)


12 Computer Programming

1.4 Algorithm and Flowcharts


Algorithm and flowchart are two types of tools to explain the process of a program. This page
extends the differences between an algorithm and a flowchart, and how to create a flowchart to
explain an algorithm in a visual way.
Algorithms and flowcharts are two different tools used for creating new programs, especially
in computer programming. An algorithm is a step-by-step analysis of the process, while a flowchart
explains the steps of a program in a graphical way.

Definition of Algorithm
To write a logical step-by-step method to solve the problem is called algorithm, in other
words, an algorithm is a procedure for solving problems. In order to solve a mathematical or computer
problem, this is the first step of the procedure. An algorithm includes calculations, reasoning and
data processing. Algorithms can be presented by natural languages, pseudo code and flowcharts,
etc.

Definition of Flowchart
A flowchart is the graphical or pictorial representation of an algorithm with the help of different
symbols, shapes and arrows in order to demonstrate a process or a program. With algorithms, we
can easily understand a program. The main purpose of a flowchart is to analyze different processes.
Several standard graphics are applied in a flowchart:
 Terminal Box – Start/End

 Input/Output

CU IDOL SELF LEARNING MATERIAL (SLM)


Introduction to Computer and Programming 13

 Process/Instruction

 Decision

 Connector / Arrow

The graphics above represent different part of a flowchart. The process in a flowchart can be
expressed through boxes and arrows with different sizes and colours. In a flowchart, we can easily
highlight a certain element and the relationships between each part.

Difference between Algorithm and Flowchart


If you compare a flowchart to a movie, then an algorithm is the story of that movie. In other
words, an algorithm is the core of a flowchart. Actually, in the field of computer programming,
there are many differences between algorithm and flowchart regarding various aspects, such as the
accuracy, the way they display, and the way people feel about them. Below is a table illustrating the
differences between them in detail.
Table 1.1: Difference between Algorithm and Flowchart

Algorithm Flowchart
It is a procedure for solving problems. It is a graphic representation of a process.
The process is shown in step-by-step instruction. The process is shown in block-by-block
information diagram.
It is complex and difficult to understand. It is intuitive and easy to understand.
It is convenient to debug errors. It is hard to debug errors.
The solution is showcased in natural language. The solution is showcased in pictorial format.
It is somewhat easier to solve complex problem. It is hard to solve complex problem.
It costs more time to create an algorithm. It costs less time to create a flowchart.

CU IDOL SELF LEARNING MATERIAL (SLM)


14 Computer Programming

Characteristics of Algorithm

Finiteness

Fig. 1.4: Characteristics of Algorithm

Not all procedures can be called an algorithm. An algorithm should have the following
characteristics:
 Unambiguous: Algorithm should be clear and unambiguous. Each of its steps (or
phases), and their inputs/outputs should be clear and must lead to only one meaning.
 Input: An algorithm should have 0 or more well-defined inputs.
 Output: An algorithm should have 1 or more well-defined outputs, and should match
the desired output.
 Finiteness: Algorithms must terminate after a finite number of steps.
 Feasibility: Should be feasible with the available resources.
 Independent: An algorithm should have step-by-step directions, which should be
independent of any programming code.
Algorithms are mainly used for mathematical and computer programs, whilst flowcharts can
be used to describe all sorts of processes: business, educational, personal and of course algorithms.
So flowcharts are often used as a program planning tool to visually organize the step-by-step process
of a program. Here are some examples:

CU IDOL SELF LEARNING MATERIAL (SLM)


Introduction to Computer and Programming 15

Example 1: Print 1 to 20:

Algorithm:
Step 1: Initialize X as 0,
Step 2: Increment X by 1,
Step 3: Print X,
Step 4: If X is less than 20 then go back to step 2.
Flowchart:

Start

Initialize x = 0

Increment x by 1

Print x

YES
x > 20

No

End

Fig. 1.5: Flowchart for Printing 1 to 20

Example 2: Convert Temperature from Fahrenheit (°F) to Celsius (!)

Algorithm:
Step 1: Read temperature in Fahrenheit,
Step 2: Calculate temperature with formula C=5/9*(F-32),
Step 3: Print C,

CU IDOL SELF LEARNING MATERIAL (SLM)


16 Computer Programming

Flowchart:

Fig. 1.6: Flowchart for Converting Temperature from Fahrenheit (ºF) to Celsius (!)

Example 3: Determine Whether A Student Passed the Exam or Not:

Algorithm:
Step 1: Input grades of 4 courses M1, M2, M3 and M4,
Step 2: Calculate the average grade with formula “Grade=(M1+M2+M3+M4)/4”
Step 3: If the average grade is less than 60, print “FAIL”, else print “PASS”.

CU IDOL SELF LEARNING MATERIAL (SLM)


Introduction to Computer and Programming 17

Flowchart:

Fig. 1.7: Flowchart to Determine whether a Student passed the Exam or Not

1.5 Machines and Knowledge about Problem Solving


‘Machine learning’ is one of the popular buzzwords that have been slowly moving from the
tech side to the other departments. Every day, new applications for machine learning combined
with big data and artificial intelligence has been doing its rounds in almost all fields. With Google,
Amazon and Microsoft introducing their own machine learning platforms, it has attained newer
levels of fame!
Here are a few significant applications and solutions of machine learning that can be compared
with the business problems you have:

CU IDOL SELF LEARNING MATERIAL (SLM)


18 Computer Programming

Image Recognition
Remember how Facebook automatically tags your friends accurately when you upload a group
picture? Facebook started using machine learning to record the faces of the millions of Facebook
users and store them and identifies them with the faces in the picture you upload.
This face recognition technique from Facebook is just one application of machine learning in
image recognition. There are a lot of other applications in assembly lines in factories, in healthcare
applications and it has also been tested out with the driverless cars.

Customer Segmentation
This has been widely used by the marketing departments across all businesses. Customer
retention, churn prediction and lead generation have always been a major challenge for all marketers
but with the advancements in machine learning, marketers can now eliminate the guesswork and
get real-time, accurate results in customer segmentation from the past and current data. Marketers
can now get the complete analysis of each segment’s behaviour which can be leveraged in their
marketing campaigns for more specific results.

Customer Service
Customer service is yet another department that every company will have no matter the size
and the volume of the business. With the machine learning technology, businesses can now analyse
the past data from the customer support and provide better services to the customers while also
reducing the manpower.

Product Recommendations
This is majorly used in the e-commerce service sectors where the websites use machine learning
to tempt the customers in buying more things. Remember the section of ‘Also Bought’ in many
popular e-commerce websites where you will be displayed related items for the things you just
added to a cart?
This has been widely used by almost all online shopping websites where, based on the customer
historical data of the individual customer and the total gathered data, the top predicted things that
the customer will most likely buy will be displayed in the home page and in some sections of the
product pages too.

CU IDOL SELF LEARNING MATERIAL (SLM)


Introduction to Computer and Programming 19

Machine learning can definitely make a major impact in solving the business problems if the
right approach and the right set of data are used.

1.6 Stages of Program Development Process


The various stages in the development of a computer program are :
1. Problem Definition
2. Program Design
3. Coding
4. Debugging
5. Testing
6. Documentation
7. Maintenance

Fig. 1.8: Stages of Program Development Process

CU IDOL SELF LEARNING MATERIAL (SLM)


20 Computer Programming

Problem Definition:
 The first step in the process of program development is the thorough understanding and
identification of the problem for which is the program or software is to be developed.
 In this step the problem has to be defined formally.
 All the factors like Input/output, processing requirement, memory requirements, error
handling, interfacing with other programs have to be taken into consideration in this
stage.

Program Design:
 The next stage is the program design. The software developer makes use of tools like
algorithms and flowcharts to develop the design of the program.
 Algorithm

 Flowchart

Coding:
 Once the design process is complete, the actual computer program is written, i.e. the
instructions are written in a computer language.
 Coding is generally a very small part of the entire program development process and
also a less time consuming activity in reality.
 In this process all the syntax errors, i.e., errors related to spelling, missing commas,
undefined labels etc. are eliminated.
 For effective coding some of the guidelines which are applied are :
 Use of meaningful names and labels of variables,

 Simple and clear expressions,

 Modularity with emphasis on making modules generalized,

 Making use of comments and indenting the code properly,

 Avoiding jumps in the program to transfer control.

CU IDOL SELF LEARNING MATERIAL (SLM)


Introduction to Computer and Programming 21

Debugging:
 At this stage the errors in the programs are detected and corrected.
 This stage of program development is an important process. Debugging is also known
as program validation.
 Some common errors which might occur in the programs include:
 Uninitialization of variables.
 Reversing of order of operands.
 Confusion of numbers and characters.

 Inverting of conditions, e.g., jumping on zero instead of on not zero.

Testing:
 The program is tested on a number of suitable test cases.
 A test plan of the program has to be done at the stage of the program design itself.
 This ensures a thorough understanding of the specifications.
 The most trivial and the most special cases should be identified and tested.
 It is always useful to include the maximum and minimum values of all variables as test
data.

Documentation:
 Documentation is a very essential step in the program development.
 Documentation help the users and the people who maintain the software.
 This ensures that future modification if required can be done easily. Also it is required
during redesigning and maintenance.

Maintenance:
 Updating and correction of the program for changed conditions and field experience is
accounted for in maintenance.
 Maintenance becomes essential in following situations:
 Change in specification,
 Change in equipment,
 Errors which are found during the actual execution of the program.
CU IDOL SELF LEARNING MATERIAL (SLM)
22 Computer Programming

1.7 Importance of Discipline in Programming

Programming Discipline and Software Development Environment


A good programming discipline and software development environment goes a long way in
doing productive and efficient work. Here is a list:
1. Lots of programming errors can be avoided by proper usage of tools for compilation
and static code analysis.
2. For compilation, one should always use — Wall option.
3. For example: gcc -Wall myprogram.c
For static code analysis, “splint” utility.
4. The software development environment must have a Makefile, even if one has a single
C file. The advantage will become obvious as number of C files and header files grow
over a period of time.
5. In a big project, one needs to search for files, function names, variable names and so on.
One can use “cscope” and/or “ctags” utilities for this purpose.
6. All programs must follow a good C coding guideline. For Linux and C programming,
one should look at guidelines used by Linux kernel developers. Here are few links for
C-coding guidelines:
Mentioned below is a derived version of this C coding style:-

1. Indentation
The code must be indented properly. Use tabspaces for indentation. Web developers can use 4
or 8 spaces instead of tabspace for web publishing (For example publishing a post in sanfoundry.com).
Indentation level 0 -> align to column 1
Indentation level 1 -> indent by 1 tab to the right of indentation level 0
Indentation level n+1 -> indent by 1 tab to the right of indentation level n
Indentation levels in a switch statement is to align the “switch” and “case” labels in the same
column. For example:

CU IDOL SELF LEARNING MATERIAL (SLM)


Introduction to Computer and Programming 23

switch(var){
case’t’:
avar=10;
break;
case’u’:
avar=20;
break;
default:
break;
}

2. Breaking Long Lines and Strings


Don’t put multiple statements on a single line.
Don’t put multiple assignments on a single line either.
Don’t leave whitespace at the end of lines.
The maximum length of a line should be 80 columns. Statements longer than 80 columns will
be broken into sensible chunks. For example:

void fun(int a,int b,int c)


{
if(condition)
printf(“Warning this is a long printf with 3 parameters”
“ a: %u b: %u c: %u n”, a, b, c);
else
next_statement;
}

3. Placing Braces and Spaces


Put the opening brace last on the line, and put the closing brace first, thus:
if(x is true){
wedo y
}
CU IDOL SELF LEARNING MATERIAL (SLM)
24 Computer Programming

This applies to all non-function statement blocks (if, switch, for, while, do). E.g.:

switch(var){
case’t’:
avar=10;
break;
case’u’:
avar=20;
break;
default:
break;
}

However, there is one special case, namely functions: they have the opening brace at the
beginning of the next line.

1.8 Summary
 An electronic data processing device, which requires input raw data for processing and
generates the output in desired form. It stores the data in its memory which can be
accessed any number of times for reference from its memory. It is made up of a lot of
electronics, software and mechanical parts.
 A computer is divided into three basic units namely:
1. Input Unit
2. Central Processing Unit
3. Output Unit

(1) Input Unit


As the name suggests, this unit contains devices with the help of which the data is entered into
the computer. This unit is a basic requirement for computer system. The input devices are of many
types such as keyboard, mouse, joystick, microphone, camera etc. Input devices give different set
of input values converted into a form understandable to the computer.

CU IDOL SELF LEARNING MATERIAL (SLM)


Introduction to Computer and Programming 25

(2) Central Processing Unit (CPU)


Central Processing Unit (CPU) is known as the brain of the computer. It performs all types
of data processing operations as required by a programmer. It stores all the data, intermediate
results, and instructions as given by the programmer in the form of codes (program). Central
Processing Unit controls the operation of each part of the computer.
It has following three components:
1. Arithmetic Logic Unit (ALU)
2. Memory Unit
3. Control Unit

(3) Output Unit


The devices with the help of which we get the information from the computer are known as
the output devices. Output Unit is an interface between the computer and the user. Output devices
notify the information displayed into a form which is understandable by the computer user.

 Characteristics of Computer
1. Speed 
2. Accuracy 
3. Reliability
4. Versatility
5. Storage Capacity

 Problem
It is a systematic approach to find and implement the solution to a problem.

 Steps in Problem Solving


1. Problem Definition
2. Problem Analysis
3. Design
4. Coding

CU IDOL SELF LEARNING MATERIAL (SLM)


26 Computer Programming

5. Testing
6. Maintenance

1.9 Key Words/Abbreviations


 Algorithm: An Algorithm is  a  step  by  step  instruction  of  a  problem  which  defines  the
solution of a particular problem in simple language. An algorithm is expressed in pseudo code
which resembles somewhat with C language, but with some statements in English rather than any
kind of programming language. In Algorithm there is no ambiguity about which instruction is to
executed next.
 Flowchart: A flowchart is a graphical representation of an algorithm. Programmers often
use it as a program-planning tool to solve a problem. It makes use of symbols which are connected
among them to indicate the flow of information and processing.
The process of drawing a flowchart for an algorithm is known as “flowcharting”.
 Program: It is a set of instructions written in computer languages.

1.10 Learning Activity


1. Write algorithm and draw the flowchart to find average of three numbers.
.......................................................................................................................................
.......................................................................................................................................
2. Write algorithm and draw the flowchart to find whether a number entered is even or
odd.
.......................................................................................................................................
.......................................................................................................................................

1.11 Unit End Questions (MCQ and Descriptive)

A. Descriptive Type: Short Answer Type Questions


1. Define Computer and its characteristics.
2. Draw and explain Basic Block Diagram of Computer.

CU IDOL SELF LEARNING MATERIAL (SLM)


Introduction to Computer and Programming 27

3. Explain different Components of Computer.


4. What is Flowchart. Draw Symbols of flowchart.
5. What is Algorithm. Give any one example of writing Algorithm.
6. Explain different types of Algorithms.
7. Explain how Machines and Knowledge about solving can be done with computers.
8. What are different Steps involved in Program Development?
9. Explain Importance of Discipline in Programming.

B. Multiple Choice/Objective Type Questions


1. In how many generations a computer can be classified?
(a) 3 (b) 4
(c) 5 (d) 6
2. The brain of any computer system is
(a) CPU (b) Memory
(c) ALU (d) Control unit
3. Which generation of computer is still under development
(a) Fourth Generation (b) Fifth Generation
(c) Sixth Generation (d) Seventh Generation
(a) the number of partitions (b) the CPU utilization
(c) the memory size (d) all of the mentioned
4.  In computer science, algorithm refers to a pictorial representation of a flowchart.
(a) True (b) False
5. The process of drawing a flowchart for an algorithm is called __________
(a) Performance (b) Evaluation
(c) Algorithmic Representation (d) Flowcharting
Answers : 1. (c), 2. (a), 3. (b), 4. (b), 5. (d)

CU IDOL SELF LEARNING MATERIAL (SLM)


28 Computer Programming

1.12 References
1. https://www.includehelp.com/basics/computer-definition-parts-functions-and-its-
advantages.aspx
2. https://www.techoschool.com/MCA/Computer-Concepts-and-Programming-in-C/UNIT-
1-Basics-Of-Programming_Concept-of-Algorithm-and-Flowchart
3. http://newhorizonindia.edu/nhc_kasturinagar/wp-content/uploads/2018/07/PROBLEM-
SOLVING-TECHNIQUES-USING-C.pdf
4. Introduction to Computing Explorations in Language, Logic, and Machines by David
Evans
5. Introduction to computers by Rutendo Makaha



CU IDOL SELF LEARNING MATERIAL (SLM)


Fundamentals of C 29

UNIT 2 FUNDAMENTALS OF C

Structure:

2.0 Learning Objectives


2.1 Introduction
2.2 Features of C Language
2.3 Structure of C Program
2.4 Comments
2.5 Header Files and Body
2.6 Data Types
2.7 Constants
2.8 Format specifiers with scanf() and printf()
2.9 Variables
2.10 Summary
2.11 Key Words/Abbreviations
2.12 Learning Activity
2.13 Unit End Questions (MCQ and Descriptive)
2.14 References

2.0 Learning Objectives


After studying this unit, you will be able to:
 List the features of C language
 Describe the structure of C program

CU IDOL SELF LEARNING MATERIAL (SLM)


30 Computer Programming

 Define comments and header files


 Explain C data types

2.1 Introduction
C is a powerful general-purpose programming language. It is fast, portable and available in all
platforms.
If you are new to programming, C is a good choice to start your programming journey.
C was the basics language to write everything from operating systems (Windows and many
others) to complex programs like the Oracle database, Git, Python interpreter and more.
It is said that ‘C’ is a god’s programming language. One can say, C is a base for the programming.
If you know ‘C,’ you can easily grasp the knowledge of the other programming languages that uses
the concept of ‘C’.
It is essential to have a background in computer memory mechanisms because it is an important
aspect when dealing with the C programming language.

Why Name “C” was given to Language?


1. Many of C’s principles and ideas were derived from the earlier language B. (Ken
Thompson was the developer of B Language.)
2. BCPL and CPL are the earlier ancestors of B Language.
3. CPL is common Programming Language. In 1967, BCPL Language (Basic CPL) was
created as a scaled down version of CPL.
4. As many of the features were derived from “B” Language that’s why it was named
as “C”.
5. After 7-8 years C++ came into existence which was first example of object-oriented
programming.

CU IDOL SELF LEARNING MATERIAL (SLM)


Fundamentals of C 31

C Programming Language Timeline:

ANSI Committee

ISO Committee

Fig. 2.1: C Programming Language Timeline

C language has evolved from three different structured languages ALGOL, BCPL and B
Language. It uses many concepts from these languages and introduced many new concepts such as
data types, structure pointer.
In 1988, the language was formalized by American National Standard Institute (ANSI).
In 1990, a version of C language was approved by the International Standard Organization
(ISO) and that version of C is also referred to as C89.

2.2 Features of C Language

Features of C language:
C is a structured programming language, which means that it allows you to develop programs
using well defined control structures (you will learn about control structures in the articles to

CU IDOL SELF LEARNING MATERIAL (SLM)


32 Computer Programming

come), and provides modularity (breaking the task into multiple sub tasks that are simple enough to
understand and to reuse).
C is often called a middle-level language because it combines the best elements of low-level
or machine language with high-level languages.

Portable Structured

Simple
Mid-level

Memory
Management C Language Rich Library

Extensible
Pointers

Faster Recursion

Fig. 2.2: C Language Features

(1) C is a Case Sensitive Language: Case sensitivity indicates that it differtiates the
characters either upper case or lower case based on their ASCII value.
(2) C is Mother of all Languages: C is mother of all languages because from C language
BASIC language is invented and from BASIC language Visual Basic and VB. Net
languages are invented. From C language C++, VC++, C#, J#, JAVA languages are
invented.
(3) Portable: C is highly portable this means that programs once written can be run on
another machines with little or no modification. if we write C program in turbo C we
can run same program in Borland or ANSI C without any modification on windows
platform as well as we can Run on gcc complier on Linux Platform.
(4) C is a Structured Programming Language: C is a structured programming language
since it follows fixed structure for writing any program, which should have compulsory
main() function in the structure.

CU IDOL SELF LEARNING MATERIAL (SLM)


Fundamentals of C 33

(5) Modularity in structured programming refers to the breakdown of large C Language


into small modules hence due to modularity complication can be reduced and debugging
is fast.
(6) C is a Middle Level Language: C is also used to do low level programming. It is
used to develop system applications such as kernel, driver, etc. It also supports the
feature of high level language. That is why it is known as mid-level language.
(7) C has Inbuilt Library Functions: C has inbuilt Library functions and packages bundled
into header files, Programs written in C are efficient and fast. This is due to its variety
of data type and powerful operators.
(8) C allows Us to Create User Defined Functions: Apart from using inbuilt functions, C
allows us to create your own defined functions depends on requirement.
(9) C has its own Compiler: The C compiler combines the capabilities of an assembly
language with features of a high-level language.
(10) C is Used for Creating Powerful System Programs, since with the help of C
programming system, programs and kernel coding for Linux operating system can be
written.
(11) C is a Flexible and Powerful Language.
(12) C has 32 Keywords or Reserved Words which are identifiers reserved only for C
language and cannot used for variable declaration and function declaration.
(13) C supports Graphics.
(14) Robust Language: It is a robust language with rich set of built-in functions and operators
that can be used to write any complex program.
(15) Memory Management: It supports the feature of dynamic memory allocation. In C
language, we can free the allocated memory at any time by calling the free() function.
(16) Pointer: C provides the feature of pointers. We can directly interact with the memory
by using the pointers. We can use pointers for memory, structures, functions, array,
etc. C supports different functions, structures, arrays with powerful data structures like
Stack, Linked list, Queue, Trees.

CU IDOL SELF LEARNING MATERIAL (SLM)


34 Computer Programming

(17) Efficient and Fast: Programs written in C are efficient and fast. This is due to its
variety of data type and powerful operators.
(18) Extensible: In C language, new features can be added by the programmer, hence it is
extensible.
(19) Recursion: In C, we can call the function within the function. It provides code
reusability for every function.
The C programming language is used for developing system applications that forms a major
portion of operating systems such as Windows, UNIX and Linux. Below are some examples of C
being used.
 Database systems
 Graphics packages
 Word processors
 Spreadsheets
 Operating system development
 Compilers and assemblers
 Network drivers
 Interpreters

2.3 Structure of C Program

Structure of the Program


Every C program follows the structure of Program

Documentation Section/Comment section


Definition section
Link Section/Include Section
Global Declaration
void main( ) function section
{

CU IDOL SELF LEARNING MATERIAL (SLM)


Fundamentals of C 35

Local declaration part


funaction call statemenr;
Executable part
}
returntype functionname( parameters list with data type)
{
Local declaration of variables;
function statements;
return statement;
}
1. The documentation section consists of only comments.
This section is also called the comment section, It is not compiled by the compiler, It is
a user section.
Use of comments
The Single line comment can be written by // (double slash) and
Multi line comment
comment can be written by
/* ———
—————— */
Comments (remarks) may appear anywhere within a program, as long as they are placed
within the delimiters /* and */ (e.g., /* this is a comment */). Such comments are helpful
in identifying the program’s principal features or in explaining the underlying logic of
various program features.
2. Definition Section: All the symbolic constants are written in definition section. Macros
are known as symbolic constants.
3. The Link section provides instruction to the compiler to take function from system
library. E.g., To use the input and output functions we use #include<stdio.h>, this is a
link file, Please note that the character (#) should be in the first column and there is no
semicolon at the end of this line.

CU IDOL SELF LEARNING MATERIAL (SLM)


36 Computer Programming

4. In the Global Declaration section the variable used in more than one function can be
declared in Global section. Functions can be declared in this section.
5. Every C program consist of one or more function, one of which must be called the
main( ) function. The program will always begin by executing the main( ) function,
which may access other functions. Any other function definitions must be defined
separately, either ahead of or after main( ) function.

Each function must contain:


1. A function heading, which consists of the function name, followed by an optional list of
arguments, enclosed in parentheses.
A function header must contain returntype function_name and its arguments. For
example:
void sum(int a, int b) is the function header
2. A list of argument declarations, if arguments are included in the heading.
3. A function body, which comprises the remainder of the function.
The arguments are symbols that represent information being passed between the function
and other parts of the program. (Arguments are also referred to as parameters.)
Each function body is enclosed within a pair of braces, i.e., { }. The braces may
contain one or more elementary statements (called expression statements) and other
function body.
Each expression statement must end with a semicolon (;).
The C program may contain one or more sections
Both the parts must be placed between opening and closing braces. The program
execution begins with the opening braces of main( ) function. Thus the closing brace of
main( ) function is the logical end of the program.

Rules for Writing the Program


1. Every function in a program has a unique name and is designed to perform a specific
task. The task is defined by a group of instruction.
2. main() function is always the first function which is called when a program execution
begins.

CU IDOL SELF LEARNING MATERIAL (SLM)


Fundamentals of C 37

3. Each instruction in a function is written as a separate statement.


4. The statements within a function, i.e., function body should be enclosed within a pair of
braces { }. The closing brace of the main( ) function signals the end of the program.
5. All C statements are terminated by semicolon ( ; )
6. No blank spaces are allowed within a word. However, two words may be separated by
blank spaces to improve the readability of the statement.

A Simple Program for printing message


#include<stdio.h>
void main()
{
printf(“Programming is fun.”) ;
}

Output:
Programming is fun.

Working Methology of ‘C’:


Source Code Object Code Linked Code
.C .Obj .Exe

2.4 Comments
Comments are user defined help can be written anywhere in the program. Comments can be
written in documentation section. Comment section is not Executable by the compiler.
It is comment section, comments can be Single line comment or Multiline comment
The Single line comment can be written by // (double slash)
Example of Single Line Comment
// program to print hello
Example of Multiline comment
comment can be written by

CU IDOL SELF LEARNING MATERIAL (SLM)


38 Computer Programming

/* ———
—————— */

2.5 Header Files and Body

1. Link Section/Include Section


File Inclusion: #include
The second preprocessor directive causes one file to be included in another. The preprocessor
command for file inclusion looks like this:
#include <file_name>
The source code of the file “file_name” is included in the main( ) function C program where
“#include <file_name>” is mentioned. Of course this assuming that the file being included is existing.
This directive is normally used for very large programs which can be divided into several
different files each containing related functions. These files are #include at the beginning of main()
function program file. Secondly, the commonly needed functions and macro definitions can be
stored in a file, and that file can be included in every program later.
The prototypes of all the library functions are grouped into different categories and then
stored in different header files. For example prototypes of all mathematics related functions are
stored in the header file ‘math.h’ which can be included as shown below:
#include<math.h>
The #include directive can be used in two ways as discussed below:
#include “filename”
#include <filename>
#include “sum.c”
#include “c:\employee.c”
It is Link section also called as include section, this section is prefixed by # sign
# include<stdio.h>
# include<conio.h>

CU IDOL SELF LEARNING MATERIAL (SLM)


Fundamentals of C 39

# include<math.h>
#include<stdlib.h>
# is preprocessor directive which gives direction to the compiler that include specified header
file from Library to main( ) function program.
Header File Description
#include<stdio.h> It is standard input output header files, consist of standard input function
scanf() and standard output function printf()
#include<conio.h> It is console input output header file, consist of clrscr() function to clear
screen and getch() function to get character to see the output on screen.
#include<math.h> It is Math Medical Header File consist of all mathematical functions,
sin( ), cos( ), tan( ), sqrt( ).
#include<stdlib.h It is Standard Library File consist of Exit( ) function
#include<string.h> It is String Header File consist of string functions, strcmp( ), strlen( ),
strcpy( ), strrev( ), strcat( ).
#include<Ctype.h> All character handling functions are defined in this header file.functionsIt
consist of islower( ), isupper( ), isdigit( )

2.6 Data Types


C supports several different types of data, each of which may be represented differently within
the computer’s memory.
 C data types are defined as the data storage format that a variable can store a data to
perform a specific operation.
 Data types are used to define a variable before to use in a program.
 Size of variable, constant and array are determined by data types.

CU IDOL SELF LEARNING MATERIAL (SLM)


40 Computer Programming

The basic data types are listed below.

Data Types
Inbuilt Data Types User Defined Data Types

Primitive Non Primitive

Numeric Structure

integer floating point


Arrays
byte short double float

int long

non-numeric Union

character boolean

Fig. 2.3: The Basic Data Types


Built-in-type
1. Integer type: The data types in this type are int and char. The modifiers signed, unsigned,
long and short may be applied to character and integer basic data type.
The size of int is 2 bytes and the size of char is 1 byte.
Example: int a=10;
2. Floating Type: The data type in this can be float or double. The size of the float is 4
bytes and size of double is 8 bytes. It is used to store the numbers with decimal. The
modifier long can be applied to double and the size of long double is 10 bytes.
Example: float per=95.3;
 float data type supports single precision numbers.
 double data type supports double precision numbers and having size greater than
float.
 long double can store double precision numbers and having size greater than double.

CU IDOL SELF LEARNING MATERIAL (SLM)


Fundamentals of C 41

3. char – characters stored like type char, It stores single character, Sixe is 1 byte.
4. void: void is used for:
 To specify the return type of a function when it is not returning any value.
 To indicate an empty argument list to a function

Table 2.1: List of All Datatype in C programming language

Data Type Format Specifier Size Data Range


char %c 1 Byte -128 to +127
unsigned char %c 8 Byte 0 to 255
int %d 2 Byte -32768 to +32767
long int %ld 4 Byte -231 to +2 31
unsigned int %u 2 Byte 0 to 65535
float %f 4 Byte -3.4e38 to +3.4e38
double %lf 8 Byte -1.7e38 to +1.7e38
long double %Lf 12-16 Byte -3.4e38 to +3.4e38

2.7 Constants
Constants refer to fixed values that the program may not alter during its execution. These
fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a
character constant, or a string literal.
There are enumeration constants as well. Constants are treated just like regular variables
except that their values cannot be modified after their definition.
You use a named constant when you want to assign a useful name for a value that will never
be changed during a program’s execution.
There are two simple ways in C to define constants:
 Using #define preprocessor
 Using const keyword

CU IDOL SELF LEARNING MATERIAL (SLM)


42 Computer Programming

The #define Preprocessor


Given below is the form to use #define preprocessor to define a constant:
#define identifier value
#define WIDTH 10

The Constant Keyword


You can use const prefix to declare constants with a specific type as follows:
const type variable = value;
constint WIDTH = 10;

Constants

Numeric Character
Constants Constants

Single
Integer Real String
Character
Constants Constants Constants Constants

e.g. e.g. “Hello”,


e.g. 123,-123,0 0.0083,0.95 e.g. ‘5’,’x’,’a’
“1+2+3+4+5...”

Fig. 2.4: The Constant Keyword

Integer Constants
An integer constant is an integer quantity which contains a sequence of digits. It should not
have a decimal point. Blanks and commas are not allowed within an integer constant. An integer
constant can be either +ve or -ve. The constant must lie within the range of the declared data type
(including qualifiers long, short, etc.).
Example of valid integer constants: 976 8987 5 -25 etc.
Example of invalid integer constants: 78.43 7-8 89,76 etc.

CU IDOL SELF LEARNING MATERIAL (SLM)


Fundamentals of C 43

An integer constant can be either Decimal, Hexa Decimal or Octal. See the table below to
understand how these three different constants are defined in C.

Floating Point Constants


They are also known as real constants. A real constant contains a decimal point or an exponent.
It can be either +ve or -ve. Commas and blank space are not allowed within a real constant.
Examples: 254.175, -16.47 -0.5e-7 +4.1e8

Character Constant
A character constant is a character which is enclosed in single quotes. A character constant is
of size 1 byte and can contain only 1 character. A character can be an alphabet like a,b,A,C etc or a
special character like &,^, $, #,@ etc or a single digit from 0 through 9. It can also be an escape
sequence character like space ‘ ‘ or a null character ‘\o’ or a new line ‘\n’ etc.
Example: ‘A’ ‘a’ ‘b’ ‘8’ ‘#’ etc.
Each character has a corresponding ASCII value. ASCII value is the numeric code of a
particular character and is stored inside the machine’s character set.

Example: A sample program of printing ASCII value of a character can be included.


#include<stdio.h>
int main()
{
char ch;
printf(“Enter any character:”);
scanf(“%c”, &ch);
printf(“ASCII value is %d”, ch);
return 0;
}

String Constants
(a) A string constant is a collection of characters enclosed in double quotations “ “
(b) It may contain alphabets, digits, special characters and blank space.

CU IDOL SELF LEARNING MATERIAL (SLM)


44 Computer Programming

Symbolic Constants
A symbolic constant is a name that substitutes for a sequence of characters. The characters
may represent a numeric constant, a character constant or a string constant. Thus, a symbolic constant
allows a name to appear in place of a numeric constant, a character constant or a string.
When a program is compiled, each occurrence of a symbolic constant is replaced by its
corresponding character sequence. Symbolic constants are usually defined at the beginning of a
program.
The symbolic constants may then appear later in the program in place of the numeric constants,
character constants, etc. that the symbolic constants represent. A symbolic constant is defined by
writing
#define name text
where name represents a symbolic name, typically written in uppercase letters, and text represents
the sequence of characters that is associated with the symbolic name.
Since a symbolic constant definition is not a true C statement, text does not end with a
semicolon. Moreover, if text were to end with a semicolon, this semicolon would be treated as
though it were a part of the numeric constant, character constant or string constant that is substituted
for the symbolic name.
Preprocessor is also called Macro Definition.
# define max 100
Hence # is a preprocessor directive which directs to the compiler that identifier max as a
token replaced with the string 100.
Hence in the program each occurrence of max is automatically replaced by 100.

Examples:
# define true 1
# define false 0
# define EoF – 1
# define product (x, y) ((x) * (y))

CU IDOL SELF LEARNING MATERIAL (SLM)


Fundamentals of C 45

2.8 Format specifiers with scanf() and printf()


The format string can contain format specifiers like scanf().
%dstands for integer numbers
%c stands for character
%f stands for float
%s stands for string
%o stands for octal
%x stands for hexadecimal

printf Function
The printf function writes data to standard output (usually, the terminal).
printf( ) function is available in stdio.h (standard input output header file)
Syntax of print() function:
printf(control_string,arg1,arg2,arg3,..., argn);
where control_string refers to a character string containing formatting information, and arg1, arg2,
etc., are arguments that represent the individual output data items.
The purpose of printf() is to display messages and values on the standard output using format
specifiers.
The general format of printf() is
(1) printf(<msg>); only for displaying the message.
(2) printf(<format string>, arguments); only for displaying the value of argument or variable
(3) printf(<format string><msg>,arguments)Displaying the message along with the value
of argument or variable.
Always the format string is defined within the ” ” ( double quotes)

Example 1:
printf(“Welcome to C programming”);
Will display

CU IDOL SELF LEARNING MATERIAL (SLM)


46 Computer Programming

Welcome to C programming
printf() does not automatically print a new line. The programmer has to explicitly do it, by including
the \n in the format string.

scanf Function
The scanf function reads data from standard input (usually, the terminal).
scanf( ) function is available in stdio.h (standard input output header file)
For inputting values to your program you can either use getchar() or scanf(). The getchar()
returns a single character from a standard input device, the function does not require any argument
and it is restricted in the sense that only one character can be read-in at a time and no float/string
values can be read and the scanf() function allows more flexible input.
Syntax of scanf() is:
scanf(control_string, arg1, arg2, arg3, ..., argn);
where control_string refers to a character string containing certain required formatting information,
and arg1, arg2, etc., are arguments that represent the individual input data items.

Example:
scanf(”%d”, &n);
where the variable n has been declared as an integer.
The & is mandatory and stands for “address of”.
scanf(”%d %d”, &a, &b);
where a,b are integers.

2.9 Variables
Variable is a place holder which occupies memory space to store variable value, or a constant
value, integer, float, character, string value.
In C, all variables must be declared before they are used in executable statements.
In C language all variables are to be declared first in local declaration section, i.e., at the
beginning of scope.

CU IDOL SELF LEARNING MATERIAL (SLM)


Fundamentals of C 47

float per = 92.8;


Here, per is a variable of integer type. The variable is holding 92.8 in the above code.
The value of a variable can be changed, hence the name ‘variable’.
The variable/Identifier name follows following rules:
1. The variable name should always start from any alphabet a – z.
2. The variable name is a combination of alphabets, numbers and underscores.
3. The variable name cannot start with a digit.
4. No special symbol other than underscore can be used in variable name.
5. Variables are case sensitive.
6. No special symbols are allowed other than underscore.
7. Reserved keywords that are not allowed as variable names because they are part of the
language’s syntax.
C is a strongly typed language. What this means it that, the type of a variable cannot be
changed. Suppose, you declared an integer type variable. You cannot store character or a decimal
number in that variable.

Variable Definition
Declaring and Initializing C Variable:
 Variables should be declared in the C program before to use.
 Memory space is not allocated for a variable while declaration. It happens only on
variable definition.
 Variable initialization means assigning a value to the variable.

CU IDOL SELF LEARNING MATERIAL (SLM)


48 Computer Programming

Fig. 2.5: Variable and Constants

Table 2.2: Variable Syntax

Sr. No. Type Syntax Example


1 Variable declaration Data_typevariable_name; Int x, y, z; char flat, ch;
2 Variable initialization Data_typevariable_name = value; Int x = 50, y = 30;
char flag = ‘x’, ch = ‘1’;

Scope of Variables in C Program are:


1. Local variable
2. Global variable

1. Local Variable in C:
 The scope of local variables will be within the function only.
 These variables are declared within the function and can’t be accessed outside the
function.

2. Global Variable in C:
 The scope of global variables will be throughout the program. These variables can be
accessed from anywhere in the program.
 This variable is defined outside the main function. So that, this variable is visible to
main function and all other sub-functions.

Storage classes
 Every variable in C programming has two properties: type and storage class.
 Type refers to the data type of a variable. And, storage class determines the scope and
lifetime of a variable.

CU IDOL SELF LEARNING MATERIAL (SLM)


Fundamentals of C 49

 Every time a variable is defined, its type is mentioned. Along with it, its ‘storage class’
is also required. In other words, not only do all variables have a data type, they also
have a ‘storage class’, i.e., Scope.
 Most of the variables defined have only data type and a default storage class is used. If
the storage class of a variable is not specified in its declaration, the compiler will assume
a storage class depending on the context in which the variable is used.
 In C programming language, a variable name identifies some physical location within
the computer where the variable’s value is stored.
 There are basically two kinds of locations in a computer — Memory and CPU registers.
It is the variable’s storage class that determines in which of these two locations the
value is stored.
The storage class of a variable also signifies:
(a) Where it will be stored.
(b) What will be the initial value; default value
(c) What is the scope; availability
(d) What is the life, i.e., how long would the variable exist.
There are 4 types of storage class:
1. Automatic storage class (Local)
2. External storage class (Global)
2. Static storage class
4. Register storage class

1. Automatic (Local Variable)


The variables declared inside the function are automatic or local variables. The local variables
exist only inside the function in which it is declared. When the function exits, the local variables
are destroyed. This is the default storage class for all local variables.
A variable defined with automatic storage class are stored in memory and often initialized
with garbage (random) value.

CU IDOL SELF LEARNING MATERIAL (SLM)


50 Computer Programming

The scope and life of the variable is local to the block it’s defined. The moment the control
comes out of the block in which the variable is defined, the variable and its value is forever lost.

Syntax:
int main()
{
int n; // n is a local varible to main() function
... .. ...
}
void func()
{
int n1; // n1 is local to func() fucntion
}

Example:
void main()
{
int var1; //default storage class : auto
auto int var2; //storage class explicitly mentioned
printf(“\n %d %d”, var1, var2);
}
In the above example, both the variables are defined with the same storage class. Storage
class for var1 is not mentioned and so its initialized with default, i.e., auto. ‘auto’ can only be used
within functions, i.e., local variables.
Output of the above program is:
1258 1547
Their garbage values, as the variable were not initialized. So always make it a point that you
initialize the automatic variables properly, otherwise you are likely to get unexpected results.

CU IDOL SELF LEARNING MATERIAL (SLM)


Fundamentals of C 51

2. Extern (Global Variable)


Variables that are declared outside of all functions are known as external variables. External
or global variables are accessible to any function.
A variable defined to have external storage class is stored in memory and initialized to a
default value zero. Variables of this storage class are also called “Global variables”. External
variables are declared outside all functions, yet are available to all functions that care to use them.
Generally, External variables are declared again in the function using keyword extern.
In the explicit declaration of variable ‘extern’ keyword is used.

Example #1 : External Variable


#include <stdio.h>
void display();
int n = 5; // global variable
int main()
{
++n; // variable n is not declared in the main() function
display();
return 0;
}
void display()
{
++n; // variable n is not declared in the display() function
printf(“n = %d”, n);
}

Output:
n=7
Suppose, a global variable is declared in file1. If you try to use that variable in a different
file file2, the compiler will complain. To solve this problem, keyword extern is  used  in file2 to
indicate that the external variable is declared in another file.

CU IDOL SELF LEARNING MATERIAL (SLM)


52 Computer Programming

Example #2 : External Variable


int x = 30; // variable definition
void showx(void);
void main()
{
extern int x; //explicit declaration
printf(“\n %d”, x++);
showx();
}
void showx()
{
extern int x; //explicit declaration
printf(“\n %d”, x);
}

Output of the program is:


30
31
As seen in the output, the variable x, defined as global, has its value accessible in main() and
showx() methods. The value of x is incremented in the main method and its value retains even
outside the scope of main method when the showx() method is called and the incremented value is
printed.

3. Static Variable
A static variable is declared by using keyword static. A variable defined to have static storage
class is stored in memory and initialized to a default value zero. The static storage class instructs
the compiler to keep a local variable in existence during the lifetime of the program instead of
creating and destroying it each time it comes into and goes out of scope. Therefore, making local
variables static allows them to maintain their values between function calls. The static modifier

CU IDOL SELF LEARNING MATERIAL (SLM)


Fundamentals of C 53

may also be applied to global variables. When this is done, it causes that variable’s scope to be
restricted to the file in which it is declared.

Syntax:
static int i;
The value of a static variable persists until the end of the program.

Example #1: Static Variable


#include <stdio.h>
void display();
int main()
{
display();
display();
}
void display()
{
static int c = 0;
printf(“%d “,c);
c += 5;
}

Output:
0
5
During the first function call, the value of c is equal to 0. Then, its value is increased by 5.
During the second function call, variable c is not initialized to 0 again. It’s because c is a
static variable. So, 5 is displayed on the screen.

CU IDOL SELF LEARNING MATERIAL (SLM)


54 Computer Programming

Example #2: Static Variable


//function prototype
void call_me(void);
void main()
{
Call_me();
Call_me();
Call_me();
Call_me();
}
void call_me()
{
static int i=5;
printf(“\n %d”, i++);
}

Output of the above program is:


5
6
7
8
Here the static variable i is initialized with 5 only once. It is never initialized again. During
the first call to Call_me( ), i is incremented to 6. Because i is static, this value persists. The next
time Call_me( ) is called, i is not re-initialized to 1; on the contrary its old value 6 is still available.
This current value of i (i.e., 6) gets printed and then i++ increments i to get a value of 7. When
Call_me( ) is called the third time, the current value of i (i.e., 7) gets printed and once again i is
incremented. In short, if the storage class is static then the statement static int i = 5 is executed
only once, irrespective of how many times the same function is called.

CU IDOL SELF LEARNING MATERIAL (SLM)


Fundamentals of C 55

4. Register Variable
The register keyword is used to declare register variables. Register variables were supposed
to be faster than local variables. Local variable defined using register storage class is stored in CPU
registers instead of memory. They are by default initialized to garbage value. This means that the
variable has a maximum size equal to the register size (usually one word) and can’t have the unary
‘&’ operator applied to it (as it does not have a memory location). The scope and life of the variable
is same as auto variables, i.e., is local to the block it’s defined.
Why would a variable be defined with this storage class? The answer is to have quick access.
For example, the counter variables may be defined with register storage class. It should also be
noted that defining ‘register’ does not mean that the variable will be stored in a register. It means
that it might be stored in a register depending on hardware and implementation restrictions like
number of free registers.
void main()
{
register int i;
for(i=0;i<3;i++)
printf(“\n %d”, i);
}
Not every type of variable can be stored in a CPU register. For example, if the microprocessor
has 16-bit register then they cannot hold float and double variables which require 4 or 8 bytes
respectively. In this case the compiler would treat the variable as auto storage class.
However, modern compilers are very good at code optimization and there is a rare chance that
using register variables will make your program faster. Unless you are working on embedded system
where you know how to optimize code for the given application, there is no use of register variables.

CU IDOL SELF LEARNING MATERIAL (SLM)


56 Computer Programming

Table 2.3: CPU Register

Category Automatic Register Static External


Storage Memory CPU Register Memory Memory
Initial Value Garbage Garbage Zero Zero
Life Within Block Within Block Outside Block but active Outside Block and also
only in the file declared active in multiple files
Scope Local Local Local Global

2.10 Summary
C programming is a general-purpose, procedural, imperative computer programming language
developed in 1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the UNIX
operating system. C is the most widely used computer language. It keeps fluctuating at number one
scale of popularity along with Java programming language, which is also equally popular and most
widely used among modern software programmers.

Key advantages of learning C Programming:


 Easy to learn
 Structured language
 It produces efficient programs
 It can handle low-level activities
 It can be compiled on a variety of computer platforms

Features of C Language:
1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. Structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed

CU IDOL SELF LEARNING MATERIAL (SLM)


Fundamentals of C 57

8. Pointers
9. Recursion
10. Extensible

Every C program follows the structure of Program

Documentation Section/Comment section


Definition section
Link Section/Include Section
Global Declaration
void main( ) function section
{
Local declaration part
Executable part
}

Datatypes in C
Data types specify how we enter data into our programs and what type of data we enter. C
language has some predefined set of data types to handle various kinds of data that we can use in
our program. These datatypes have different storage capacities.
C language supports 2 different type of data types:
1. Primary data types:
These are fundamental data types in C namely integer(int), floating point(float),
character(char) and void.
2. Derived data types:
Derived data types are nothing but primary datatypes but a little twisted or grouped
together like array, stucture, union and pointer.
Data type determines the type of data a variable will hold. If a variable x is declared as int. it
means x can hold only integer values. Every variable which is used in the program must be declared
as what data-type it is.

CU IDOL SELF LEARNING MATERIAL (SLM)


58 Computer Programming

2.11 Key Words/Abbreviations

Execution Flow
1. C program (source code) is sent to preprocessor first. The preprocessor is responsible
to convert preprocessor directives into their respective values. The preprocessor generates
an expanded source code.
2. Expanded source code is sent to compiler which compiles the code and converts it
into assembly code.
3. The assembly code is sent to assembler which assembles the code and converts it into
object code. Now a simple.obj file is generated.
4. The object code is sent to linker which links it to the library such as header files. Then
it is converted into executable code. A simple.exe file is generated.
5. The executable code is sent to loader which loads it into memory and then it is executed.
After execution, output is sent to console.

2.12 Learning Activity


1. What are the rules for writing any program.
.......................................................................................
.......................................................................................
2. Write a program in C to print “HELLO WORLD”.
......................................................................................
.......................................................................................

2.13 Unit End Questions (MCQ and Descriptive)

A. Descriptive Type: Short Answer Type Questions


1. Explain structure of C program in detail with neat diagram.
2. What are the major components of a C program? What significance is attached to the
name
main( ) function?

CU IDOL SELF LEARNING MATERIAL (SLM)


Fundamentals of C 59

3. Explain header section of C program.


4. Explain body section of C program.
5. Explain use of #define section.
6. Explain use of #include section and state which header files can be included.
7. Explain category of different Header Files.
8. Name and describe the four basic data types in C.
9. Write a short note on Use of Comments in C program and state what are different ways
to write comments.
10. Explain data types and constants.
11. Explain constants and types of constants.
12. What is a variable? How can variables be characterized?
13. What is a symbolic constant? How is a symbolic constant defined?
14. Differentiate constants and variables.

B. Multiple Choice/Objective Type Questions


1.  All keywords in C are in ____________.
(a) LowerCase letters (b) UpperCase letters
(c) CamelCase letters (d) None of the mentioned
2. Which of the following is not a valid variable name declaration?
(a) float PI = 3.14; (b) double PI = 3.14;
(c) int PI = 3.14; (d) #define PI 3.14
3. Which is the only function all C programs must contain?
(a) start() (b) main()
(c) getch() (d) printf()
4. What number should be the shown on the screenafter the following statements of C are
executed?
char ch;
int i;

CU IDOL SELF LEARNING MATERIAL (SLM)


60 Computer Programming

ch=’G’;
i=ch=’A’;
printf(“%d”,i);
(a) 5 (b) 7n
(c) 8 (d) 6
Answers : 1. (a), 2. (d), 3. (b), 4. (d)

2.14 References
1. https://www.studytonight.com/c/datatype-in-c.php
2. https://www.programiz.com/c-programming
3. https://www.tutorialspoint.com/cprogramming/c_data_types.htm
4. http://www-personal.acfr.usyd.edu.au/tbailey/ctext/ctext.pdf
5. http://www.vssut.ac.in/lecture_notes/lecture1424354156.pdf



CU IDOL SELF LEARNING MATERIAL (SLM)


Operators and Expressions 61

UNIT 3 OPERATORS AND EXPRESSIONS

Structure:
3.0 Learning Objectives
3.1 Introduction
3.2 Arithmetic Operators
3.3 Relational Operators
3.4 Logical Operators
3.5 Assignment and Compound Assignment Operators
3.6 Unary Operators and Increment and Decrement Operator
3.7 Conditional Operator or Ternary Operator
3.8 Bitwise and Comma Operator
3.9 Expressions and Evaluation of Expression
3.10 Type Conversion
3.11 Precedence and Associatively (Order of Evaluation)
3.12 I/O Functions: printf( ), scanf( )
3.13 Summary
3.14 Key Words/Abbreviations
3.15 Learning Activity
3.16 Unit End Questions (MCQ and Descriptive)
3.17 References

CU IDOL SELF LEARNING MATERIAL (SLM)


62 Computer Programming

3.0 Learning Objectives


After studying this unit, you will be able to:
 Describe different types of C operators
 Solve expressions having different operators
 Change the type of given data and variable
 Explain operator precedence and associativity
 Discuss I/O functions

3.1 Introduction
An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions.Operators, functions, constants and variables are combined together to form expressions.
Here you will learn about Operators in C Programming (all valid operator’s available in C),
expressions (combination of operators, variables and constants) and precedence of operators (which
operator has higher priority and which operator has lower priority).

3.2 Arithmetic Operators


The operators used to perform arithmetic operations such as addition (+), subtraction (–),
multiplication (*), division (/) are called arithmetic operators. These basic operators are known as
binary operators as they require two variables to be evaluated.

Table 3.1: Arithmetic Operators

Sr. No. Operator Meaning


(1) + Addition or unary plus
(2) – Subtraction or unary minus
(3) * Multiplication
(4) / Division
(5) % Modulo division (Reminder of an Integer division)

The variables or constants on which operators are operated are known as operands. The
arithmetic in C can be of three types:

CU IDOL SELF LEARNING MATERIAL (SLM)


Operators and Expressions 63

(a) Integer Arithmetic.


(b) Real Arithmetic.
(c) Mixed Mode Arithmetic.
(a) Integer Arithmetic: When both the operands are integers, the operation is called integer
arithmetic.
For example:
55 – 5 = 50
55 + 5 = 60
14 * 2 = 28
14/2 = 7 (Decimal part truncated integer division)
14% 2 = 0 (Remainder of division)
– 14 % 3 = – 2
14 % 3 = 2
6/7 = 0
(b) Real Arithmetic: An arithmetic operation involving only real operands is called real
arithmetic. A real operand may assume values either in fractional or exponential form.
For e.g.,
1.5 – 0.7 = 0.8
1.5 + 0.7 = 2.2
1.5 * 2.0 = 3.0
6.0/7.0 = 0.857143
1.0/3.0 = 0.3333
– 2.0/3.0 = – 0.666667
% (modulo operator) cannot be used with Real numbers
x_int/y_int = result_int
x_int/y_float = result_float

CU IDOL SELF LEARNING MATERIAL (SLM)


64 Computer Programming

x_float/y_int = result_float
x_float/y_float = result_float
(c) Mixed Mode Arithmetic: C++ permits us to mix integer operand with real operand.
When one operand is real and the other is integer, the expression is called mixed mode
arithmetic expression, i.e., if either of the operand is of the real type, then only real
operation is performed and result is always a real number.
For e.g.,
15/10.0 = 1.5
4 + 3.5 = 7.5

Example of Arithmetic Operators


// C Program to demonstrate the working of arithmetic operators
#include <stdio.h>
void main()
{
int a = 9,b = 4, c;
c = a+b;
printf(“a+b = %d \n”,c);

c = a-b;
printf(“a-b = %d \n”,c);
c = a*b;
printf(“a*b = %d \n”,c);
c=a/b;
printf(“a/b = %d \n”,c);
c=a%b;
printf(“Remainder when a divided by b = %d \n”,c );
getch();
}

CU IDOL SELF LEARNING MATERIAL (SLM)


Operators and Expressions 65

Output:
a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1
The operators +, - and * computes addition, subtraction and multiplication respectively as
expected.
In normal calculation, 9/4 = 2.25. However, the output is 2 in the program.
It is because both variables a and b are integers. Hence, the output is also an integer. The
compiler neglects the term after decimal point and shows answer 2 instead of 2.25.
The modulo operator % computes the remainder. When a = 9 is divided by b = 4, the remainder
is 1. The % operator can only be used with integers.
Suppose a = 5.0, b = 2.0, c = 5 and d = 2. Then in C programming,
a/b = 2.5 // Because both operands are floating-point variables
a/d = 2.5 // Because one operand is floating-point variable
c/b = 2.5 // Because one operand is floating-point variable
c/d = 2 // Because both operands are integers

3.3 Relational Operators


Relational Operators: With the help of relational operators we can take a decision by
comparing two or more operands values.
Relational operators compare values to see if they are equal or if one of them is greater than
the other and so on.
Operator Meaning
< is less than
<= is less than equal to
> is greater than
>= is greater than equal to

CU IDOL SELF LEARNING MATERIAL (SLM)


66 Computer Programming

expression1 relational_operator expression2

Expression Result
3>4 false
6<=2 false
10 > – 32 True
(23 * 7) > = (–67 + 89) True

The relational operators are self-explanatory. As far as the explanation of the logical operators
is concerned. Consider the following. Any operator which uses two characters as a symbol should
have no space between the two characters, that is ==, It will erroneous if it is written as = =.
A relational operator checks the relationship between two operands. If the relation is true, it
returns 1 if the relation is false, it returns value 0.
Operator Meaning of Operator Example
== Equal to 5 == 3 returns 0
> Greater than 5 > 3 returns 1
< Less than 5 < 3 returns 0
!= Not equal to 5 != 3 returns 1
>= Greater than or equal to 5 >= 3 returns 1
<= Less than or equal to 5 <= 3 return 0

3.4 Logical Operators


Logical Operators: The logical operators are those which are used to perform logical
expression such as logical AND, logical OR and logical NOT.
The logical AND and logical OR operators are used when we want to test for more than one
condition and make decision.

C Logical Operators with Example


Operator Meaning of Operator Example
&& Logial AND. True only if all operands If c = 5 and d = 2 then, expression ((c == 5)
are true && (d > 5)) equals to 0.
|| Logical OR. True only if either one If c = 5 and d = 2 then, expression ((c == 5)
operand is true || (d > 5)) equals to 1.
! Logical NOT. True only if the operand is 0 If c = 5 then, expression ! (c == 5) equals
to 0.

CU IDOL SELF LEARNING MATERIAL (SLM)


Operators and Expressions 67

The && (AND) operator


1. Evaluates true when both the relational expressions are true.
2. Evaluates false when any one of the relational expressions is false.
The following truth table will be useful to understand more clearly
Logical AND indicates that compound expression is true when two conditions or expressions
are true.
Situation Result
true && true true
true && false false
false && true false
false && false false

The || (OR) operator


Logical OR indicates the Results is true if any or all inputs are true.
1. Evaluates true when any one the relational expression is true
2. Evaluates false when both the relational expressions is false.
expression1 || expression2
Situation Result
true || true true
true || false true
false || true true
false || false false

(a < b) || (b > c)

true || false
true
Logical Negation Operator (!): A logical expression can be changed from false to true or
from true to false with negation operator (!)

CU IDOL SELF LEARNING MATERIAL (SLM)


68 Computer Programming

Situation Result
! (true) false
! (false) true

3.5 Assignment and Compound Assignment Operators

Assignment Operator
Assignment operators are used to assign the result of an expression or constant to variable.
The assignment operators can be used within any valid expression, the usual assignment
operator is ‘=’.
variable_Name = constant or expression;
The arithmetic expression is a combination of variables, constants and operators
E.g., x = a + b;
z = 0;
final = 100;
During the assignment operator the value of expression of right hand side is assigned to left
side variable.
During the assignment operator the value of the expression on right hand side is computed
and is assigned to the variable on the left hand side.

Compound Assignment OR Short Hand Assignment Operators:


The compound assignment operators enable you to abbreviate assignment statements. For
example, the statement
value = value + 3
which mentions the variable value on both sides of the assignment, can be abbreviated with
the addition assignment operator, += as

value += 3

The += operator adds the value of the right operand to the value of the left operand and stores
the result in the left operand’s variable.

CU IDOL SELF LEARNING MATERIAL (SLM)


Operators and Expressions 69

In addition to the usual assignment operator ‘=’. C++ has short hand assignment operators of
the form.
variable op = expression;
where op is C language is binary arithmetic operator
Compound assignment operator Sample expression Explanation Assigns
Assume: c = 4, d = “He”
+= c += 7 c= c+ 7 11 to c
-= c -= 3 c= c-3 1 to c
*= c *= 4 c=c*4 16 to c
/= c /= 2 c=c/2 2 to c
\= c \= 3 c= c\3 1 to c
^= c ^= 2 c= c^ 2 16 to c
&= d &= “llo” d = “kiran” & “llo” “Hello” to kiran

Fig. 3.1: Compound Assignment Operators.

3.6 Unary Operators and Increment and Decrement Operator


(a) Unary Operators: The unary operators require only a single expression to produce a
line. Some unary operators may be followed by the operands such as incremental and
detrimental.
The most common unary operation is unary minus, where a minus sign precedes a
numerical constant, a variable or an expression.

Unary Arithmetic Operators


The unary operators are unary minus(-), increment operator (++) and decrement operator
(—).

Unary Minus(-)
The symbol is the same as used for binary subtraction. Unary minus is used to indicate or
change the algebraic sign of a value. For example:
a=-75;
b=-a;

CU IDOL SELF LEARNING MATERIAL (SLM)


70 Computer Programming

assign the value –75 to a and the value 75(-(-75)) to b. The minus sign used in this way is called the
unary operator because it takes just one operand.
Strictly speaking, there is no unary + in C.

Increment and Decrement Operators


Increment Operators are used to increased the value of the variable by one and Decrement
Operators are used to decrease the value of the variable by one in C programs.
Both increment and decrement operator are used on a single operand or variable, so it is
called as a unary operator. Unary operators are having higher priority than the other operators it
means unary operators are executed before other operators.

Syntax
++ // increment operator
— // decrement operator
Increment and decrement operators cannot apply on constant.
x= 4++; // gives error, because 4 is constant
C includes two useful operators, which are generally not found in other computer languages.
These are the increment operator (+ +) and the decrement operator (—). The operator ++ adds 1 to
its operand, whereas the operator – subtracts 1 from its operand.
To be precise,
x = x + 1; can be written as x++; and
x = x –1; can be written as x—;
Both these operators may either precede or follow the operand, i.e.,
x = x + 1; can be represented as
1] ++x; or x++;
The first case is known as prefix while the later one is known as postfix operator.
Similar operations hold true for – operator. Ie. 1] - –x or x - -
The difference between pre and post-fixing the operator is useful when it is used in an
expression. When the operator precedes the operand, C performs the increment or decrement

CU IDOL SELF LEARNING MATERIAL (SLM)


Operators and Expressions 71

operation before using the value of the operand. If the operator follows the operand, the value of
the operand is used before incrementing or decrementing it.

Example:
x = 1;
i = i +(+ + x);
In the above expression, the value of x, which is added to i is 2
On the other hand,
x = 1;
i = i +(x + +);
x =1 is added to i; in both the cases the value of x after evaluating the expression is 2.

Type of Increment Operator


 pre-increment
 post-increment
pre-increment (++ variable)
In pre-increment first increment the value of variable and then used inside the expression
(initialize into another variable).

Syntax
++ variable;

Example pre-increment
#include<stdio.h>
#include<conio.h>
void main()
{
int x,i;
i=10;
x=++i;

CU IDOL SELF LEARNING MATERIAL (SLM)


72 Computer Programming

printf(“x: %d”,x);
printf(“i: %d”,i);
getch();
}

Output:
x: 11
i: 11
In above program first increase the value of i and then used value of i into expression.
post-increment (variable ++)
In post-increment first value of variable is used in the expression (initialize into another variable)
and then increment the value of variable.
post-increment (variable ++)
In post-increment first value of variable is used in the expression (initialize into another variable)
and then increment the value of variable.

Syntax
variable ++;

Example post-increment
#include<stdio.h>
#include<conio.h>
void main()
{
int x,i;
i=10;
x=i++;
printf(“x: %d”,x);
printf(“i: %d”,i);

CU IDOL SELF LEARNING MATERIAL (SLM)


Operators and Expressions 73

getch();
}

Output:
x: 10
i: 11
In above program first used the value of i into expression then increase value of i by 1.

Type of Decrement Operator


 pre-decrement
 post-decrement

Pre-decrement (— variable)
In pre-decrement first decrement the value of variable and then used inside the expression
(initialize into another variable).

Syntax
— variable;

Example pre-decrement
#include<stdio.h>
#include<conio.h>
void main()
{
int x,i;
i=10;
x=—i;
printf(“x: %d”,x);
printf(“i: %d”,i);
getch();
}

CU IDOL SELF LEARNING MATERIAL (SLM)


74 Computer Programming

Output:
x: 9
i: 9
In above program first decrease the value of i and then value of i used in expression.

post-decrement (variable —)
In Post-decrement first value of variable is used in the expression (initialize into another
variable) and then decrement the value of variable.

Syntax
variable —;

Example post-decrement
#include<stdio.h>
#include<conio.h>
void main()
{
int x,i;
i=10;
x=i—;
printf(“x: %d”,x);
printf(“i: %d”,i);
getch();
}

Output:
x: 10
i: 9
In above program first used the value of x in expression then decrease value of i by 1.

CU IDOL SELF LEARNING MATERIAL (SLM)


Operators and Expressions 75

Difference Between Pre/Post Increment and Decrement Operators in C:


Below table will explain the difference between pre/post increment and decrement operators
in C programming language.
Operator Operator/Description
Pre increment operator (++i) value of i is incremented before assigning it to the variable i
Post increment operator (i++) value of i is incremented after assigning it to the variable i
Pre decrement operator (–i) value of i is decremented before assigning it to the variable i
Post decrement operator (i–) value of i is decremented after assigning it to variable i

3.7 Conditional Operator or Ternary Operator


Conditional operator (?:): C includes a very special operator called the ternary or conditional
operator. It is called ternary operator because it uses three expressions. It is short hand version of
if_else construct. A conditional operator is a ternary operator, that is, it works on 3 operands.
The format of the ternary operator is
conditionalexpression1?expression2:expression3
If expression1 evaluated is true then expression2 is evaluated otherwise expression3 is
evaluated.
The conditional operator works as follows:
 The first expression conditionalExpression is evaluated at first. This expression evaluates
to 1 if it’s and evaluates to 0 if it’s false.
 If conditionalExpression is true, expression1 is evaluated.
 If conditionalExpression is false, expression2 is evaluated.

Example:
(1) if (i % 2 = = 0)
even = true
else
even = false
even = (i % 2 = = 0)? true : false;

CU IDOL SELF LEARNING MATERIAL (SLM)


76 Computer Programming

(2) if (i > j)
max = i
else
man = j
max = (i > j)? i : j;
(3) if (x > y)
x=x+3
else
x=x–3
x = (x > y)? x + 3 : x – 3;

Example: C conditional Operator


#include <stdio.h>
void main()
{
char February;
int days;
printf(“If this year is leap year, enter 1. If not enter any integer: “);
scanf(“%c”,&February);

// If test condition (February == ‘l’) is true, days equal to 29.


// If test condition (February ==’l’) is false, days equal to 28.
days = (February == ‘1’) ? 29 : 28;

printf(“Number of days in February = %d”,days);


getch();
}

CU IDOL SELF LEARNING MATERIAL (SLM)


Operators and Expressions 77

Output:
If this year is leap year, enter 1. If not enter any integer: 1
Number of days in February = 29

3.8 Bitwise and Comma Operator

Bitwise Operators
During computation, mathematical operations like: addition, subtraction, addition and division
are converted to bit-level which makes processing faster and saves power.
Bitwise operators are used in C programming to perform bit-level operations.

Operators Meaning of operators

& Bitwise AND


| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
<< Shift left
>> Shift right

(a) Bitwise AND: The bitwise AND operation will be carried out between the two bit patterns
of the two operands.

Variable Value Binary pattern

x 5 0101
y 2 0010
x&y 0 0000
a 6 0110
b 3 0011
a&b 2 0010

To generate a 1 bit in the result, bitwise AND need a one in both numbers.

Bitwise AND operator &


The output of bitwise AND is 1 if the corresponding bits of two operands is 1. If either bit of
an operand is 0, the result of corresponding bit is evaluated to 0.

CU IDOL SELF LEARNING MATERIAL (SLM)


78 Computer Programming

Let us suppose the bitwise AND operation of two integers 12 and 25.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bit Operation of 12 and 25
00001100
& 00011001
—————
00001000 = 8 (In decimal)

Example #1: Bitwise AND


#include <stdio.h>
void main()
{
int a = 12, b = 25;
printf(“Output = %d”, a&b);
getch();
}

Output:
Output = 8
(b) Bitwise OR: The bitwise OR operations result 1 if any one of the bit value is 1.

Bitwise OR
Variable Value Binary pattern

x 5 0101
y 2 0010
x|y 7 0111
a 6 0110
b 1 0001
a|b 7 0111

CU IDOL SELF LEARNING MATERIAL (SLM)


Operators and Expressions 79

Bitwise OR operator |
The output of bitwise OR is 1 if at least one corresponding bit of two operands is 1. In C
Programming, bitwise OR operator is denoted by |.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise OR Operation of 12 and 25
00001100
| 00011001
________
00011101 = 29 (In decimal)

Example #2: Bitwise OR


#include <stdio.h>
void main()
{
int a = 12, b = 25;
printf(“Output = %d”, a|b);
getch( );
}

Output:
Output = 29
(c) Bitwise Exclusive OR: The bitwise exclusive OR will be carried out by the notation ^. To
generate a 1 bit in the result, a bitwise exclusive OR needs a one in either number but not both.
Bitwise EX – OR
Variable Value Binary pattern
x 5 0101
y 2 0011
x^y 25 11001
a 6 0110
b 3 0011
a^b 216 11011000

CU IDOL SELF LEARNING MATERIAL (SLM)


80 Computer Programming

Bitwise XOR (exclusive OR) operator ^


The result of bitwise XOR operator is 1 if the corresponding bits of two operands are opposite.
It is denoted by ^.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise Xor Operation Of 12 And 25
00001100
| 00011001
________
00010101 = 21 (In decimal)

Example #3: Bitwise XOR


#include <stdio.h>
void main()
{
int a = 12, b = 25;
printf(“Output = %d”, a^b);
getch( );
}

Output:
Output = 21
(d) Bitwise complement: The complement operator ~ switches all the bits in a binary pattern,
that is all the zeroes become ones and all ones become zeroes. It acts as a 1’s complement.

Variable Value Binary pattern

x 23 0001 0111
~x 132 1110 1000
y Ff 1111 1111
~y 00 0000 0000

CU IDOL SELF LEARNING MATERIAL (SLM)


Operators and Expressions 81

Bitwise complement operator ~


Bitwise complement operator is an unary operator (works on only one operand). It changes 1
to 0 and 0 to 1. It is denoted by ~.
35 = 00100011 (In Binary)
Bitwise complement Operation of 35
~ 00100011
________
11011100 = 220 (In decimal)
Twist in bitwise complement operator in C Programming
The bitwise complement of 35 (~35) is -36 instead of 220, but why?

Example #4: Bitwise complement


#include <stdio.h>
void main()
{
printf(“complement = %d\n”,~35);
printf(“complement = %d\n”,~-12);
getch( );
}

Output:
Complement = -36
Output = 11

(e) Shift Operators in C programming


There are two shift operators in C programming:
 Right shift operator
 Left shift operator.
Bitwise Right shift: The right shift >> operator is used for right shifting. For y = 41 binary
pattern is 0010 1001.

CU IDOL SELF LEARNING MATERIAL (SLM)


82 Computer Programming

y >> 3 will result


0010 1001
00010100 *****shift
00001010 *****shift
00000101 *****shift
y >> is 0000 0101

Right Shift Operator other Example:-


Right shift operator shifts all bits towards right by certain number of specified bits. It is
denoted by >>.
212 = 11010100 (In binary)
212>>2 = 00110101 (In binary) [Right shift by two bits]
212>>7 = 00000001 (In binary)
212>>8 = 00000000
212>>0 = 11010100 (No Shift)
Bitwise Left Shift: The << operator is used for left shifting. For y = 41 binary pattern is 0010
1001.
Variable Value Binary pattern
x 33 0010 0001
x << 3

0010 0001
shift *** 01000010
shift *** 10000100
shift *** 00001000
x << 3 is 00001000
Left Shift Operator: Left shift operator shifts all bits towards left by certain number of
specified bits. It is denoted by <<.

CU IDOL SELF LEARNING MATERIAL (SLM)


Operators and Expressions 83

212 = 11010100 (In binary)


212<<1 = 110101000 (In binary) [Left shift by one bit]
212<<0 =11010100 (Shift by 0)
212<<4 = 110101000000 (In binary) =3392(In decimal)

Example #5: Shift Operators


#include <stdio.h>
void main()
{
int num=212, i;
for (i=0; i<=2; ++i)
printf(“Right shift by %d: %d\n”, i, num>>i);

printf(“\n”);

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


printf(“Left shift by %d: %d\n”, i, num<<i);
getch( );
}

Right Shift by 0: 212


Right Shift by 1: 106
Right Shift by 2: 53

Left Shift by 0: 212


Left Shift by 1: 424
Left Shift by 2: 848
(f) Comma Operator: Comma operators are used to link related expressions together. For
example:
int a, c = 5, d;

CU IDOL SELF LEARNING MATERIAL (SLM)


84 Computer Programming

comma (,) works as a separator and an operator too and its behaviour is little different
according to the place where it is used.
(1) Comma (,) as separator
While declaration multiple variables and providing multiple arguments in a function, comma
works as a separator.
Example:
int a,b,c;
In this statement, comma is a separator and tells to the compiler that these (a, b, and c)
are three different variables.
(2) Comma (,) as an operator
Sometimes we assign multiple values to a variable using comma, in that case comma is known
as operator.
Example:
a = 10,20,30;
b = (10,20,30);
In the first statement, value of a will  be  10,  because assignment operator (=) has more
priority more than comma (,), thus 10 will be assigned to the variable a.
In the second statement, value of b will be 30, because 10, 20, 30 are enclosed in braces,
and braces has more priority than assignment (=) operator. When multiple values are given
with comma operator within the braces, then right most value is considered as result of the expression.
Thus, 30 will be assigned to the variable b.
Consider the program:
#include <stdio.h>
int main()
{
int a,b;
a = 10,20,30;
b = (10,20,30);

CU IDOL SELF LEARNING MATERIAL (SLM)


Operators and Expressions 85

//printing the values


printf(“a= %d, b= %d\n”,a,b);
return 0;
}
Output
a=10, b=30

3.9 Expressions and Evaluation of Expression


A statement causes the computer to carry out some action. There are three different classes of
statements in C. They are expression statements, compound statements and control statements.
An expression statement consists of an expression followed by a semicolon. The execution
of an expression statement causes the expression to be evaluated.
a = 23; //Assignment statement
Sum=a+b; //calculative assignment statement
++i; // Incremental statement
The first two expression statements are assignment-type statements. Each causes the value of
the expression on the right of the equal sign to be assigned to the variable on the left.
The third expression statement is an incrementing-type statement, which causes the value of
i to increase by 1.
A compound statement consists of several individual statements enclosed within a pair of
braces { }. Decision statement is also called as compound statement. The individual statements
may themselves be expression statements, compound statements or control statements. Thus, it is
the compound statement provides a capability for embedding statements within other statements.
A typical compound statement is shown below:
If(c==0)
{
total = 600;

CU IDOL SELF LEARNING MATERIAL (SLM)


86 Computer Programming

Percentage=(marks/total)*100;
}
Control statements are used to create special program features, such as logical tests, loops
and branches. Many control statements require that other statements be embedded within them.
for(i=1;i<=10;i++)
{
printf(“%d”,i);
}

3.10 Type Conversion


When variables and constants of different types are combined in an expression then they are
converted to same data type. The process of converting one predefined type into another is called
type conversion or type casting.
Type conversion in C can be classified into the following two types:

Implicit Type Conversion


When the type conversion is performed automatically by the compiler without programmers
intervention, such type of conversion is known as implicit type conversion or type promotion.
The compiler converts all operands into the data type of the largest operand.
The sequence of rules that are applied while evaluating expressions are given below:
All short and char are automatically converted to int, then,
1. If either of the operand is of type long double, then others will be converted to long
double and result will be long double.
2. Else, if either of the operand is double, then others are converted to double.
3. Else, if either of the operand is float, then others are converted to float.
4. Else, if either of the operand is unsigned long int, then others will be converted to
unsigned long int.

CU IDOL SELF LEARNING MATERIAL (SLM)


Operators and Expressions 87

5. Else, if one of the operand is long int, and the other is unsigned int, then
(1) if a long int can represent all values of an unsigned int, the unsigned int is converted
to long int.
(2) otherwise, both operands are converted to unsigned long int.
6. Else, if either operand is long int then others will be converted to long int.
7. Else, if either operand is unsigned int then others will be converted to unsigned int.
It should be noted that the final result of expression is converted to type of variable on left
side of assignment operator before assigning value to it.
Also, conversion of float to int causes truncation of fractional part, conversion of double to
float causes rounding of digits and the conversion of long int to int causes dropping of excess
higher order bits.

Explicit Type Conversion


The type conversion performed by the programmer by posing the data type of the expression
of specific type is known as explicit type conversion.
The explicit type conversion is also known as type casting.
Type casting in C is done in the following form:
(data_type)expression;
where, data_type is any valid C data type, and expression may be constant, variable or
expression.
For example,
1 x=(int)a+b*d;
The following rules have to be followed while converting the expression from one type to
another to avoid the loss of information:
1. All integer types to be converted to float.
2. All float types to be converted to double.
3. All character types to be converted to integer.

CU IDOL SELF LEARNING MATERIAL (SLM)


88 Computer Programming

3.11 Precedence and Associatively (Order of Evaluation)


C Operator Precedence Table
This page lists C operators in order of precedence (highest to lowest). Their associativity indicates in what
order operators of equal precedence in an expression are applied.

Operator Description Associativity


() Parentheses (function call) (see Note 1) left-to-right
[] Brackets (array subscript)
. Member selection via object name
-> Member selection via pointer
++ — Postfix increment/decrement (see Note 2) right-to-left

++ — Prefix increment/decrement
+- Unary plus/minus
!~ Logical negation/bitwise complement
(type) Cast (convert value to temporary value of type)
* Dereference
& Address (of operand)
sizeof Determine size in bytes on this implementation
*/% Multiplication/Division/Modulus left-to-right
+- Addition/Subtraction left-to-right

<< Bitwise shift left left-to-right


>> Bitwise shift right left-to-right
< <= Relational less than/less than or equal to left-to-right

> >= Relational greater than/greater than or equal to


== != Relational is equal to/is not equal to left-to-right
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right

CU IDOL SELF LEARNING MATERIAL (SLM)


Operators and Expressions 89

?: Ternary conditional right-to-left


= Assignment right-to-left
+= -= Addition/Subtraction assignment
*= /= Multiplication/Division assignment
%= &= Modulus/Bitwise AND assignment

^ = |= Bitwise exclusive/inclusive OR assignment


<<= >>= Bitwise shift left/right assignment
, Comma (separate expressions) left-to-right

Note 1: Parentheses are also used to group sub-expressions to force a different precedence; such
parenthetical expressions can be nested and are evaluated from inner to outer.

Note 2: Postfix increment/decrement have high precedence, but the actual increment or decrement of
the operand is delayed (to be accomplished sometime before the statement completes execution).
So in the statement y = x * z++; the current value of z is used to evaluate the expression,
(i.e., z++ evaluates to z) and z only incremented after all else is done. See postinc.cfor another
example.

Notes: Precedence and associativity are independent from order of evaluation.


The C language standard doesn't specify operator precedence. It specifies the language grammar,
and the precedence table is derived from it to simplify understanding. There is a part of the grammar
that cannot be represented by a precedence table: assignment is never allowed to appear on the
right hand side of a conditional operator, so e = a < d ? a++ : a = d is an expression that cannot be
parsed, and, therefore, relative precedence of conditional and assignment operators cannot be
described easily.
However, many C compilers use non-standard expression grammar where ?: is designated
higher precedence than =, which parses that expression as e = ( ((a < d) ? (a++) : a) = d ), which then
fails to compile due to semantic constraints: ?: is never lvalue and = requires a modifiable lvalue on
the left. This is the table presented on this page.
Note that this is different in C++, where the conditional operator has the same precedence as
assignment.

CU IDOL SELF LEARNING MATERIAL (SLM)


90 Computer Programming

Associativity specification is redundant for unary operators and is only shown for completeness:
unary prefix operators always associate right-to-left (sizeof ++*p is sizeof(++(*p))) and unary
postfix operators always associate left-to-right (a[1][2]++ is ((a[1])[2])++). Note that the associativity
is meaningful for member access operators, even though they are grouped with unary postfix
operators: a.b++ is parsed (a.b)++ and not a.(b++).

3.12 I/O Functions: printf( ), scanf( )

printf Function
The printf function writes data to standard output (usually, the terminal).
printf( ) function is available in stdio.h (standard input output header file)
Syntax of print() function:
printf(control_string, arg1, arg2, arg3, ..., argn);
where control_string refers to a character string containing formatting information, and arg1,
arg2, etc., are arguments that represent the individual output data items.
The purpose of printf() is to display messages and values on the standard output using format
specifiers.
The general format of printf() is
(1) printf(<msg>); only for displaying the message.
(2) printf(<format string>, arguments); only for displaying the value of argument or variable
(3) printf(<format string> <msg>, arguments) Displaying the message along with the value
of argument or variable.
Always the format string is defined within the " " ( double quotes)

Example 1:
printf("C is fun");
Will display
C is fun
printf() does not automatically print a new line. The programmer has to explicitly do it, by
including the \n in the format string.

CU IDOL SELF LEARNING MATERIAL (SLM)


Operators and Expressions 91

Example 2:
printf("The rain in Spain");
printf("stays mainly on the plains");

Output:
The rain in Spain stays mainly on the plains.
If you change the above to:
printf("The rain in Spain");
printf("\nstays mainly on the plains");

Output:
The rain in Spain
Stays mainly on the plains
The control string consists of individual groups of characters, with one character group for
each output data item. In its simplest form, each character group consists of a percent sign (%),
followed by a conversion character which controls the format of the corresponding data item.
The most useful conversion characters are as follows:
The format string can contain format specifiers like scanf().
%d stands for integer numbers
%c stands for character
%f stands for float
%s stands for string
%o stands for octal
%x stands for hexadecimal

Example 1:
void main()
{
int n;

CU IDOL SELF LEARNING MATERIAL (SLM)


92 Computer Programming

n = 7;
printf("There are %d days in a week. \n",n);
}

Output:
There are 7 days in a week.

Example 2:
void main()
{
int num=0;
printf("Enter number :");
scanf("%d\n" &num);
printf("The number is %d.\n",num);
}

Output:
Enter number: 20
The number is 20.

Example 3:
void main()
{
int num=0;
printf("Enter number :");
scanf("%d\n" &num);
printf("The number is %4d.\n",num);
}

CU IDOL SELF LEARNING MATERIAL (SLM)


Operators and Expressions 93

Output:
Enter number: 12
The number is 12
 Indicates a Blank Space

Example 4:
void main()
{
int a, b,c;
a= 10;
b=20;
c = a*b;
printf("The Product of Two numbers %d & %d is = %d \n", a,b,c);
}

Output:
The Product of Two numbers 10 and 20 is = 200

scanf Function
The scanf function reads data from standard input (usually, the terminal).
scanf( ) function is available in stdio.h (standard input output header file)
For inputting values to your program you can either use getchar() or scanf(). The getchar()
returns a single character from a standard input device, the function does not require any argument
and it is restricted in the sense that only one character can be read-in at a time and no float/string
values can be read and the scanf() function allows more flexible input.
Syntax of scanf() is:
scanf(control_string, arg1, arg2, arg3, ..., argn);
where control_string refers to a character string containing certain required formatting
information, and arg1, arg2, etc., are arguments that represent the individual input data items.

CU IDOL SELF LEARNING MATERIAL (SLM)


94 Computer Programming

Example:
scanf("%d", &n);
where the variable n has been declared as an integer.
The & is mandatory and stands for "address of".
scanf("%d %d", &a, &b);
where a,b are integers.
scanf("%f %d", &a, &f);
where a is a float and f is an integer
The first argument to the scanf() function is a format string which contains FORMAT
SPECIFIERS. Always the format string is defined within " " (double quotes).
The control string consists of individual groups of characters, with one character group for
each data input item. In its simplest form, each character group consists of a percent sign (%),
followed by a set of conversion characters which indicate the type of the corresponding data item.
These can be any of the following:
%d stands for integer numbers
%c stands for character
%e stands for floating-point value with an exponent
%f stands for float
%i stands for signed decimal integer
%u stands for unsigned decimal integer
%s stands for string
%o stands for octal
%x stands for hexadecimal
These all % characters are known as Modulus Operator

3.13 Summary
Operators form expressions by joining individual constants, variables, array elements. C
includes a large number of operators which fall into different categories. They are as follows:

CU IDOL SELF LEARNING MATERIAL (SLM)


Operators and Expressions 95

1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit-wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators
Type Conversion: When variables and constants of different types are combined in an
expression then they are converted to same data type. The process of converting one predefined
type into another is called type conversion or type casting.
Type conversion in C can be classified into the following two types:
(a) Implicit Type Conversion
(b) Explicit Type Conversion
Operators Precedence in C: Operator precedence determines the grouping of terms in an
expression and decides how an expression is evaluated. Certain operators have higher precedence
than others; for example, the multiplication operator has a higher precedence than the addition
operator.

3.14 Key Words/Abbreviations


 Operator: An operator is  a  symbol  that  tells  the  compiler  to  perform  a  certain
mathematical or logical manipulation.
 Operand: Operands are the objects that are manipulated and operators are the symbols
that represent specific actions. For example, in the expression. 5 + x. x and 5 are
operands and + is an operator. All expressions have at least one operand.
 I/O functions: These functions are used to permit the transfer of information between
the computer and the standard input/output device. The basic input/output functions are
getchar, putchar, puts, scanf and printf. The first two functions, getchar and putchar, are
used to transfer single characters.

CU IDOL SELF LEARNING MATERIAL (SLM)


96 Computer Programming

3.15 Learning Activity


1. What do you mean by operators in C? Explain the types of operators in detail.
.......................................................................................................................................
.......................................................................................................................................
2. Write a note on type casting in C.
.......................................................................................................................................
.......................................................................................................................................
3. Write a program in C to swap between two numbers.
.......................................................................................................................................
.......................................................................................................................................
4. Write a program in C to find the area of triangle.
.......................................................................................................................................
.......................................................................................................................................
5. Write a program in C to calculate simple interest.
.......................................................................................................................................
.......................................................................................................................................

3.16 Unit End Questions (MCQ and Descriptive)

A. Descriptive Type: Short Answer Type Questions


1. Explain different Arithmetic operators with example of each.
2. Describe the four relational operators included in C. With what type of operands can
they be used? What type of expression is obtained?
3. Describe the two logical operators included in C. What is the purpose of each? With
what type of operands can they be used?
4. How is the type of an assignment expression determined when the two operands are of
different data types?

CU IDOL SELF LEARNING MATERIAL (SLM)


Operators and Expressions 97

5. What are unary operators? How many operands are associated with a unary operator?
State purpose of each.
6. Describe two different ways to utilize the increment and decrement operators. How do
the two methods differ?
7. Explain conditional or ternary operators with suitable example.
8. Explain Bitwise operators and its types and comma operators with suitable example.
9. Describe Precedence and order of evaluation used in C Programming language.
10. Explain Statements and different types of statements in C programming language.
11. Describe Automatic and explicit type conversion with suitable example.
12. Explain Use of Formatted input and output functions with format specifers used. Illustrate
with some suitable examples.

B. Multiple Choice/Objective Type Questions


1. What is the output of this C code?
      int main()
    {
         int i = -5;
        int k = i %4;
        printf(“%d\n”, k);
    }
(a) Compile time error (b) -1
(c) 1 (d) None
2. What is the value of x in this C code?
     void main()
    {
         int x = 4 *5 / 2 + 9;
    }

CU IDOL SELF LEARNING MATERIAL (SLM)


98 Computer Programming

(a) 6.75 (b) 1.85


(c) 19 (d) 3
3.  What is the output of this C code?
    void main()
    {
        int k = 8;
        int x = 0 == 1 && k++;
        printf(“%d%d\n”, x, k);
    }
(a) 0   9 (b) 0   8
(c)  1   9 (d) 1   8
4. When double is converted to float, then the value is?
(a) Truncated (b) Rounded
(c) Depends on the compiler (d) Depends on the standard
5. When do you need to use type-conversions?
(a) The value to be stored is beyond the max limit
(b) The value to be stored is in a form not supported by that data type
(c) To reduce the memory in use, relevant to the value
(d) All of the mentioned
Answers: 1. (b), 2. (c), 3. (b), 4. (c), 5. (d)

3.17 References
1. http://download.nos.org/cca/cca11.pdf
2. https://www.programtopia.net/c-programming/docs/operators-expressions
3. https://fresh2refresh.com/c-programming/c-operators-expressions/
4. https://faculty.psau.edu.sa/filedownload/doc-13-pdf-
b790198028e7b75cde4173bc1c825c64-original.pdf
5. https://www.tenouk.com/download/pdf/Module3.pdf


CU IDOL SELF LEARNING MATERIAL (SLM)
Decision and Loop Control Structure 99

UNIT 4 DECISION AND LOOP CONTROL


STRUCTURE

Structure:
4.0 Learning Objectives
4.1 Introduction
4.2 Control Statements for Decision Making
4.3 Branching: If Statement
4.4 Looping: While Loop
4.5 Jump Statements
4.6 Summary
4.7 Key Words/Abbreviations
4.8 Learning Activity
4.9 Unit End Questions (MCQ and Descriptive)
4.10 References

4.0 Learning Objectives


After studying this unit, you will be able to:
 Define the concept of decision making
 Apply various decision making statements
 Differentiate between if-else and switch statement
 Explain the necessity of loop
 Describe various looping statements
 Analyze the nesting of loops
 Demonstrate the use of break and continue statements
 Elaborate go to statement

CU IDOL SELF LEARNING MATERIAL (SLM)


100 Computer Programming

4.1 Introduction
In any programming language, there is a need to perform different tasks based on the condition.
For example, consider an online website, when you enter wrong id or password it displays error
page and when you enter correct credentials then it displays welcome page. So there must be a logic
in place that checks the condition (id and password) and if the condition returns true it performs a
task (displaying welcome page) else it performs a different task (displaying error page).
Using decision control statements we can control the flow of program in such a way so that it
executes certain statements based on the outcome of a condition (i.e., true or false).

4.2 Control Statements for Decision Making


Decision making is about selecting one option from the available options, which are more
than one. While writing programs this concept is always going to play an important role. We have
to provide the capabilities to program so that it can take decisions on its own, depending upon the
various possible inputs from the user.
Decision making is about deciding the order of execution of statements based on certain
conditions or repeating a group of statements until certain specified conditions are met. We can
perform different — different tasks based on the conditions. C language handles decision making
in various ways as follows.

Sequential
Sequential means the program flow moves from one statement to the next, and then to the
later and then to the one after and so on.
It is the simplest form of structures, and it is not likely to be sequential structuring when
developing complex programs.

Selection (Decision)
Selection structures make decisions and perform commands according to the desicion making.
Selection structures involve “if statements” which are statements like “if this, then do that” and “if
not this, then do that”.
With “if statements”, we can also include “nested if statements”, which are “if statements”
inside other “if statements”. Another form of selection structures is called a “switch statement”,

CU IDOL SELF LEARNING MATERIAL (SLM)


Decision and Loop Control Structure 101

which is very powerful for certain situations, but not for others. “Switch statements” focus on the
value of a particular variable and perform different “cases” accordingly.

Repetition (Loops)
Repetition structures are used when something needs to be repeated a certain number of times
through the use of “loops”. A loop is simply a statement that completes iterations or cycles until a
certain value is reached and then execution moves to the next executable statement.
For instance, if you were to ask the user to enter ten values; to find the average of the numbers,
you could write a loop that would continue letting the user enter numbers until ten numbers had
been entered.

4.3 Branching: If Statement


One-way decisions are handled with an "if statement" and they either do some particular
thing or do nothing at all. The decision is based on a logical expression, which either evaluates to
true or false. If the logical expression is evaluated to true, then the corresponding statement is
executed; if the logical expression evaluates to false, control goes to the next executable statement.
The form of a one-way decision statement is as follows:
if ( test expression)
{
stmtT; //Block of code execute when condition is true
}
The stmtT can be a simple or compound statement. Simple involves 1 single statement.
Compound involves 1 or more statements enclosed with curly braces { }. A compound statement is
called a block statement.
The if statement evaluates the test expression inside parenthesis.
If test expression is evaluated to true (nonzero), statements inside the body of if is executed.
If test expression is evaluated to false (0), statements inside the body of if is skipped.

CU IDOL SELF LEARNING MATERIAL (SLM)


102 Computer Programming

Flowchart of if Statement

Fig. 4.1: Flowchart of if Statement

Example:
#include<stdio.h>
void main()
{
int x =20;
int y =22;
if(x<y)
{
printf("Variable x is less than y");
}
getch( );
}

CU IDOL SELF LEARNING MATERIAL (SLM)


Decision and Loop Control Structure 103

Output:
Variable x is less than y

4.3.1 If-Else Statement


Multi-way decision statements involve using "if/else if" statements, "nested ifs", or "switch"
statements. They are all used to evaluate a logical expression that could have several possible
values. "if/else if" statements are often used to choose between ranges of values.
The if...else statement executes some code if the test expression is true (nonzero) and some
other code if the test expression is false (0).

Syntax of if...else
if (testExpression)
{
// codes inside the body of if
}
else
{
// codes inside the body of else
}
If test expression is true, codes inside the body of if statement is executed and, codes inside
the body of else statement is skipped.
If test expression is false, codes inside the body of else statement is executed and, codes
inside the body of if statement is skipped.

CU IDOL SELF LEARNING MATERIAL (SLM)


104 Computer Programming

Flowchart of if...else statement

Test False
expression

True

Body of if Body of else

Statement just
below if.. else

Fig. 4.2: Flowchart of if... Else Statement


Example : C if...else statement
// Program to check whether an integer entered by the user is odd or even
#include <stdio.h>
void main()
{
int number;
printf("Enter an integer: ");
scanf("%d",&number);

// True if remainder is 0
if( number%2 == 0 )
printf("%d is an even integer.",number);
else
printf("%d is an odd integer.",number);
return 0;
}

CU IDOL SELF LEARNING MATERIAL (SLM)


Decision and Loop Control Structure 105

Output:
Enter an integer: 7
7 is an odd integer.
When user enters 7, the test expression ( number%2 == 0 ) is evaluated to false. Hence, the
statement inside the body of else statement printf("%d is an odd integer"); is executed and the
statement inside the body of if is skipped.

4.3.2 Nested if...else statement (if...elseif....else Statement)


The if...else statement executes two different codes depending upon whether the test expression
is true or false. Sometimes, a choice has to be made from more than 2 possibilities.
The nested if...else statement allows you to check for multiple test expressions and execute
different codes for more than two conditions.

Syntax of nested if...else statement.


if (testExpression1)
{
// statements to be executed if testExpression1 is true
}
else if(testExpression2)
{
// statements to be executed if testExpression1 is false and testExpression2 is true
}
else if (testExpression 3)
{
// statements to be executed if testExpression1 and testExpression2 is false and
testExpression3 is true
}
.
.
else
{

CU IDOL SELF LEARNING MATERIAL (SLM)


106 Computer Programming

// statements to be executed if all test expressions are false


}
The form of a multi-way decision using "nested ifs" is as follows:
if (conditionA)
{
if (conditionB)
stmtBT;
else
stmtBF;
}
else
stmtAF;
If conditionA is evaluated to true, then execution moves into the nested if and evaluates
conditionB. If conditionA is evaluated to false, then stmtAF is executed.
Example: C Nested if...else statement
// Program to relate two integers using =, > or <
#include <stdio.h>
void main()
{
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);

//checks if two integers are equal.


if(number1 == number2)
{

CU IDOL SELF LEARNING MATERIAL (SLM)


Decision and Loop Control Structure 107

printf("Result: %d = %d",number1,number2);
}
//checks if number1 is greater than number2.
else if (number1 > number2)
{
printf("Result: %d > %d", number1, number2);
}
// if both test expression is false
else
{
printf("Result: %d < %d",number1, number2);
}
getch( );
}

Output:
Enter two integers: 12
23
Result: 12 < 23

4.3.3 Switch Statement


A switch statement is yet another option for writing code that deals with multi-way decisions.
Switch case statementsare mostly used when we have a number of options (or choices) and we may
need to perform a different task for each choice.
The following are the feature of a switch construct:
1. Expression must be an integer expression.
2. Each case is labelled by an integer or character constant.
3. Cases and defaults may occur in any order.

CU IDOL SELF LEARNING MATERIAL (SLM)


108 Computer Programming

4. Cases must all be different.


5. After the code for one case is done, execution falls through to the next, unless you take
explicit action to escape.
6. The break statement causes an immediate exit from the switch.
7. Falling through cases is a mixed blessing.
8. Positive side is to have one code for multiple cases, redundancy avoided.
9. Negative side is to put break after each case.
Switch statements offer an alternative to an "else if" structure which has multiple possible
paths based on the value of a single expression.
A revised form for a switch statement is as follows:
switch (int expression)
{
case label - 1:
stmt-list-1;
break;
case label - 2:
stmt-list-2;
break;
case label - 3:
stmt-list-3;
break;
.
.
.
case label - n:
stmt-list-n;
break;

CU IDOL SELF LEARNING MATERIAL (SLM)


Decision and Loop Control Structure 109

default:
stmt-list;
}
During execution, the expression is evaluated. If the value of the expression matches label-1,
then stmt-list-1 will be executed. If not, execution will move on to check label-2 and so on. If no
labels match the expression, default will be executed. Inside each case and at the end of every
statement list (except default) there must be a break statement, which terminates the innermost
enclosing switch or loop statement.
Here are some final notes about switch statements: the expression being tested must result in
an integral value (int or single char), case labels must be integral constants (either literals or named
constants), each label within a switch should be unique, and each stmt-list may contain 0 or more
statements which do not need to enclosed with curly braces { }.

switch_expression

Equal
Case 1 Case 1 code block

Not Equal
Equal
Case 2 Case 2 code block

Not Equal
Equal
Case 3 Case 3 code block

Not Equal

Default Default code block

Next Statement after


Switch

Fig. 4.3: Flowchart of Switch Statement

CU IDOL SELF LEARNING MATERIAL (SLM)


110 Computer Programming

Example:
void main()
{
int i=2;
switch(i)
{
case1:
printf("Case1 ");
break;
case2:
printf("Case2 ");
break;
case3:
printf("Case3 ");
break;
case4:
printf("Case4 ");
break;
default:
printf("Default ");
}
getch( );
}

Output:
Case2

CU IDOL SELF LEARNING MATERIAL (SLM)


Decision and Loop Control Structure 111

4.4 Looping: While Loop


Loops are used in programming to repeat a specific block of code A loop is a statement of
code that does something over and over again until the logical expression of the loop evaluates to
false. It is simply a way of repeating code over and over again until some particular value is reached.
It can also be an effective way of making sure the user is inputting the correct type of input
(data validation).
The while loop is generally used for performing the same task, a fixed number of times.

Syntax of while loop:


while(test expression)
{
// C- statements, which requires repetition.
// Increment (++) or Decrement (--) Operation.
}
The while loop evaluates the test expression.
If the test expression is true (nonzero), codes inside the body of while loop is evaluated. The
test expression is evaluated again. The process goes on until the test expression is false.
When the test expression is false, the while loop is terminated

Flowchart of while loop

Fig. 4.4: Flowchart of While Loop

CU IDOL SELF LEARNING MATERIAL (SLM)


112 Computer Programming

Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int count=1;
while(count <=5)
{
printf("%d ", count);
count++;
}
getch();
}

Output:
12345
Step 1: First counter variable count has initialized with value 1 and then it has been tested
for the condition.
Step 2: If condition holds true then the body of the while loop gets executed otherwise,
control comes out of the loop.
Step 3: Count value was incremented using ++ operator, then it has been tested again for
the loop condition. It keeps happening until the condition returns to false.

4.4.1 Do.... While Loops


A do while loop is another type of repetition statement. It is exactly the same as the while
loop, except it does something and then evaluates the logical expression of the loop to determine
what happens next. Normally with a while loop, a part of the logical expression in the loop must be
initialized before execution of the loop.

CU IDOL SELF LEARNING MATERIAL (SLM)


Decision and Loop Control Structure 113

A do while loop statements will be performed and then checks the test expression of the loop.
do
{
// codes or statements
} while (testExpression);
The code block (loop body) inside the braces is executed once.
Then, the test expression is evaluated. If the test expression is true, the loop body is executed
again. This process goes on until the test expression is evaluated to 0 (false).
When the test expression is false (nonzero), the do...while loop is terminated.
The statement in the loop may be single or complex. Complex statements must be enclosed
with curly braces { }. Let's look at a couple of examples of do while loops.

Body of Loop

true Test
expression

false

Statement just
below Loop

Fig. 4.5: Flowchart of do... While Loop

Example: Program to print first ten multiple of 5.


#include<stdio.h>
#include<conio.h>
void main()

CU IDOL SELF LEARNING MATERIAL (SLM)


114 Computer Programming

{
int a;i;
a=5;
i=1;
do
{
printf("%d\t",a*i);
i++;
}
while (i <= 10);
getch();
}

Output:
5 10 15 20 25 30 35 40 45 50

4.4.2 For Loop


A for loop is another way to perform something that needs to be repeated in C++ (repetition).
Most programmers like to use for loops because the code can be written in a more compact manner
compared to the same loop written with a while or do while loop.
A for loop is generally used when you know exactly how many times a section of code needs
to be repeated.
The general form of a for loop is as follows:
for (expression1; expression2; expression3)
stmt(s);
where stmt(s) is a single or compound statement.
This is one of the most frequently used loops in C programming.

CU IDOL SELF LEARNING MATERIAL (SLM)


Decision and Loop Control Structure 115

The syntax of for loop looks like this –


for (initialization; condition test; control flow)
{
//Code - C statements needs to be repeated
}
The control flow can be increment or decrement value of variable depending on requirements.
Expression1 is used to initialize the loop; expression2 is used to determine whether or not the
loop will continue; expression3 is evaluated at the end of each iteration or cycle.
Note 1: Expression2 is tested before the stmt and expression3 is executed; it is possible that the
body of the loop is never executed or tested.
Note 2: Any or all of the 3 expressions in a for loop can be omitted, but the 2 semi-colons must
remain. Like for( ; ; )
If expression1 is omitted, there is no initialization done in the loop, but you might not
need any initialization for your program.
Like :
i=1;
for ( ; i<=10;i++)
If expression2 is omitted, there is no test section so you will essentially have an infinite
loop.
for(i=1; ; i++)
If expression3 is omitted, there is no update as part of the for statement, but the update
could be done as part of the statement in the body of the loop.
for(i=1;i<=10; )
{
printf("%d",i);
i++;
}

CU IDOL SELF LEARNING MATERIAL (SLM)


116 Computer Programming

The for loop is commonly used when the number of iterations is known.
In general, a for loop can be written as an equivalent to a while loop and vice versa.
for (expression1; expression2; expression3)
statement;
is equivalent to...
expression1;
while (expression2)
{
Statements;
expression3;
}

For Loop Flow Diagram

Initialization

False
For loop
condition

True

For loop code block

Increment/Update
Statements

Statement after for loop


code block

Fig. 4.6: Flowchart of For Loop

Example:

int i;
for(i=1; i<=4; i++)

CU IDOL SELF LEARNING MATERIAL (SLM)


Decision and Loop Control Structure 117

{
printf("hello, World");
}

Output:
hello,World
hello,World
hello,World
hello, World
Step 1: First the counter variable gets initialized; here variable is I, which has been assigned
by value 1.
Step 2: Then variable has been tested for a given condition, if the condition results in true
then C statements enclosed in loop body get executed by compiler, otherwise control
skips the loop and continues with the next statements following loop.
Step 3: After successful execution of loop's body, the counter variable is incremented or
decremented, depending on the operation (++ or -).

Various forms of for LOOP


Here we use variable num in all the below examples:
1. Here instead of num++, We can usenum=num+1, which is the same as num++.
for(num=10;num<20;num=num+1)
2. Initialization part can be skipped from loop as shown below, the counter variable is
declared before the loop itself.
int num=10;
for(;num<20;num++)
Must Note: Although we can skip init part but semicolon (;) before condition is must,
without which you will get compilation error.

CU IDOL SELF LEARNING MATERIAL (SLM)


118 Computer Programming

3. Like initialization, you can also skip the increment part as we did below. In this case
semicolon (;) is must, after condition logic. The increment part is being done in for loop
body itself.
for(num=10;num<20;)
{
//Code
num++;
}
4. Below case is also possible, increment in body and init during declaration of counter
variable.
int num=10;
for(;num<20;)
{
//Statements
num++;
}
5. Counter can be decremented also. In the below example the variable gets decremented
each time the loop runs until the condition num>10 becomes false.
for(num=20;num>10;num--)

4.4.3 Nested Loops


Nested loops or nesting of loop is placing one loop into another loop to execute a program
based on multiple conditions and checks.
Here we have an example of nesting of for loop, likewise you can use nesting of various loops
such as while, while do or for.
Basic syntax is for nesting for loop is,
for(initialization; condition; control flow)
{

CU IDOL SELF LEARNING MATERIAL (SLM)


Decision and Loop Control Structure 119

for(initialization; condition; control flow)


{
statement ;
}
}
Example: Program to print half Pyramid of numbers
#include<stdio.h>
#include<conio.h>
void main( )
{
int i,j;
for(i=1;i<5;i++)
{
printf("\n");
for(j=i;j>0;j--)
{
printf("%d",j);
}
}
getch();
}

Output:
1
21
321
4321
54321

CU IDOL SELF LEARNING MATERIAL (SLM)


120 Computer Programming

4.4.4 Infinite Loops


Infinite loop is a loop that never stops until you press ctrl-break on your keyboard. In order to
avoid infinite loops, you need a statement(s) inside the body of the loop that changes some part of
the logical expression.

Example 1:
#include<stdio.h>
#include<conio.h>
int main()
{
int a=6;
while(a>=5)
{
printf("%d",a);
a++;
}
return0;
}
Infinite loop: a will always have value >=5 so the loop would never end.

Example 2:
#include<stdio.h>
int main()
{
int x=5;
while(x<=10)
{
printf("%d",x);

CU IDOL SELF LEARNING MATERIAL (SLM)


Decision and Loop Control Structure 121

x--;
}
return0;
}
Infinite loop: x value will keep decreasing because of - operator, hence it will always be <=
10.

4.5 Jump Statements


It is sometimes desirable to skip some statements inside the loop or terminate the loop
immediately without checking the test expression. In such cases, Jumping statement break and
continue are used.

4.5.1 Break Statements


The break statement terminates the loop (for, while and do...while loop) immediately when it
is encountered. The break statement is used with decision making statement such as if...else.
Break statements are useful when you want your program-flow to come out of the switch
body. Whenever a break statement is encountered in the switch body, the execution flow would
directly come out of the switch.

Syntax of break statement


break;

CU IDOL SELF LEARNING MATERIAL (SLM)


122 Computer Programming

Flowchart of break statement

Fig. 4.7: Flowchart of Break Statements

Working of break statement:


while (test Expression)
{
// codes
If (condition for break)
{
break;
}
// codes
}

for (init, condition, update)

CU IDOL SELF LEARNING MATERIAL (SLM)


Decision and Loop Control Structure 123

{
// codes
if (condition for break)
{
break;
}
// codes
}
You can also use characters in switch case. For example:
void main()
{
char ch='b';
switch(ch)
{
case'd':
printf("CaseD ");
break;
case'b':
printf("CaseB");
break;
case'c':
printf("CaseC");
break;
case'z':
printf("CaseZ ");
break;

CU IDOL SELF LEARNING MATERIAL (SLM)


124 Computer Programming

default:
printf("Default ");
}
getch( );
}

Output:

CaseB
In addition to this, the break statement can also be used to terminate loops or to exit from a
switch. It can be used within a while a do — while, a for or a switch statement.
while(condition check)
{
statement-1;
statement-2;
if(some condition)
{
break;
}
statement-3;
statement-4;
}
Jumps out of the loop, no matter how
many cycles are left, loop is exited

4.5.2 Continue and goto Statements

Continue Statement
The continue statement skips some statements inside the loop. The continue statement is used
with decision making statement such as if...else

CU IDOL SELF LEARNING MATERIAL (SLM)


Decision and Loop Control Structure 125

Syntax of continue Statement


continue;

Flowchart of Continue Statement

Fig. 4.8: Flowchart of Continue and goto statements

Continue statement works following way:


while (test Expression)
{
// codes
If (condition for continue)
{
continue;
}
// codes
}

CU IDOL SELF LEARNING MATERIAL (SLM)


126 Computer Programming

for (init, condition, update)


{
// codes
if (condition for continue)
{
continue;
}
// codes
}

The continue statement can be used in for loop


The continue allows you to continue the execution of a for or while loop from the beginning,
making it possible to skip the rest of the statement in the loop after the continue statement.

Example:
#include <stdio.h>
void main( )
{
static int marks[5] = {90,80,76,89, -90};
int i, total = 0;
for(i=0; i<5; i++)
{
if(marks[i] <0)
{
ptrint("negative marks not added \n");
continue;
}
total += marks[i]
}

CU IDOL SELF LEARNING MATERIAL (SLM)


Decision and Loop Control Structure 127

printf("total marks = %d \n", total);


getch( );
}

Goto Statement:
A goto statement in C programming provides an unconditional jump from the 'goto' to a
labelled statement in the same function.

Syntax
The syntax for a goto statement in C is as follows ?
goto label;
... .. ...
... .. ...
... .. ...
label:
statement;
Here label can be any plain text except C keyword and it can be set anywhere in the C
program above or below to goto statement. The label is an identifier. When goto statement is
encountered, control of the program jumps to label: and starts executing the code.

Flow Diagram:

label 1 statement 2

go to
label 2 statement 2 label 3

label 3
statement 2

Fig. 4.9: Flowchart of goto Statement

CU IDOL SELF LEARNING MATERIAL (SLM)


128 Computer Programming

Example
#include <stdio.h>
void main ()
{
/* local variable definition */
int a = 10;
/* do loop execution */
LOOP:
do
{
if( a == 15)
{
/* skip the iteration */
a = a + 1;
goto LOOP;
}
printf("value of a: %d\n", a);
a++;
}
while( a < 20 );
getch( );
}
When the above code is compiled and executed, it produces the following result ?
value of a: 10
value of a: 11
value of a: 12
value of a: 13

CU IDOL SELF LEARNING MATERIAL (SLM)


Decision and Loop Control Structure 129

value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

4.6 Summary
We generally follow a sequence in the program but at times we would just want to execute
only selected statements.
1. This type of conditional processing is really useful to the programs.
2. It allows the programmers to build the programs that determine which statements
of the code should be executed and which are to be ignored.
Conditional statements
The conditional statements help to jump from one part of a program to another depending if a
particular condition is satisfied or not.
The conditional statements are:
1. if statement: It is one of the simplest forms of decision control statements which is frequently
used in decision making.
4. Switch case: This case statement is a multi-way decision statement which is a simpler
version of the if-else block which evaluates only one variable.
Control Structures: A loop is used for executing a block of statements repeatedly until a
given condition returns false.
1. For loop
2. While loop
3. do..while loop
Syntax of do-while loop

CU IDOL SELF LEARNING MATERIAL (SLM)


130 Computer Programming

Continue statement: The continue statement is used inside loops. When a continue statement
is encountered inside a loop, control jumps to the beginning of the loop for next iteration, skipping
the execution of statements inside the body of loop for the current iteration.
Goto statement: The goto statement is rarely used because it makes program confusing,
less readable and complex. Also, when this is used, the control of the program won’t be easy to
trace, hence it makes testing and debugging difficult.

4.7 Key Words/Abbreviations


1. Pre-increment operator: A pre-increment operator is used to increment the value of a
variable before using it in a expression. In the Pre-Increment, value is first incremented and then
used inside the expression.
Syntax:
a= ++x;
Here, if the value of ‘x’ is 10 then value of ‘a’ will be 11 because the value of ‘x’ gets modified
before using it in the expression.
2. Post-increment operator: A post-increment operator is used to increment the value of
variable after executing expression completely in which post increment is used. In the Post-Increment,
value is first used in a expression and then incremented.
Syntax:
a=x++;
Here, suppose the value of ‘x’ is 10 then value of variable ‘b’ will be 10 because old value of
‘x’ is used.

4.8 Learning Activity


1. Write a program in C to whether the no. entered is even or odd.
......................................................................................................................................
......................................................................................................................................

CU IDOL SELF LEARNING MATERIAL (SLM)


Decision and Loop Control Structure 131

2. Write a program in C to whether the no. entered is prime no. or not.


......................................................................................................................................
......................................................................................................................................
3. Write a program in C to display first 10 nos.
......................................................................................................................................
......................................................................................................................................
4. Write a program in C to display the following pattern
......................................................................................................................................
......................................................................................................................................
*
* *
* * *
* * * *

4.9 Unit End Questions (MCQ and Descriptive)

A. Descriptive Type: Short Answer Type Questions


1. Explain what are the different control structures available in C language.
2. Explain if, if-else and Nested if with syntax and demonstrate through suitable example.
3. What is meant by looping? Describe two different forms of looping.
4. Explain difference between for loop and while loop.
5. How is the execution of a while loop terminated?
6. Explain the for and while loop with continue statement.
7. Explain nesting of for loop with an example.
8. Explain nesting of if-else loop with an example.
9. Explain Infinite loop with an example.
10. Explain use of switch statement. Compare switch statement with if statement and state
the advantages of switch statement.

CU IDOL SELF LEARNING MATERIAL (SLM)


132 Computer Programming

11. How is break statement used in switch statement?


12. Explain use of continue statement with suitable example.
13. Explain Nested Loops with example.
14. Explain use of infinite loop with example.
15. Explain use of goto statement with suitable example.

B. Multiple Choice/Objective Type Questions


1. The continue statement cannot be used with
(a) for  (b) while
(c) do while (d) switch
2. Which keyword can be used for coming out of recursion?
(a) return (b) break
(c) exit (d) both A and B
3. goto can be used to jump from main to within a function?
(a) True (b) False
4.  Switch statement accepts.
(a) Int (b) char
(c) long (d) All of the above
5. Which loop is guaranteed to execute at least one time.
(a) for (b) while
(c) do while (d) None of the above
Answers: 1. (d), 2. (a), 3. (b), 4. (d), 5. (c)

CU IDOL SELF LEARNING MATERIAL (SLM)


Decision and Loop Control Structure 133

4.19 References
1. https://www.tutorialride.com/c-programming/decision-control-statements-in-c-
programming.htm
2. https://beginnersbook.com/2014/01/c-if-statement/
3. https://fresh2refresh.com/c-programming/c-decision-control/
4. http://www.nhcue.edu.tw/~jinnliu/teaching/cs07/6%20Control%20Structures.pdf
5. http://www.nyu.edu/classes/jcf/CSCI-GA.2110-001/slides/session3/ControlStructures-
LoopsConditionalsAndCaseStatements.pdf



CU IDOL SELF LEARNING MATERIAL (SLM)


134 Computer Programming

UNIT 5 ARRAYS

Structure:
5.0 Learning Objectives
5.1 Introduction
5.2 One Dimensional Array
5.3 Two Dimensional Arrays
5.4 Summary
5.5 Key Words/Abbreviations
5.6 Learning Activity
5.7 Unit End Questions (MCQ and Descriptive)
5.8 References

5.0 Learning Objectives


After studying this unit, you will be able to:
 Describe the concepts of arrays.
 Initializing a single dimensional array and accessing its elements with its memory
allocation.
 Declaring and initializing a 2 dimenional array and accessing its elements with its memory
allocation.
 Differentiate between one and two dimensional arrays

CU IDOL SELF LEARNING MATERIAL (SLM)


Arrays 135

5.1 Introduction
The array is another kind of variable or user defined variable that is used extensively in C. An
array is an identifier that refers to a collection of data items that all have the same name hence,
Array is a collection of similar types of data items like collection of all integers, collection of all
floats, collection of all characters.
The individual data items are represented by their corresponding array-elements (index).
Suppose that x is a 10-element array. The first element is referred to as x [0], the second as
x[1], and so on. The last element will be x [9]

Fig. 5.1: Array Structure

Each member in the array (i.e., each individual data item) is referred to by specifying the
array name followed by one or more subscripts (array index), with each subscript enclosed in
square brackets. Each subscript must be expressed as a non-negative integer. In an n-element array,
the array elements are:
x [0], x [1] , x [2], . . . ,x [n - 1]
as illustrated in the following diagram. The first element of the array is referred to using the notation
x[0], the second element is referred to using the notation x[1] and so on.
A declaration is a statement that provides a data type and an identifier for a variable. An
identifier is a program component’s name.

5.2 One Dimensional Array


When you declare an array, you declare a array that contains multiple similar type of data
items; each data item is one element of the array. Each element has the same data type, and each

CU IDOL SELF LEARNING MATERIAL (SLM)


136 Computer Programming

element occupies an area in memory next to, or contiguous to, the others. All elements in a array
will be stored in a contiguous allocation of a memory.

5.2.1 Array Declaration and Definition of Single Dimensional


An array is declared in a similar manner as a variable, only difference being that each array
name has to be specified by size. For one dimensional array, this is done by specifying a positive
integer expression in square brackets as shown below:
data-type array_name[ expression ]
where data-type is the data type (int, float, char) of array elements, array_name is the array name
and expression is a positive values integer constant that identifies the size of array.
For example,
int items[40];
the above statement declares an array named items of integer type with a capacity of 40 elements.
char street_name[35];
the above example declares a 35-element array named street_name of character type.

5.2.2 Initializing an Array


The following snippet places the data into array items of integer type with a capacity of 40
elements
for(i=0;i<40;i++)
{
printf(“Enter the item”);
scanf(“%d”, &items[i]);
}
The above for loop asks the user to enter the item 40 times. In the beginning, i=0 which causes
the scanf statement to initialize the array element items [ 0 ] (first element of the array). This
process continues till i=39 and that would initialize the last element of array: items [ 39 ].
Note that the scanf function includes an ampersand (&) in front of items[i], since single array
element is being entered rather than an entire array.

CU IDOL SELF LEARNING MATERIAL (SLM)


Arrays 137

5.2.3 Accessing an Array Element


The following snippet allows accessing an array element from array items of integer type
with a capacity of 40 elements
int value;
printf(“\n Values of array item:\n “);
for(i=0;i<40;i++)
{
value=items[i];
printf(“\n %d”, value);
}
The above for loop extracts the 40 elements stored in array items one at a time in variable
value and displays it in a printf() statement. Of course, the value variable can be eliminated and the
array element could have been displayed directly in printf() statement as shown below:
printf(“\n %d”, items[i]);
In some applications it may be desirable to assign initial values to the elements of an array.
This requires that the array either be defined globally, or locally (within the function) as a static
array. The following example explains the same:
int items[]={1,6,3,9,2,4,8,0};
void main()
{
int i, value=0;
printf(“\n Values of array item:\n “);
for(i=0;i<8;i++)
{
value=items[i];
printf(“\n %d”, value);
}
}

CU IDOL SELF LEARNING MATERIAL (SLM)


138 Computer Programming

Note that this version of the program does not require any input data. Execution of this program
will generate the following output:
Values of array item:
1
6
3
9
2
4
8
0

What Happens in Memory?


Consider the array
int arr[5];
here 5*2=10 bytes is immediately reserved in memory. Since this array is not initialized, the values
present in the memory location would be garbage. This happens because the storage class for the
array is auto, if it would have been static then the default initial value would be zero. This is
depicted in the following diagram:
arr elements: 4587 4125 8954 1478 1258

memory location: 5010 5012 5014 5016 5018

Fig. 5.2: Array in Memory Location after its Definition

Remember one thing; all the array elements would always be present in contiguous memory
locations.
Data entered with a subscript exceeding the array size will simply be placed in memory outside
the array; probably on top of other data, or on the program itself. This will lead to unpredictable
results and there will be no error message. In some cases the computer may just hang.

CU IDOL SELF LEARNING MATERIAL (SLM)


Arrays 139

5.3 Two Dimensional Arrays

5.3.1 Declaring Array Variables


The simplest form of multidimensional array is the two-dimensional array. A two-dimensional
array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of
size [x][y], you would write something as follows:
data-type array_name[expression][expression];
where data-type can be any valid C data type and array_name will be a valid C identifier. A two-
dimensional array can be considered as a table which will have x number of rows and y number of
columns. A two-dimensional array a, which contains three rows and four columns can be shown as
follows:
Column 0 Column 1 Column2
Row 1 a[0][0] a[0][1] a[0][2]
Row 2 a[1][0] a[1][1] a[1][2]
Row 3 a[2][0] a[2][1] a[2][2]

Fig. 5.3: Two-dimensional Array

Thus, every element in the array a is identified by an element name of the forma [ i ][ j ],
where ‘a’ is the name of the array, and ‘i’ and ‘j’ are the subscripts that uniquely identify each
element in ‘a’.

5.3.2 Initialization of 2D Array


Consider the following snippet to understand two-dimensional array initialization.
int items[4][2] = { { 34, 56 },
{ 12, 33 },
{ 34, 80 },
{ 12, 78 }
};
The above snippet initializes a 4 by 2 two-dimensional array. the same array may be even
initialized in the following manner:
int items[4][2] = { 1234, 56, 1212, 33, 1434, 80, 1312, 78 } ;

CU IDOL SELF LEARNING MATERIAL (SLM)


140 Computer Programming

Of course, it is little difficult to understand so most of the programmers use the previous way
to initialize the 2D array items.
It is important to remember that while initializing a 2-D array it is necessary to mention the
second (column) dimension, whereas the first dimension (row) is optional. That means the following
declarations are valid
int items[4][2] = { 34, 56, 12, 33, 34, 80, 12, 78 } ;
int items[][2] = { 34, 56, 12, 33, 34, 80, 12, 78 } ;
whereas the following declarations are not valid
int items[4][] = { 34, 56, 12, 33, 34, 80, 12, 78 } ;
Programmers need to take care of the order in which initial values are assigned to
multidimensional array elements. The rule is that the last (rightmost) subscript increases most
rapidly, and the first (leftmost) subscript increases least rapidly. Thus, the elements of a two-
dimensional array will be assigned by rows; i.e., the elements of the first row will be assigned, then
the elements of the second row, and so on. Hence the above declaration will have the initial assignment
as follows:

item[0][0] = 34 item[0][1] = 56 item[1][0] = 12 item[1][1] = 33

item[2][0] = 34 item[2][1] = 80 item[3][0] = 12 item[3][1] = 78

Fig. 5.4: Contents of the Array Items

Observe that the first subscript ranges from 0 to 2, while the second one ranges from 0 to 3.
The natural order in which the initial values are assigned can be altered by forming groups of
initial values enclosed within braces (i.e., { ... }). Consider the following example:
int items[4][2] = { { 34 },
{ 12 },
{ 34 },
{ 12 }
};

CU IDOL SELF LEARNING MATERIAL (SLM)


Arrays 141

What happens in memory for 2D arrays?


The arrangement of 2D array elements in rows and columns is only conceptual. The actual
memory allocations for 2D array are same as one-dimensional array. i.e. continuous.
Consider the array
int a[3][2]={ 81, 29, 34, 47, 52, 46 };
Its arrangement is shown in the following diagram:

a[0][0] a[0][1] a[1][0] a[1][1] a[2][0] a[2][1]


arr elements: 81 29 34 47 52 46
memory location: 4781 4783 4785 4787 4789 4791
Fig. 5.5: 2D array in Memory

An element of the above array can be accessed using the following code:
int value = a[1][0];
printf("Value = %d", a[1][0]);
The above snippet would produce the following output:
Value = 34

5.4 Summary
 An array is a group (or collection) of same data types. For example an int array holds
the elements of int types while a float array holds the elements of float types.
 There are 2 types of C arrays. They are,
1. One dimensional array
2. Multi-dimensional array
 Two dimensional  array
 Three dimensional array
 Four dimensional array etc…

CU IDOL SELF LEARNING MATERIAL (SLM)


142 Computer Programming

5.5 Key Words/Abbreviations


Arrays are important to C and should need a lot more attention. The following important
concepts related to array should be clear to a C programmer –

1. Multi-dimensional arrays: C supports multidimensional arrays. The simplest form of


the multidimensional array is the two-dimensional array.
2. Passing arrays to functions: You can pass to the function a pointer to an array by
specifying the array's name without an index.
3. Return array from a function: C allows a function to return an array.
4. Pointer to an array: You can generate a pointer to the first element of an array by
simply specifying the array name, without any index.

5.6 Learning Activity


1. Differentiate between one dimensional array and multi-dimensional array.
........................................................................................................................................
........................................................................................................................................
2. Write Program in C to take 5 values from the user and store them in an array.
........................................................................................................................................
........................................................................................................................................
3. Write Program in C find the average of n numbers using arrays.
........................................................................................................................................
........................................................................................................................................

5.7 Unit End Questions (MCQ and Descriptive)

A. Descriptive Type: Short Answer Type Questions


1. What is an array? How is it declared? What happens in memory?
2. Explain the process of single dimension array definition and declaration.
3. How can you initialize a single and double dimension array? Explain with an example.

CU IDOL SELF LEARNING MATERIAL (SLM)


Arrays 143

4. Differentiate between one dimensional and two dimensional array.


5. What is a two dimensional array? Explain how it can be initialized and how to access
elements of an array.
6. Write a program in c to declare a single dimension array of 10 elements, Accept 10
elements from the user and store into array and display sum of all 10 elements of an
array, sum of even elements separately, sum of odd elements separately.
7. Write a program in C to declare a single dimension array of 50 elements, Accept 50
elements from the user and store into array and display how many even elements, how
many odd elements separately.
8. Write a program in C to declare a single dimension array of 10 elements, Accept 10
elements from the user and store into array and Arrange array elements in ascending
order and display sorted order of elements also display minimum and maximum element
from array.
9. Write a program in C to declare a matrix of 3×3, Accept all matrix elements from the
user and store into matrix elements of two dimensional array and display matrix.

B. Multiple Choice/Objective Type Questions


1. Which of these best describes an array?
(a) A data structure that shows a hierarchical behaviour
(b) Container of objects of similar types
(c) Arrays are immutable once initialised
(d) Array is not a data structure
2. How do you initialize an array in C?
(a) int arr[3] = (1,2,3); (b) int arr(3) = {1,2,3};
(c) int arr[3] = {1,2,3}; (d) int arr(3) = (1,2,3);
3. An array elements are always stored in _______ memory locations.
(a) Sequential (b) random
(c) Sequential and random (d) None of the above

CU IDOL SELF LEARNING MATERIAL (SLM)


144 Computer Programming

4. An array Index starts with?


(a) -1 (b) 0
(c) 1 (d) 2
5. What is the output of C Program?
int main()
{
int a[];
a[4] = {1,2,3,4};
printf("%d", a[0]); }
(a) 1 (b) 2
(c) 4 (d) Compiler error
Answers: 1. (b), (c), 3. (a), 4. (b), 5. (d)

5.8 References
1. https://beginnersbook.com/2014/01/c-arrays-example/
2. https://fresh2refresh.com/c-programming/c-array/
3. https://www.tutorialspoint.com/cprogramming/c_arrays.htm
4. http://ee.hawaii.edu/~tep/EE160/Book/PDF/Chapter9.pdf



CU IDOL SELF LEARNING MATERIAL (SLM)


Strings 145

UNIT 6 STRINGS

Structure:
6.0 Learning Objectives
6.1 Introduction
6.2 Strings Basics
6.3 Declaring and Initializing String Variables
6.4 String Storage
6.5 Built-in-string functions
6.6 Summary
6.7 Key Words/Abbreviations
6.8 Learning Activity
6.9 Unit End Questions (MCQ and Descriptive)
6.10 References

6.0 Learning Objectives


After studying this unit, you will be able to:
 Describe the concepts of strings
 Declaring and initialzing the string variables
 String storage
 Apply string handling functions

CU IDOL SELF LEARNING MATERIAL (SLM)


146 Computer Programming

6.1 Introduction
String is an array of characters. In this guide, we learn how to declare strings, how to work
with strings in C programming and how to use the pre-defined string handling functions.
We will see how to compare two strings, concatenate strings, copy one string to another &
perform various string manipulation operations. We can perform such operations using the pre-
defined functions of “string.h” header file. In order to use these string functions you must include
string.h file in your C program.

6.2 Strings Basics


In C programming, array of characters is called a string. A string is terminated by a null
character/0. Strings are in fact one-dimensional array of characters. Strings are always enclosed by
double quotes. Whereas, character is enclosed by single quotes in C.

Example for C String


char string[15] = {'s', 'h', 'r', 'u', 't', 'k', 'i', 'r', 't', 'i', '\0'};
char string[15] = "shrutkirti";
char string [] = "shrutkirti";
Difference between above declarations are, when we declare char as "string[20]", 20 bytes of
memory space is allocated for holding the string value.
When we declare char as "string[]", memory space will be allocated as per the requirement
during execution of the program.
A string in the C language is simply an array of characters. Strings must have a NULL or \0
character after the last character to show where the string ends. A string can be declared as a
character array or with a string pointer. First we take a look at a character array example:
char mystr[15];
As you can see the character array is declared in the same way as a normal array. This array
can hold only 14 characters, because we must leave room for the NULL character
#include <stdio.h>
int main()

CU IDOL SELF LEARNING MATERIAL (SLM)


Strings 147

{
char name[15];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}

Output:
Enter name
Shrutkirti
Your name is Shrutkirti

6.3 Declaring and Initializing String Variables


Consider the following declaration and initialization that creates a string consisting of the
word "Program". To hold the null character at the end of the array, the size of the character array
containing the string is one more than the number of characters in the word "Programming"
char word[8] = {'P', 'r', 'o', 'g', 'r', 'a', 'm', '\0'};
The above array can also be initialized as follows
char word[] = "Program";

6.4 String Storage

Index 0 1 2 3 4 5 6 7
Array P r o g r a m \0
Memory location 7890 7891 7892 7893 7894 7895 7896 7897

Fig. 6.1: Contents of the character array

The null character automatically places the \0 character at the end of the string when it's
initialized in the array.

CU IDOL SELF LEARNING MATERIAL (SLM)


148 Computer Programming

Example:
void main()
{
char word[8] = {'P', 'r', 'o', 'g', 'r', 'a', 'm', '\0'};
printf("Message = %s", word );
}

Output:
Message = Program

Global and Local Variables


A local variable is declared inside a function. A global variable is declared outside all functions.
A local variable can only be used in the function where it is declared. A global variable can be used
in all functions.
##include<stdio.h>
// Global variables
int x;
int y;

int add()
{
return x + y;
}
int main()
{
int answer; // Local variable
x = 2;
y = 5;

CU IDOL SELF LEARNING MATERIAL (SLM)


Strings 149

answer = add();
printf(“%d\n”,answer);
return 0;
}
In example, global variables are declared, x and y. These variables can be used in main() and
add(). The local variable answer can only be used in main().

6.5 Built-in-string-Functions
string.h or strings.h
The C language provides no explicit support for strings in the language itself. The string-
handling functions are implemented in libraries. String I/O operations are implemented in <stdio.h>
(puts , gets, etc). A set of simple string manipulation functions are implemented in <string.h>, or on
some systems in <strings.h>.
There is a separate header file that handles String in C Programming named "string.h". It
provides a wide range of functions that manipulate a null-terminated string.

strcpy() function
This library function is used to copy a string and can be used like this: strcpy(destination,
source). (It is not possible in C to do this: string1 = string2). Take a look at the following example:
str_one = "shruti";
str_two = "kirti";
strcpy(str_one , str_two); // str_one becomes "kirti"
Note: strcpy() will not perform any boundary checking, and thus, there is a risk of overrunning
the strings.

strcmp() function
This library function is used to compare two strings and can be used like this: strcmp(str1,
str2).
 If the first string is greater than the second string a number greater than null is returned.
 If the first string is less than the second string a number less than null is returned.
 If the first and the second string are equal a null is returned.

CU IDOL SELF LEARNING MATERIAL (SLM)


150 Computer Programming

Take look at an example:


printf("Enter you name: ");
scanf("%s", name);
if( strcmp( name, "Shruti" ) == 0 )
printf("Hello, Shruti!\n");
Note: strcmp() will not perform any boundary checking, and thus, there is a risk of overrunning
the strings.

strcat() function
This library function concatenates a string onto the end of the other string. The result is
returned. Take a look at the example:
printf("Enter you age: ");
scanf("%s", age);
result = strcat( age, " years old." ) == 0 )
printf("You are %s\n", result);
Note: strcat() will not perform any boundary checking, and thus, there is a risk of overrunning
the strings.

strlen() function
This library function returns the length of a string. (All characters before the null termination.)
Take a look at the example:
name = "Shruti";
result = strlen(name); //Will return size of six.

memcmp() function
This library function compares the first count characters of buffer1 and buffer2. The function
is used like this: memcmp(buffer1,buffer2). The return values are as follows:
 If buffer1 is greater than buffer2 a number greater than null is returned.
 If buffer1 is less than buffer2 a number less than null is returned.
 If buffer1 and buffer2 are equal a null is returned.

CU IDOL SELF LEARNING MATERIAL (SLM)


Strings 151

Note: There are also library functions: memcpy, memset and memchr.

strlwr() function
strlwr( ) function converts a given string into lowercase. Syntax for strlwr( ) function is given
below.
char *strlwr(char *string);
In this program, string "MODIFY This String To LOwer" is converted into lower case using
strlwr( ) function and result is displayed as "THIS IS CAPITAL STRING".
#include<stdio.h>
#include<string.h>
int main()
{
char str[ ] = " THIS IS CAPITAL STRING ";
printf("%s\n",strlwr (str));
return 0;
}

Output:
modify this string to lower

strupr() function
strupr( ) function converts a given string into uppercase. Syntax for strupr( ) function is given
below.
char *strupr(char *string);
In this program, string is converted into uppercase using strupr( ) function and result is displayed
as "THIS IS LOWER CASE STRING".
#include<stdio.h>
#include<string.h>
int main()
{

CU IDOL SELF LEARNING MATERIAL (SLM)


152 Computer Programming

char str[ ] = "This is lower case string";


printf("%s\n",strupr(str));
return 0;
}

Output:
MODIFY THIS STRING TO UPPER

strrev() function
strrev( ) function reverses a given string in C language. Syntax for strrev( ) function is given
below:
char *strrev(char *string);
In below program, string "Shrutkirti" is reversed using strrev( ) function and output is displayed
as "itrikturhS".
#include<stdio.h>
#include<string.h>
int main()
{
char name[25] = " Shrutkirti ";
printf("String before strrev( ) : %s\n",name);
printf("String after strrev( ) : %s",strrev(name));
return 0;
}

Output:
String before strrev( ) : Shrutkirti
String after strrev( ) : itrikturhS

CU IDOL SELF LEARNING MATERIAL (SLM)


Strings 153

Table 6.1: List of String Functions

Sr. No. String Function Description


1 strcpy(s1, s2); Copies string s2 into string s1
2 strcat(s1, s2); Concatenates string s2 onto the end of string s1
3 strlen(s1); Returns the length of string s1
4 strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than
0 if s1>s2.
5 strchr(s1, ch); Returns a pointer to the first occurrence of character ch in string s1
6 strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1
7 strrchr ( ) Returns last occurrence of given character in a string is found
8 strrstr ( ) Returns pointer to last occurrence of str2 in str1
9 strdup ( ) Returns Duplicates the string
10 strlwr ( ) It Converts string to lowercase
11 strupr ( ) It Converts string to uppercase
12 strrev ( ) Returns Reverses the given string
13 strset() Returns Sets all character in a string to given character
14 strnset() It sets the portion of characters in a string to given character
15 strtok() Tokenizing given string using delimiter

Consider the following example that demonstrates some of the above mentioned methods
#include<string.h>
#include<stdio.h>
#include<conio.h>
void main()
{
char msg1[10] = "Good"; //String one
char msg2[10] = "morning"; //String two
char msg3[15]; //String three to hold the result
//original strings

CU IDOL SELF LEARNING MATERIAL (SLM)


154 Computer Programming

printf("\n\nOriginal Messages:\n");
printf("\nMsg1 : %s",msg1);
printf("\nMsg2 : %s",msg2);
//copy string
strcpy(msg3,msg2);
printf("\n\nMessages after copying:\n");
printf("\nMsg1 : %s",msg1);
printf("\nMsg2 : %s",msg2);
printf("\nMsg3 : %s",msg3);
printf("\n\nLength of Messages before concatenation:\n");
printf("\nMsg1 : %d", strlen(msg1));
printf("\nMsg2 : %d", strlen(msg2));
//string concatenation
strcat(msg1,msg2);
printf("\n\nMessages after concatenation:\n");
printf("\nMsg1 : %s",msg1);
printf("\nMsg2 : %s",msg2);
printf("\n\nLength of Messages after concatenation:\n");
printf("\nMsg1 : %d", strlen(msg1));
printf("\nMsg2 : %d", strlen(msg2));
getch();
}

Output:
Original Message
Msg1 : Good
Msg2 : Morning

CU IDOL SELF LEARNING MATERIAL (SLM)


Strings 155

Messages after copying


Msg1 : Good
Msg2 : Morning
Msg3 : Morning
Length of Messages before concatenation
Msg1 : 4
Msg2 : 7
Messages after concatenation
Msg1 : GoodMorning
Msg2 : Morning
Length of Messages after concatenation
Msg1 : 11
Msg2 : 7

6.6 Summary
 Strings are actually one-dimensional array of characters terminated by a null character
‘\0’. Thus a null-terminated string contains the characters that comprise the string
followed by a null.
 Strings are defined as an array of characters. The difference between a character array
and a string is the string is terminated with a special character ‘\0’.

6.7 Key Words/Abbreviations


C STRING FUNCTIONS:
String.h header file supports all the string functions in C language. All the string functions are
given below.
1. strcat ( ) - Concatenates str2 at the end of str1
2. strcpy ( ) - Copies str2 into str1
3. strlen ( ) - Gives the length of str1

CU IDOL SELF LEARNING MATERIAL (SLM)


156 Computer Programming

4. strcmp ( ) - Returns 0 if str1 is same as str2. Returns <0 if strl < str2. Returns >0 if str1
> str2
5. strcmpi ( ) - Same as strcmp() function. But, this function negotiates case.  “A” and “a”
are treated as same.
6. strchr ( ) - Returns pointer to first occurrence of char in str1.
7. strrchr ( ) - last occurrence of given character in a string is found
8. strstr ( ) - Returns pointer to first occurrence of str2 in str1
9. strrstr ( ) - Returns pointer to last occurrence of str2 in str1
10. strdup ( ) - Duplicates the string
11. strlwr ( ) - Converts string to lowercase
12. strupr ( ) - Converts string to uppercase
13. strrev ( ) - Reverses the given string
14. strset ( ) - Sets all character in a string to given character
15. strtok ( ) - Tokenizing given string using delimiter

6.8 Learning Activity


1. Write a program in C to print a string.
.......................................................................................................................................
.......................................................................................................................................
2. Write a program in C to sort string characters.
.......................................................................................................................................
.......................................................................................................................................
3. Write a program in C to find length of the string without function.
.......................................................................................................................................
.......................................................................................................................................
4. Write a program in C to concatenate two strings.
.......................................................................................................................................
.......................................................................................................................................

CU IDOL SELF LEARNING MATERIAL (SLM)


Strings 157

6.9 Unit End Questions (MCQ and Descriptive)

A. Descriptive Type: Short Answer Type Questions


1. What is string? How is it declared? What happens in memory?
2. Explain the various types of string functions with example.
3. Write a program in C to compare two strings.
4. Write a program in C to accept the string from user & print length of the string.
5. Write a program in C to accept string from user and copy that string into another string.
6. Write a program in C to accept two strings from user and combine both of the strings
and print combined string.
7. Write a program in C to accept the string from user and print whether it is palindrome or
not.
8. Explain string header files in C programming language.

B. Multiple Choice/Objective Type Questions


1. Which of the following function sets first n characters of a string to a given character?
(a) strinit() (b) strnset()
(c) strset() (d) strcset()
2. If the two strings are identical, then strcmp() function returns
(a) -1 (b) 1
(c) 0 (d) Yes
3. The library function used to find the last occurrence of a character in a string is
(a) strnstr() (b) laststr()
(c) strrchr() (d) strstr()
4. Which of the following function is more appropriate for reading in a multi-word string?
(a) printf(); (b) scanf();
(c) gets(); (d) puts();

CU IDOL SELF LEARNING MATERIAL (SLM)


158 Computer Programming

5. What will be the output of the following C code?


#include <stdio.h>
int main()
{
char *str = "hello, world\n";
printf("%d", strlen(str));
}
(a) Compilation error (b) Undefined behaviour
(c) 11 (d) 13
Answers: 1. (b), 2. (c), 3. (c), 4. (c), 5. (d)

6.10 References
1. https://www.tutorialspoint.com/learn_c_by_examples/string_programs_in_c.htm
2. https://beginnersbook.com/2014/01/c-strings-string-functions/
3. https://www.programiz.com/c-programming/c-strings
4. C Programming Language written by Dennis Ritchie and Brian W. Kernighan.



CU IDOL SELF LEARNING MATERIAL (SLM)


Functions 159

UNIT 7 FUNCTIONS

Structure:
7.0 Learning Objectives
7.1 Introduction
7.2 Concepts of User Defined Function
7.3 Function Prototype (Declaration) and Definition
7.4 Return Statement
7.5 Calling a Function by Passing Values
7.6 Recursive Function
7.7 Summary
7.8 Key Words/Abbreviations
7.9 Learning Activity
7.10 Unit End Questions (MCQ and Descriptive)
7.11 References

7.0 Learning Objectives


After studying this unit, you will be able to:
 Explain the concepts of functions
 Describe different types of functions
 Discuss recursive functions
 Discuss Attributes of functions

CU IDOL SELF LEARNING MATERIAL (SLM)


160 Computer Programming

 Discuss Prototype of Function


 Diffferent way of calling the Function

7.1 Introduction
A function is a block of statements that performs a specific task. Suppose you are building an
application in C language and in one of your program, you need to perform a same task more than
once. In such case you have two options –
(a) Use the same set of statements every time you want to perform the task.
(b) Create a function to perform that task, and just call it every time you need to perform
that task.
Using option (b) is a good practice and a good programmer always uses functions while
writing codes in C.

7.2 Concepts of User Defined Function


Functions are a set of block of statement to avoid repetitive task.
Dividing a program into functions is the major principle of top-down structured programming.
It also reduces the size of the program when function is called many times or can be called at
different places.
Since function will be defined to put repetitive statements to perform a task and then function
can be called at places wherever we need to execute that task.

Different uses of Functions used in C


1. C functions are used to avoid rewriting the same block of statements, which are to be
executed again and again.
2. Functions can be called as many times as required. No limitation on calling of a function.
3. Defining function specifies modularization which divides large C programs into
functions,. i.e., dividing big task into small parts to achieve functionality.
4. The core concept of modularization that means dividing program into functions is
reusability.

CU IDOL SELF LEARNING MATERIAL (SLM)


Functions 161

5. Modification can be done easily because of modularization. Updatation does not affect
whole program only respective module will be affected.

Categories of Functions
C functions can be classified into two categories,
 Library functions
 User-defined functions
Library functions are those functions which are defined by C library, example printf(), scanf(),
strcat() etc.
Every C Program has main() function inbuilt in the program with return type int or void which
is function header statement.
Consist of main function definition with function body comprises of atatements terminated
by; sign and user defined functions can be added according to the requirement.

7.3 Function Prototype (Declaration) and Definition


7.3.1 Defining a Function

Function Definition:
return_type function name (no. of parameters/arguments with data types)
{
c statement; // Block code of statements //
c statement;
return statement;
}
Return_type: Every function returns a value after execution of block of statements, Return
type can be of any data type such as int, double, char, void, short, etc., Normally, function return
type is any datatype but if function does not return any value then we have to specify with void
keyword to indicate function returns null value.

CU IDOL SELF LEARNING MATERIAL (SLM)


162 Computer Programming

Function_name: Function name should be valid identifier and function name should be a
meaningful name so that it can be easy to understand the purpose of function just by seeing its
name.
Argument list/parameter list (type arg1, type arg2): Arguments are also called parameters,
parameter list contains variables names along with their data types. These arguments are positional
formal/dummy parameters whose value can be replaced with actual parameter during function call.
For example – A function which is used to add three integer variables, will have three integer
argument. All arguments are to be specified along with data type and are separated by commas.
Block of code: It is a Set or Block of C statements, which will be executed during function
call. Function definition execution will be performed in a stack.
If function has return type, then return statement will be the last statement of a block and if
function has no return type, i.e., void then this function will have a no return statement.
Let us Assume on example to solve the problem of function

Problem 1: Write a Function for addition of two numbers

Solution:

Function Definition of sum of two numbers with Return type:


int sum (int a, int b)
{
int c;
c = a + b;
return c;
}

Problem 2: Write a Function to print entered number in even or odd

Solution:.

Function definition of even number checking with No return type hence void:
void even (int a)
{

CU IDOL SELF LEARNING MATERIAL (SLM)


Functions 163

if (a%2 = = 0)
printf(“a is even”);
else
printf(“a is odd”);
}

Example:
/* function return type is void and doesn’t have parameters*/
void main()
{
/*calling function*/
intro();
getch();
}
void intro()
{
printf(“Hi\n”);
printf(“My name is Kiran Gurbani\n”);
printf(“How are you?”);
/* there is no return statement inside this function, since its
* return type is void */
}

Output:
Hi
My name is Kiran Gurbani
How are you?

CU IDOL SELF LEARNING MATERIAL (SLM)


164 Computer Programming

Pictorial representation of function call accessed by function definition and returing


value back to main function.

Fig. 7.1: Pictorial representation of function call accessed by function definition and
returing value back to main function

7.3.3 Function Prototypes

Function Prototypes
1. Function prototype is the signature of the function also called a function declaration.
2. Function declaration informs to the compiler about return type of the function, name of
the function and list of arguments with their data types.

Examples of function prototype statement or function declaration


Function with three integer arguments and integer as return type is represented using below
syntax
 int sum(int,int, int);, int c); OR
 int sum( int a, int b, int c);
Function with integer argument and integer as return type is represented using below syntax
 int cube(int);
In the below example we have written function with no argument and no return type
 void display(void);

CU IDOL SELF LEARNING MATERIAL (SLM)


Functions 165

In below example we have declared function with no argument and integer as return type
 int get(void);

Case 1: Function definition written before main function


In this case we are defining function before main function, hence function declaration is not
needed. It is optional.
#include<stdio.h>
#include<conio.h>
void display()
{
printf(“Hello, Welcome to Kiran\n”);
printf(“ How are you”);
}
void main()
{
display();
getch();
}

Case 2: Function definition written after main function


In this case we are defining function after main funiction, hence function declaration is
compulsory to be specified in the global declaration or local declaration before main function.
#include<stdio.h>
#include<conio.h>
// Function Prototype Declaration
int sum(int a, int b);
void main()
{

CU IDOL SELF LEARNING MATERIAL (SLM)


166 Computer Programming

int x,y,s;
clrscr();
printf(“Enter two numbers\n”);
scanf(“%d %d”,&x,&y);
s=x+y;
printf(“\n The sum of two numbers is %d”,s);
getch();
}
int sum(int a, int b)
{
int c;
c= a+b;
return c;
}

7.3.4 Passing Arguments to a Function and Specifying Argument Data Type


Arguments are the parameters that are passed to a function definition, function call and function
declaration.
These parameters or arguments are local to a function, the scope of these arguments is valid
within a function itself, outside function, it cannot be executed, hence these local arguments value
is to be passed to formal positional parameters of the function.

Arguments can be passed to functions and functions always return one value
1. If function returns only one single value then function must have return data type
compulsory.
Example: Sum of three numbers, Factorial of a number, these functions having return
value by function, will be single.
2. If function returns more than one values or if through function we are going to print
any message then in both the cases function does not have any return type because

CU IDOL SELF LEARNING MATERIAL (SLM)


Functions 167

function cannot return more than one value and we cannot return message hence function
will not have any return type. By using pointers we can achieve this.
Example: Print number is even or odd, print number is prime or not, print natural
numbers from 1 to 10, print prime numbers from 1 to n.
3. Function with argument return multiple values using function using pointers.

1. Functions with arguments with return type


In this type when function is called within a main function then function can send arguments
from the calling function to the called function and wait for the result to be returned back from the
called function back to the calling function. The argument values will be evaluated by called function
and result will be returned to calling function.
This program has sum as a user defined function, during the call of this function values of x
and y are passed from calling function to user defined function sum into a and b variables. The
result of addition will be stored in r variable within called function and return back to calling
function and stored in z variable. Further processing of printing of result will be done in main
function.

Example of sum of two numbers using function


#include<stdio.h>
#include<conio.h>
void main()
{
int sum(int, int);
int x,y,z;
clrscr();
printf(“Enter two numbers\n”);
scanf(“%d %d”,&x, &y);
z = sum(x,y);

CU IDOL SELF LEARNING MATERIAL (SLM)


168 Computer Programming

printf(“\nThe sum of two numbers is %d.”,z);


getch();
}
int add(int a, int b)
{
int r;
r = a+b;
return r;
}

2. Functions with arguments no return type due to message returning


In this type when a function is called within a main function then function can send arguments
from the calling function to the called function. The argument values will be evaluated by called
function and the result will be displayed within the user defined function. Called function will not
return anything to calling function since function does not return any value.
In this program during call of this function values of x is passed from calling function to user
defined function even into a variable, then evaluation of variable a will be done in function definition
and result message will be printed in function definition.
#include<stdio.h>
#include<conio.h>
void even(int n);
void main()
{
int x;
clrscr();
printf(“Enter a number\n”);
scanf(“%d”,&x);
even(x);

CU IDOL SELF LEARNING MATERIAL (SLM)


Functions 169

getch();
}
void even(int n)
{
If(n % 2 ==0)
printf(“*n=%d is even number “,n);
else
printf(“n = %d is odd number”,n);
}
c of the function with arguments and no return value.

3. Functions with arguments no return type due to returning of multiple values


In this type when function is called within main function then function can send argument
from the calling function to the called function The argument values will be evaluated by called
function and the result will be displayed within user defined function. Called function will not
return anything to calling function since function does not return any value.
In this program during call of this function, value of x is passed from calling function to user
defined function into a variable, then evaluation of variable a will be done in function definition
and result message will be printed in function definition, since function is returning multiple values.
#include<stdio.h>
#include<conio.h>
void natural(int x);
void main()
{
int x;
clrscr();
printf(“Enter a number\n”);
scanf(“%d”,&x);
natural(x);

CU IDOL SELF LEARNING MATERIAL (SLM)


170 Computer Programming

getch();
}
void natural(int n)
{
int i;
for( i=1;i<=n;i++)
{
printf(“%d”,i);
}
}
Pictorial representation of the function with arguments and no return value because of multiple
values returning.

4. Functions with arguments that return multiple values


So far, we have learned and seen that in a function, return statement was able to return only a
single value. That is because; a return statement can return only one value. But if we want to send
back more than one value then how could we do this?
For that we have to use pointers

What are pointers?


A pointer is a variable that represents the location (rather than the value) of a data item in
memory, such as a variable or an array element. Pointer is a very useful tool of C programming as
it can help improve the programs efficiency and allow the user to handle unlimited amount of data.
Pointers are also closely associated with arrays and, therefore, provide an alternate way to access
individual array elements.
Variable are stored in the memory in one or more contiguous memory location. This depends
on the type of data. For example, a single char is stored in one byte of memory, an integer variable
will be stored in two bytes and floating point may require four contiguous memory locations.
Let’s consider a variable x. compiler immediately assigns a memory location after the variable
declaration. The address of variable x can be accessed using the expression &x, where & is a unary

CU IDOL SELF LEARNING MATERIAL (SLM)


Functions 171

operator called address operator, that evaluates the address of its operand. Now suppose the address
of x is assigned to another variable, px, i.e.,
px = &x;
This new variable, px, is called a pointer to x because it points to the location where x is
stored in memory. Thus px is referred to as pointer variable. The data item identified by x can also
be accessed by the expression *px, where * is a unary operator that operates on only a pointer
variable. Therefore, *px and x both identify the same data. The relationship between px and x is
shown in the diagram below:

Address of x Value of x

px x
Fig. 7.2: Pictorial Representation of Relationship between Pointer Variable and Variable

Defining a Pointer
The syntax for pointer declaration is
data-type *pt_var
where pt_var is the name of the pointer variable and data-type refers to the data type of the pointer.
(Note: Remember that an asterisk must precede pt_var)
For example, consider the following snippet for pointer declaration
int x, y; //integer variable declaration
int *ptr_x; // integer pointer declaration
The variable ptr_x is declared as pointer variable that can point to a integer quantity. Note that
ptr_x represents an address, not a floating-point quantity.

Pointer Initialization and Pointer Assignment


A pointer variable can be initialized by assigning it the address of another variable during
pointer variable declaration. Remember that the variable whose address is assigned to the pointer
variable must have been declared earlier in the program:
Consider the following pointer declaration
int x, y; //integer variable declaration
int *ptr_x = &x; //integer pointer declaration and initialization

CU IDOL SELF LEARNING MATERIAL (SLM)


172 Computer Programming

We have used arguments to send values to the called function, in the same way we can also
use arguments to send back information to the calling function. The arguments that are used to send
back data are called Output Parameters.
It is a bit difficult for a novice because this type of function uses a pointer. Let’s see an
example:
#include<stdio.h>
#include<conio.h>
void main()
{
int len,br,area,peri;
void areaperi(int l,int b,int *area,int *peri);
clrscr();
printf(“Enter length & breath\n”);
scanf(“ %d %d”,&len,&br, &area, &peri);
printf(“Area is %d”,*area);
printf(“permeter is %d”, *peri);
getch();
}
void areaperi(int l, int b, int *area, int *peri)
{
*area = l * b;
*peri = 2*(l+b);
}

Parameters are of two types


Formal arguments: While declaring a function, ie while specifying function prototype or
providing function signature, the arguments list of parameters we specify are known as formal
parameters. These formal parameters are also called dummy parameters and they are local variables

CU IDOL SELF LEARNING MATERIAL (SLM)


Functions 173

to a function also they are called as positional parameters, since their postion is fixed when passed
within a function. While passing formal parameters we have to specify data types.
Actual arguments: The parameter’s value (or arguments) we provide while calling a function
is known as actual arguments. These arguments are original or actual values of parameters which is
to be passed during function call. Actual parameters are also positional parameters. While passing
actual parameters we have to pass values of variables but we don’t have to pass data type of
parameters, we have to pass only arguments or its value.

For example

Example of C program containing a function that alters the value of its argument.
#include <stdio.h>
void modify ( int a); /* function prototype */
void main ( )
{
int a = 2;
printf( “ \n a = %d (from main, before calling the function ) “, a );
modify(a);
printf( “ \n a = %d (from main, after callig the function) “, a ) ;
getch();
}
void modify (int a)
{
a *= 3;
printf ( “ \n a = %d (from the function, after being modified)”, a ) ;
return;
}
The value of a variable is assigned with value is 2, original value of a (i.e., a = 2) is displayed
when main begins execution. This value is then passed to the function modify, i.e., actual parameter
a value will be passed to formal parameter of modify function, where it is multiplied by 3 in modify

CU IDOL SELF LEARNING MATERIAL (SLM)


174 Computer Programming

function and the new value displayed after modification since function does not have return value.
Note that it is the altered value of the formal argument that is displayed within the function. Finally,
the value of a within main (i.e., the actual argument) is again displayed, after control is transferred
back to main from modify.
When the program is executed, the following output is generated.
a = 2 (from main, before calling the function)
a = 6 (from the function, after being modified)
a = 2 (from main, after calling the function)
These results show that a is not altered within main, even though the corresponding value of
a is changed within modify.
Passing an argument by value has the following advantages and disadvantages :
Advantage: It allows a single valued actual argument to be written as an expression rather
than being restricted to a single variable.
Moreover, if the actual argument is expressed simply as a single variable, it protects the value
of this variable from alterations within the function.
Disadvantage: It does not allow information to be transferred back to the calling portion of
the program via arguments. Thus, passing by value is restricted to a one-way transfer of information.

Fig. 7.3: Pictorial Representation of Formal and Actual Partameters

CU IDOL SELF LEARNING MATERIAL (SLM)


Functions 175

7.4 Return Statement


Like variable and an array, a function must also be declared before it is called. A function
declaration tells the compiler about a function name and how to call the function.

Function Definition
1. Function Definition is a body of the function written outside the main function.
2. The function definition has a function header statement with a body of statements
enclosed within { and }
3. Function definition has two main components: (1) First Line Function Header (2) Body
of function enclosed with { }
4. The First Header statement consists of type specification of the value returned by the
function followed by function name and followed by ( )
5. Within ( ) round brackets either can be empty or it can have parameters or arguments
with data type of each argument
The Syntax of function definition is:
return_type function_name (no. of parameters/arguments with data types)
{
c statement; // Block code of statements //
c statement;
return statement;
}
 Return_type: Every function returns a value after execution of block of statements,
Return type can be of any data type such as int, double, char, void, short etc. Normally
function return type is any datatype but if function does not return any value then we
have to specify with void keyword to indicate function returns null value.
 Function_name: Function name should be valid identifier and function name should
be a meaningful name so that it can be easy to understand the purpose of function just
by seeing its name.

CU IDOL SELF LEARNING MATERIAL (SLM)


176 Computer Programming

 Argument list/parameter list (type arg1, type arg2): Arguments are also called
parameters, parameter list contains variables names along with their data types. These
arguments are positional formal/dummy parameters whose value can be replaced with
actual parameter during function call. For example – A function which is used to add
three integer variables, will have three integer argument. All arguments are to be specified
along with data type and are separated by commas.
 Block of code: It is a Set or Block of C statements, which will be executed during
function call. Function definition execution will be performed in a stack.
If function has return type, then return statement will be the last statement of a block
and if function has no return type, i.e., void then this function will have a no return
statement.
Let us assume on example to solve the problem of function.

Function Definition of sum of two numbers with Return type:


int sum (int a, int b)
{
int c;
c = a + b;
return c;
}

Function definition of even number checking with no return type hence void:
void even (int a)
{
if (a%2 = = 0)
printf(“a is even”);
else
printf(“a is odd”);
}

CU IDOL SELF LEARNING MATERIAL (SLM)


Functions 177

Functions with arguments with return type


In this type when function is called within a main function then function can send arguments
from the calling function to the called function and wait for the result to be returned back from the
called function back to the calling function. The argument values will be evaluated by called function
and result will be returned to calling function.
This program has sum as a user defined function, during the call of this function values of x
and y are passed from calling function to user defined function sum into a and b variables. The
result of addition will be stored in r variable within called function and return back to calling
function and stored in z variable. Further processing of printing of result will be done in main
function.

Example of sum of two numbers using function


#include<stdio.h>
#include<conio.h>
void main()
{
int sum(int, int);
int x,y,z;
clrscr();
printf(“Enter two numbers\n”);
scanf(“%d %d”,&x, &y);
z = sum(x,y);
printf(“\nThe sum of two numbers is %d.”,z);
getch();
}
int add(int a, int b)
{
int r;
r = a+b;

CU IDOL SELF LEARNING MATERIAL (SLM)


178 Computer Programming

return r;
}
Pictorial representation of function with arguments and return type.

Functions with arguments that return multiple values


So far, we have learned and seen that in a function, return statement was able to return only a
single value. That is because; a return statement can return only one value. But if we want to send
back more than one value then how could we do this?
We have used arguments to send values to the called function, in the same way we can also
use arguments to send back information to the calling function. The arguments that are used to send
back data are called Output Parameters.
It is a bit difficult for a novice because this type of function uses a pointer. Let’s see an
example:
#include<stdio.h>
#include<conio.h>
void main()
{
int len,br,area,peri;
void areaperi(int l,int b,int *area,int *peri);
clrscr();
printf(“Enter length & breath\n”);
scanf(“ %d %d”,&len,&br, &area, &peri);
printf(“Area is %d”,*area);
printf(“permeter is %d”, *peri);
getch();
}
void areaperi(int l, int b, int *area, int *peri)
{

CU IDOL SELF LEARNING MATERIAL (SLM)


Functions 179

*area = l * b;
*peri = 2*(l+b);
}

7.5 Calling a Function by Passing Values


In C programming language call by value and call by reference (also known as pass-by-value
and pass-by-reference). These methods are different ways of passing (or calling) data to functions.
In call by value while
In call by reference while
Call by value and call by reference function parameters can be passed by two ways:
1. Call by value (function call we pass values of variables)
2. Call by reference (function call we pass reference or address of variables)

Call by Value
If data is passed by value, the data is copied from the variable used in for example main() to a
variable used by the function. So if the data passed (that is stored in the function variable) is
modified inside the function, the value is only changed in the variable used inside the function.
Let’s take a look at a call by value example:
1. Call by value: Function call has number of different parameters, the value of these parameters
is passed to formal parameters hence the value of actual parameters passed to formal parameters
are called call by value. In this function call passes arguments by value. The called function creates
a new set of variables.
Function prototype statement is:
void call_by_value(int x)
Function call statement is:
call_by_value(a);
Function definition is:
void call_by_value(int x)
{

CU IDOL SELF LEARNING MATERIAL (SLM)


180 Computer Programming

printf(“Inside call_by_value x = %d before adding 10.\n”, x);


x += 10;
printf(“Inside call_by_value x = %d after adding 10.\n”, x);
}

Program:
# include <stdio.h>
void call_by_value(int x)
{
printf(“Inside call_by_value x = %d before adding 10.\n”, x);
x += 10;
printf(“Inside call_by_value x = %d after adding 10.\n”, x);
}
void main()
{
int a=20;
printf(“a = %d before function call_by_value.\n”, a);
call_by_value(a);
printf(“a = %d after function call_by_value.\n”, a);
getch();
}

The output of the program:


a = 10 before function call_by_value.
Inside call_by_value x = 20 before adding 10.
Inside call_by_value x = 30 after adding 10.
a = 20 after function call_by_value.
In the main() we create a variable of integer type that has the value of 0. Starting value of a we
are printing then function call_by_value is called and we input the variable a. This variable (a) is

CU IDOL SELF LEARNING MATERIAL (SLM)


Functions 181

then copied to the function variable x. In the function we add 10 to x (and also call some print
statements). Then when the next statement is called in main() function the value of variable a is
printed. We can see that the value of variable a isn’t changed by the call of the function
call_by_value().
2. Call by reference: In this function, declaration and definition parameters are passed by
reference. In this formal parameters of function definition become aliases to the actual arguments
in the calling function.
The call  by  reference method  of  passing  arguments  to  a  function  copies  the  address  of  an
argument into the formal parameter. Inside the function, the address is used to access the actual
argument used in the call. It means the changes made to the parameter affect the passed argument.
To pass a value by reference, argument pointers are passed to the functions just like any other
value. So accordingly you need to declare the function parameters as pointer types as in the following
function swap(),  which  exchanges  the  values  of  the  two  integer  variables  pointed  to,  by  their
arguments. The pointer variables are to be specified in function declaration and function definition.
/* function definition to swap the values */
void swap(int *a, int *b)
{
int temp;
temp = *a; /* save the value at address a */
*a = *b; /* put b into a */
*b = temp; /* put temp into b */
Return
}
Let us now call the function swap() by passing values by reference as in the following example
#include <stdio.h>
/* function declaration */
void swap(int *a, int *b);
void main ()

CU IDOL SELF LEARNING MATERIAL (SLM)


182 Computer Programming

{
/* local variable definition */
int x = 10;
int y = 20;
printf(“Before swap, value of x : %d\n”, x );
printf(“Before swap, value of y : %d\n”, y );
/* calling a function to swap the values.
* &x indicates pointer to x ie. address of variable x and
* &y indicates pointer to y ie. address of variable y.
*/
swap(&x, &y);
printf(“After swap, value of x : %d\n”, x );
printf(“After swap, value of y : %d\n”, y );
getch();
}

Output:
Before swap, value of x :10
Before swap, value of y :20
After swap, value of x :20
After swap, value of y :10

7.6 Recursive Function


Recursion is a process by which a function calls itself repeatedly, until some specified condition
has been satisfied. Function calling itself is Recursion.
The process is used for repetitive computations in which each action is stated in terms of a
previous result.
In C, Recursion is a programming technique that allows the programmer to express operations
in terms of themselves.
CU IDOL SELF LEARNING MATERIAL (SLM)
Functions 183

Recursion is a process by which action calls itself repeatedly, until some specified condition
has been satisfied. The process is used for repetitive computations in which each action is stated in
terms of a previous result. It is similar to looping. On the other hand, recursion makes it easier to
express ideas in which the result of the recursive call is necessary to complete the task.
A simple example of recursion would be:
void recurse()
{
recurse(); /* Function calls itself */
}
int main()
{
recurse(); /* Sets off the recursion */
return 0;
}
This program will not continue forever, however. The computer keeps function calls on a
stack and once too many are called without ending, the program will crash.

Recursive Function

Statem ents

TRUE
Condition

FALSE

Remaining Statem ents

STOP

Fig. 7.4: Flowchart Showing Recursion

CU IDOL SELF LEARNING MATERIAL (SLM)


184 Computer Programming

Example:
/* calculate the factorial of an integer quantity using recursion */
#include<stdio.h>
long int factorial(int n); / * function prototype */
void main( )
{
int n;
long int factorial(int n);
/* read in the integer value */
scanf(“‘%ld”, &n) ;
/ * calculate and display the factorial */
printf(“n! = %ld\n”, factorial(n));
getch();
}
/* function definition */
long int factorial(int n) / * calculate the factorial */
{
if (n <= 1)
return( 1 ) ;
else
return(n * factorial(n - 1));
}
The main portion of the program simply reads the integer quantity n and then calls the long-
integer recursive function factorial. The function factorial calls itself recursively, with an actual
argument (n - 1) that decreases in magnitude for each successive call. The recursive calls terminate
when the value of the actual argument becomes equal to 1.

CU IDOL SELF LEARNING MATERIAL (SLM)


Functions 185

Recursive Method

factorial(n)

Yes
n=1
factorial=1

Not

fact=n*factorial(n–1)
return fact

Fig. 7.5: Flowchart to Calculate Factorial of an Integer Quantity using Recursion

When the program is executed, the function factorial will be accessed repeatedly, once in
main and (n - 1) times within itself, though the person using the program will not be aware of this.
Only the final answer will be displayed; for example,
n! = 3628800
When a recursive program is executed, the recursive function calls are not executed
immediately. Rather, they are placed on a stack until the condition that terminates the recursion is
encountered.* The function calls are then executed in reverse order, as they are “popped” off the
stack. Thus, when evaluating a factorial recursively, the function calls will proceed in the following
order:
n! = n x (n - l)!
(n - l)! = (n - 1) x (n -2)!
(n - 2)! = (n - 2) x (n - 3)!
2! =2 x l!

CU IDOL SELF LEARNING MATERIAL (SLM)


186 Computer Programming

The actual values will then be returned in the following reverse order:
l! = 1
2! = 2 x l! = 2 x 1 = 2
3! = 3 x 2! = 3 x 2 =6
4! = 4 x 3! = 4 x 6 = 24
n!= n x (n- l)! = * - -
This reversal in the order of execution is a characteristic of all functions that are executed
recursively.

Fig. 7.6: Reversal in the Order of Execution

If a recursive function contains local variables, a set of local variables will be created during
each call. The names of the local variables will, of course, always be the same, as declared within
the function. However, the variables will represent a different set of values each time the function
is executed.

CU IDOL SELF LEARNING MATERIAL (SLM)


Functions 187

Each set of values will be stored on the stack, so that they will be available as the recursive
process “unwinds”, i.e., as the various function calls are “popped” off the stack and executed.

7.7 Summary
C functions are basic building blocks in every C program. We have given key points those to
be kept in mind for using existing C library functions and writing our own functions in a C program
efficiently.
 All C programs contain main() function which is mandatory.
 main() function is the function from where every C program is started to execute.
 Name of the function is unique in a C program.
 C Functions can be invoked from anywhere within a C program.
 There can any number of functions be created in a program. There is no limit on this.
 There is no limit in calling C functions in a program.
 All functions are called in sequence manner specified in main() function.
 One function can be called within another function.
 C functions can be called with or without arguments/parameters. These arguments are
nothing but inputs to the functions.
 C functions may or may not return values to calling functions. These values are nothing
but output of the functions.
 When a function completes its task, program control is returned to the function from
where it is called.
 There can be functions within functions.
 Before calling and defining a function, we have to declare function prototype in order
to inform the compiler about the function name, function parameters and return value
type.
 C function can return only one value to the calling function.
 When return data type of a function is “void”, then, it won’t return any values

CU IDOL SELF LEARNING MATERIAL (SLM)


188 Computer Programming

 When return data type of a function is other than void such as “int, float, double”, it
returns value to the calling function.
 main() program comes to an end when there is no functions or commands to execute.
 There are 2 types of functions in C. They are, 1. Library functions 2. User defined
functions

7.8 Key Words/Abbreviations


 Function declaration: A function declaration tells the compiler about a function's name,
return type, and parameters. A function definition provides the actual body of
the function.
 Function Call: If a function does not return a value (or if we are not interested in the
value returned by it), a function call takes the form of a C statement in which the function
call is  followed  by  a  semicolon  as  shown  below.  printf("Enter  values  of  a  and  b:  ");
scanf("%d %d", &a, &b);
 Function Definition: A function definition provides the actual body of the function.

7.9 Learning Activity


1. Explain Recursive function.
.......................................................................................................................................
.......................................................................................................................................
2. What is call by value and call by reference?
.......................................................................................................................................
.......................................................................................................................................

7.10 Unit End Questions (MCQ and Descriptive)

A. Descriptive Type: Short Answer Type Questions


1. Define function. What is the use of function?
2. How can you functions? Explain with example.

CU IDOL SELF LEARNING MATERIAL (SLM)


Functions 189

3. What are the advantages of function prototype in C?


4. What is the difference between function declaration and function definition?
5. How do you use parameters in C functions?
6. What are the types of functions?
7. How can you access function? Give example.
8. Explain block structure of function with diagram.
9. What are the two different ways to pass arguments?
10. Explain argument data types with its types.
11. What is recursion? Explain with example.
12. How is recursion use in function? Explain in detail.
13. Write a program in C to print factorial of a number using recursion.
14. Write a program in C to print Fibonacci series using recursion.
15. Write a program in C to print reverse of the string using recursion.

B. Multiple Choice/Objective Type Questions


1. Which of the following is a correct format for declaration of function?
(a) return-type function-name(argument type);
(b) return-type function-name(argument type){}
(c) return-type (argument type)function-name;
(d) all of the mentioned
2. The value obtained in the function is given back to main by using ________ keyword.
(a) return (b) static
(c) new (d) volatile
3. Which of the following function declaration is illegal?
(a) int 1bhk(int); (b) int 1bhk(int a);
(c) int 2bhk(int*, int []); (d) all of the mentioned

CU IDOL SELF LEARNING MATERIAL (SLM)


190 Computer Programming

4. Which is an indirection operator among the following?


(a) & (b) *
(c) -> (d) .
5. What will be the output of the following C code?
#include <stdio.h>
int main()
{
int i = 10;
void *p = &i;
printf("%d\n", (int)*p);
return 0;
}
(a) Compile time error (b) Segmentation fault/runtime crash
(c) 10 (d) Undefined behaviour
Answers: 1. (a), 2. (a), 3. (d), 4. (b), 5. (a)

7.11 References
1. https://beginnersbook.com/2014/01/c-functions-examples/
2. https://www.programiz.com/c-programming/c-functions.
3. https://publications.gbdirect.co.uk/c_book/thecbook.pdf
4. https://phy.ntnu.edu.tw/~cchen/ctutor.pdf



CU IDOL SELF LEARNING MATERIAL (SLM)


Pointers 191

UNIT 8 POINTERS

Structure:
8.0 Learning Objectives
8.1 Introduction
8.2 Fundamentals of Pointer
8.3 Pointer Variables
8.4 Referencing and Dereferencing
8.5 Pointer Arithmetic
8.6 Using Pointers with Arrays
8.7 Using Pointers with Strings
8.8 Arrays of Pointers
8.9 Pointers as Function Arguments
8.10 Functions Returning Pointers
8.11 Summary
8.12 Key Words/Abbreviations
8.13 Learning Activity
8.14 Unit End Questions (MCQ and Descriptive)
8.15 References

8.0 Learning Objectives


After studying this unit, you will be able to:
 Describe the concepts of pointers
 Elaborate the pointer to pointer concept

CU IDOL SELF LEARNING MATERIAL (SLM)


192 Computer Programming

 Differentiate between pointer to array and array of pointers


 Describe functions returning a pointer

8.1 Introduction
Introduction to C Pointers. A Pointer in C language is a variable which holds the address
of another variable of same data type. Pointers are  used  to  access  memory  and  manipulate  the
address. Pointers are one of the most distinct and exciting features of C language.

8.2 Fundamentals of Pointer


Variable values are stored in memory locations and every memory location has an address.
This memory address of a variable can be accessed using an ampersand (&) operator.

What are pointers?


A pointer is a variable that represents the location (rather than the value) of a data item in
memory, such as a variable or an array element. Pointer is a very useful tool of C programming as
it can help improve the programs efficiency and allow the user to handle unlimited amount of data.
Pointers are also closely associated with arrays, and therefore, provide an alternate way to access
individual array elements.
Variable are stored in the memory in one or more contiguous memory location. This depends
on the type of data. For example, a single char is stored in one byte of memory, an integer variable
will be stored in two bytes and floating point may require four contiguous memory locations.
Let’s consider a variable x, compiler immediately assigns a memory location after the variable
declaration. The address of variable x can be accessed using the expression & x, where & is a unary
operator called address operator, that evaluates the address of its operand. Now suppose the address
of x is assigned to another variable, px, i.e.,
px = &x;
This new variable, px, is called a pointer to x because it points to the location where x is
stored in memory. Thus px is referred to as pointer variable. The data item identified by x can also
be accessed by the expression *px, where * is a unary operator that operates on only a pointer

CU IDOL SELF LEARNING MATERIAL (SLM)


Pointers 193

variable. Therefore, *px and x both identify the same data. The relationship between px and x is
shown in the diagram below:

Address of x Value of x

px x

Fig. 8.1: Relationship between Pointer Variable and Variable

8.3 Pointer Variables

8.3.1 Defining and Declaration of a Pointer Variable


Pointer variables, like all other variables, must be declared before they may be used in a C
program. The interpretation of a pointer declaration differs; however, from the interpretation of
other variable declarations. When a pointer variable is declared, the variable name must be preceded
by an asterisk (*). This identifies the fact that the variable is a pointer. The data type that appears in
the declaration refers to the object of the pointer, i.e., the data item that is stored in the address
represented by the pointer, rather than the pointer itself.
The syntax for pointer declaration is
data-type *pt_var
where pt_var is the name of the pointer variable and data-type refers to the data type of the
pointer. (Note: remember that an asterisk must precede pt_var)
For example, consider the following snippet for pointer declaration
int x, y; //integer variable declaration
int *ptr_x; //integer pointer declaration
The variable ptr_x is declared as pointer variable that can point to a integer quantity. Note that
ptr_x represents an address, not a floating-point quantity.

8.3.2 Pointer Initialization and Pointer Assignment


A pointer variable can be initialized by assigning it the address of another variable during
pointer variable declaration. Remember that the variable whose address is assigned to the pointer
variable must have been declared earlier in the program.

CU IDOL SELF LEARNING MATERIAL (SLM)


194 Computer Programming

Consider the following pointer declaration:


int x, y; //integer variable declaration
int *ptr_x = &x; //integer pointer declaration and initialization
The variable ptr_x is declared as pointer variable that can point to a integer quantity. In addition,
the address of x is initially assigned to ptr_x
Similarly, the above declaration can be written as follows:
int x, y; //integer variable declaration
int *ptr_x; //pointer variable declaration
ptr_x = &x; //assigning address of x to ptr_x
Observe that an asterisk is not included in the assignment statement

8.3.3 Null Pointer


It is always a good practice to assign a NULL value to a pointer variable in case you do not
have an exact address to be assigned. This is done at the time of variable declaration. A pointer that
is assigned NULL is called a null pointer.
The NULL pointer is a constant with a value of zero defined in several standard libraries or
else it can be defined as a macro in the program.
Consider the following C Program:
#define NULL 0
int x, y;
int *ptr_x = NULL;
In the above example, ptr_x is initially assigned a value of 0. In most of the operating systems,
programs are not permitted to access memory at address 0 because that memory is reserved by the
operating system. However, the memory address 0 has special significance; it signals that the pointer
is not intended to point to an accessible memory location. But by convention, if a pointer contains
the null (zero) value, it is assumed to point to nothing. The program can check for NULL pointer
using the if statement like
if(ptr_x) //succeeds, if ptr_x is not null
if(!ptr_x) //succeeds, if ptr_x is null

CU IDOL SELF LEARNING MATERIAL (SLM)


Pointers 195

8.3.4 What Happens at Memory Level


Assume the following snippet for this example:
int x=50, y=45;
int *ptr_x;
ptr_x = &x;
y = *ptr_x;
x = ptr_x;
*ptr_x = 30;
Let’s see what happens in memory for each and every corresponding statement of the above
snippet in Fig. 8.2. Assume for the sake of this discussion that variable x resides at memory location
1450, y at 1560 and ptr_x at 2581. (Note A pointer is a variable and thus its values need to be stored
somewhere.)
Program snippet Memory
int x=50, y=45; Garbage value

int *ptr_x; x 50 y 45 ptr_x 4789


1450 1560 2581
ptr_x = &x; x 50 y 45 ptr_x 1450
1450 1560 2581
y = *ptr_x; x 50 y 50 ptr_x 1450
1450 1560 2581
x = ptr_x x 1450 y 50 ptr_x 1450
1450 1560 2581
*ptr_x = 30 x 30 y 50 ptr_x 1450
1450 1560 2581

Fig. 8.2: How Pointers Work at Machine Level (Memory)

The program starts by declaring the integer variables x and y; it also initializes them with 50
and 45 respectively. It later defines a pointer variable prt_x that is assigned the address of x. so
ptr_x gets loaded with the value 1450. Now y is assigned the contents of ptr_x. ptr_x currents

CU IDOL SELF LEARNING MATERIAL (SLM)


196 Computer Programming

points to memory location 1450, i.e., location of x. so y gets assigned to the value of x, i.e., 50. now
xi assigned with ptr_x, that itself, holds the address of x. so x gets loaded with its own address, i.e.,
1450. Finally, *ptr_x is assigned with 30. *ptr_x means value at the location pointed by ptr_x that
is x itself. So x gets loaded with 30.

8.4 Referencing and Dereferencing


Pointers are variables which points address of another variable used in C program, to access
the memory and manipulate the address, address is to referred with & operator and * sign can be
used as a notation to dereference the pointer.

Address in C
If you have a variable var in your program, &var will give you its address in the memory,
where & is commonly called the reference operator.
You must have seen this notation while using scanf() function. It was used in the function to
store the user inputted value in the address of var.
scanf(“%d”, &var);
/* Example to demonstrate use of reference operator in C programming. */
#include <stdio.h>
int main()
{
int var = 5;
printf(“Value: %d\n”, var);
printf(“Address: %u”, &var); //Notice, the ampersand(&) before var.
return 0;
}

Output:
Value: 5
Address: 2686778
Note: You may obtain different value of address while using this program.

CU IDOL SELF LEARNING MATERIAL (SLM)


Pointers 197

In above source code, value 5 is stored in the memory location 2686778. var is just the name
given to that location.

Reference Operator (&) and Dereference Operator (*)


& is called reference operator. It gives you the address of a variable.
Likewise, there is another operator that gets you the value from the address, it is called a
dereference operator (*).
Note: The * sign when declaring a pointer is not a dereference operator. It is just a similar
notation that creates a pointer.

Example: To Demonstrate Working of Pointers


/* Source code to demonstrate, handling of pointers in C program */
#include <stdio.h>
int main()
{
int* pc;
int c;
c=22;
printf(“Address of c:%u\n”,&c);
printf(“Value of c:%d\n\n”,c);
pc=&c;
printf(“Address of pointer pc:%u\n”,pc);
printf(“Content of pointer pc:%d\n\n”,*pc);
c=11;
printf(“Address of pointer pc:%u\n”,pc);
printf(“Content of pointer pc:%d\n\n”,*pc);
*pc=2;
printf(“Address of c:%u\n”,&c);
printf(“Value of c:%d\n\n”,c);

CU IDOL SELF LEARNING MATERIAL (SLM)


198 Computer Programming

return 0;
}

Output:
Address of c: 2686784
Value of c: 22
Address of pointer pc: 2686784
Content of pointer pc: 22
Address of pointer pc: 2686784
Content of pointer pc: 11
Address of c: 2686784
Value of c: 2

pc c pc c pc c pc c pc c
22 22 11 2

Line 4: int *pc, c; Line 5: c=22; Line 8: pc=&c; Line 11: c=11; Line 14: *p=2;

Fig. 8.3: Diagrammatically Representation of Flow of Program

8.5 Pointer Arithmetic


Pointer is a variable that holds the memory location, which is a number. This means that
arithmetic operations can be performed on pointer. The arithmetic operations that can be performed
on pointer is ++ (increment), – (decrement),+ (addition) and - (subtraction). Thus, an integer value
can be added to or subtracted from a pointer variable, though the resulting expression must be
interpreted very carefully. Suppose, for example, that ptr_x is a pointer variable that represents the
address of some variable x. We can write expressions such as ++ptr_x, - - ptr_x, (ptr_x + 3 ) , (ptr_x
+ i),and (ptr_x - i),where i is an integer variable. Each expression will represent an address that is
located some distance from the original address represented by ptr_x.

CU IDOL SELF LEARNING MATERIAL (SLM)


Pointers 199

Increment/Decrement
Consider an integer pointer variable ptr_x which points to the address 1450. Let’s increment
the variable (integer data size is 16 bit i.e. 2 bytes).
ptr_x++;
Now the pointer variable ptr_x will point to the location 1452 because each time ptr_x will be
incremented, it will point to the next integer location which is 2 bytes next to the current location.
If ptr_x points to a character whose address is 1000, then the above operation will point to the
location 1001 because the next character will be available at 1001.

Example:
void main()
{
int x = 45;
intptr_x = &x;
printf(“\nOriginal values: x = %d ptr_x = %d”, x, ptr_x);
ptr_x++;
printf(“\nValues after incrementing : x = %d ptr_x = %d”, x, ptr_x);
}
When the above code is compiled and executed, it produces the following result:
Original values: x = 45 ptr_x = 8945
Values after incrementing : x = 45 ptr_x = 8947
Similarly for decrement, it decreases pointer variables value by the number of bytes of its data
type.

Example
void main()
{
int x = 45;
intptr_x = &x;
printf(“\nOriginal values: x = %d ptr_x = %d”, x, ptr_x);

CU IDOL SELF LEARNING MATERIAL (SLM)


200 Computer Programming

ptr_x—;
printf(“\nValues after decrementing : x = %d ptr_x = %d”, x, ptr_x);
}
When the above code is compiled and executed, it produces the following result
Original values: x = 45 ptr_x = 8945
Values after incrementing : x = 45ptr_x = 8943

Addition/Subtraction
Consider the following example to demonstrate the addition operation on pointer, which can
be similarly considered for subtraction.
void main( )
{
int *ptr_i; /* pointer to an integer */
int i= 1;
ptr_i = & i ;
printf (“Value: i=%d \n\n”, i);
printf (“Address: &i=%X \n\n”, &i) ;
printf (“ Pointer value: ptr_i=%X ptr_i + l=%X ptr_i + 2=%X ptr_i + 3=%X” ptr_i,
ptr_i + 1, ptr_i + 2, ptr_i + 3 ) ;
}
This program displays the value and address associated to i, an integer variable. The program
also makes use of a pointer variable, ptr_i, which represents the address of i. The values of ptr_i,
ptr_i + 1, ptr_i + 2 and ptr_i + 3 are also displayed, so that they may be compared with the addresses
of the different variables.
Execution of the program results in the following output:
Value: i=1
Address: &i=7890
Pointer values: ptr_i=7890 ptr_i + 1=7892 ptr_i + 2=7894 ptr_i + 3=7896

CU IDOL SELF LEARNING MATERIAL (SLM)


Pointers 201

The first line simply displays the value of the variable, and the second line displays its addresses,
as assigned by the compiler. Notice the number of bytes associated with data item. The integer
value represented by i requires two bytes (specifically, addresses 7890 and 7891).
Now consider the third line of output, it contains the addresses represented by the pointer
expressions. Clearly, ptr_i represents the address of i (i.e., 7890). However, ptr_i + 1 moves over
only two bytes, to 7892,and ptr_i + 2 moves over another two bytes, to 7894, and so on. The reason
is pointer ptr_i points to an integer quantity that require 2bytes. Hence when integer constants are
added to ptr_i, the constant is treated as two-byte multiple. If ptr_i is defined as a pointer to a
different type of object (e.g., a character or a floating-point quantity), then any integer constant that
is added to or subtracted from the pointer will be interpreted differently. For example, if ptr_i
would be a floating point quantity then the integer constant would be treated as four-byte multiple.

Pointer Comparison
Pointer variables can be compared provided both variables are of the same data type. Such
comparisons can be useful when both pointer variables point to elements of the same array. The
comparisons can test for either equality or inequality. Moreover, a pointer variable can be compared
with zero (i.e., NULL).
Assume pt_x and pt_y are pointer variables that point to elements of the same array. Several
logical expressions involving these two variables are shown below. All of the expressions are
syntactically correct.
(pt_x<pt_y) Indicates whether or not the element associated with pt_x is ranked ahead of
the element associated with pt_y
(pt_x>= pt_y) Indicates whether or not the element associated with pt_x is ranked after the
element associated with pt_y
(pt_x == pt_y) Indicates whether or not the element associated with pt_x is equal to the
element associated with pt_y
(pt_x != pt_y) Indicates whether or not the element associated with pt_x is not equal to the
element associated with pt_y
(pt_x == NULL) Indicates whether or not the element associated with pt_x is equal to NULL

Fig. 8.4: Pointer Variable comparion with Comparison Operators

CU IDOL SELF LEARNING MATERIAL (SLM)


202 Computer Programming

8.6 Using Pointers with Arrays


Arrays and pointers are closely related in C Programming. An array name is really a pointer to
the first element in the array. This means that if x is an one-dimensional array, then the address of
first element of the array can be expressed as &x[0] or x. Even the address of second element of the
array can be written as x + 1 and so on. So the address of the ith element can be expressed as x + i.
Hence, the expression (x + i) is a symbolic representation for an address specification rather than
an arithmetic expression.
Since &x [i] and (x + i) both represent the address of the ith element of x, it would seem
reasonable that x [ i]and * (x + i)both represent the contents of that address, i.e., the value of the ith
element of x. This is indeed the case. The two terms are interchangeable. Hence, either term can be
used in any particular application. The choice depends upon your individual preferences.
Consider the following example:
void main()
{
int x[5] = {51, 42, 83, 14, 65};
int i;
//displaying array elements using x[i] and x + i approach
for(i=0;i<5;i++)
printf(“\n\n i = %d, x[%d] = %d and *(x + %d) = %d”, i, i, x[i], i, *(x+i));
}
This program defines a one-dimensional, 5-element integer array x. The action portion of the
program consists of a loop that displays the value. Note that the value of each array element is
specified in two different ways, as x[i] and as *(x + i), in order to illustrate their equivalence.
Therefore, the value and the address of each array element should appear twice. The above program
would generate the following output:
i = 0, x[0] = 51 and *(x + 0) = 51
i = 1, x[1] = 42 and *(x + 1) = 42
i = 2, x[2] = 83 and *(x + 2) = 83

CU IDOL SELF LEARNING MATERIAL (SLM)


Pointers 203

i = 3, x[3] = 14 and *(x + 3) = 14


i = 4, x[4] = 65 and *(x + 4) = 65
The above program can be written to display the address of each element. This is given as an
exercise to students. Just change the expression of array elements with an expression for address of
array of element as discussed above.
To assign a value to an array element, use the expression x[i] or *(x + i) in the LHS of the
assignment statement. On the other hand, it is sometimes necessary to assign an address to an
identifier. In such situations, a pointer variable must appear on the left side of the assignment
statement. It is not possible to assign an arbitrary address to an array name or to an array element.
Thus, expressions such as x, (x + i) and &x [i] cannot appear on the left side of an assignment
statement. Moreover, the address of an array cannot arbitrarily be altered, so expressions such as
++x are not permitted.
Let’s consider the following example:
void main()
{
floatvar[5] = { 5.5, 14.6, 5.8, 17.3, 8.9};
float *ptr_var;
int i;
ptr_var = var;
//Displaying array using a pointer
printf(“\n Original array:”);
for(i=0;i<5;i++)
printf(“*(ptr_var + %d) : %f \n”, i, *(ptr_var + %d));
}
In the above example, ptr_var is a pointer to float, which means it can store the address of a
variable of float type. Once the base address of the array is assigned into ptr_var, the array elements
can be accessed using *ptr_var, *(ptr_var + 1), *(ptr_var + 2) and so on.
When the above code is compiled and executed, it produces the following output:

CU IDOL SELF LEARNING MATERIAL (SLM)


204 Computer Programming

Original array: *(p + 0) : 5.5


*(p + 1) : 14.6
*(p + 2) : 5.8
*(p + 3) : 17.3
*(p + 4) : 8.9
However, the address of one array element cannot be assigned to some other array element.
This means the following statements are illegal:
&marks[13] = &marks[12];
But the value of one array element can be assigned to another through a pointer, if required
pt = &marks[21]; or pt = marks + 21;
marks[22] = *pt; *(marks + 22) = *pt
If a numerical array is defined as a pointer variable, the array elements cannot be assigned
initial values. Therefore, a conventional array definition is required if initial values will be assigned
to the elements of a numerical array. However, a character-type pointer variable can be assigned an
entire string as a part of the variable declaration. Thus, a string can conveniently be represented by
either a one-dimensional character array or a character pointer. This is clearly discussed in the
following example:
char x[] = “First statement \n “;
void main()
{
static char y[] = “Second statement \n “;
printf(“%s %s”, x,y);
}
The first string is assigned to the external array x[ ]. The second string is assigned to the static
array y[ ], which is defined within main. This second definition occurs within a function; therefore,
y[ ] must be defined as a static array so that it can be initialized.
The strings are now assigned to pointer variables rather than to one-dimensional arrays. Let’s
see that example

CU IDOL SELF LEARNING MATERIAL (SLM)


Pointers 205

char *x = “First statement \n “;


void main()
{
char *y = “Second statement \n “;
printf(“%s %s”, x,y);
}
The external pointer variable x points to the beginning of the first string, whereas the pointer
variable y, declared within main, points to the beginning of the second string. Note that y can now
be initialized without being declared static.
Output of either of the program would be
First statement
Second statement

8.7 Using Pointers with Strings


Pointer to Array of String: A pointer which pointing to an array which content is string, is
known as pointer to array of strings.

178 arr[4] 189

C \0 C + + \0 J a v a \0 V B A \0

178 189

ptr (*ptr) [4]

Fig. 8.5: Pointer Representation with Strings

CU IDOL SELF LEARNING MATERIAL (SLM)


206 Computer Programming

In this example
1. ptr : It is pointer to array of string of size 4.
2. array[4] : It is an array and its content are string.

1 : Printing Address of the Character Array


#include<stdio.h>
int main()
{
int i;
char *arr[4] = {“C”,”C++”,”Java”,”VBA”};
char *(*ptr)[4] = &arr;

for(i=0;i<4;i++)
printf(“Address of String %d : %u\n”,i+1,(*ptr)[i]);
return 0;
}

Output:
Address of String 1 = 178
Address of String 2 = 180
Address of String 3 = 184
Address of String 4 = 189

2. Printing Contents of Character Array


#include<stdio.h>
int main()
{
int i;
char *arr[4] = {“Kiran”,”KS”,”SK”,”Shri”};

CU IDOL SELF LEARNING MATERIAL (SLM)


Pointers 207

char *(*ptr)[4] = &arr;


for(i=0;i<4;i++)
printf(“String %d : %s\n”,i+1,(*ptr)[i]);
return 0;
}

Output:
String 1 = Kiran
String 2 = KS
String 3 = SK
String 4 = Shri

3. Pointer to String and Pre-increment Operator


#include<stdio.h>
int main()
{
int i;
char *arr[4] = {“C”,”C++”,”Java”,”VBA”};
char *(*ptr)[4] = &arr;
printf(“%s”,++(*ptr)[2]);
return 0;
}

Output:
ava

8.8 Arrays of Pointers


An array is a collection of variables belongings to the same data type. Similarly, an array can
also be defined as a collection of pointer variables. Since a pointer variable contains an address, an

CU IDOL SELF LEARNING MATERIAL (SLM)


208 Computer Programming

array of pointers would be a collection of addresses. The address present in the array of pointers
can be addresses of isolated variables or addresses of array elements or any other addresses.
Consider the following example:
void main()
{
int marks[] = {45, 55, 65, 35, 47};
int i, *pt[5]; // array of pointers
for(i=0;i<5;i++)
pt[i] = &marks[i]; // assigning the address of integers stored in integer array
for(i=0;i<5;i++)
printf(“Marks of student: \n %d \n”, *pt[i]);
}
For loop in the program picks up the addresses present in pt and prints the values present at
these addresses. This is shown in Fig. 8.6.
Array index marks[0] marks[1] marks[2] marks[3] marks[4]

marks 45 55 65 35 47

Mem loc 4789 4791 4793 4795 4797

Array index marks[0] marks[1] marks[2] marks[3] marks[4]

pt 4789 4791 4793 4795 4797

Mem loc 1254 1256 1258 1260 1262


Fig. 8.6: Arrangement of Array of Pointer in Memory

As discussed above, the array of pointers can contain address of isolated variables. That
exercise if left up to readers.

8.8.1 Multidimensional Arrays


A multidimensional array can be expressed in terms of an array of pointers rather than a
pointer to a group of contiguous arrays. In such situations, the newly defined array will have one
less dimension than the original multidimensional array. Each pointer will indicate the beginning
of a separate (n- 1)-dimensional array.
CU IDOL SELF LEARNING MATERIAL (SLM)
Pointers 209

In general terms, a two-dimensional array can be defined as a one-dimensional array of pointers


by writing
data-type (*pt_array)[ expression2 ] ;
instead of
data-type array[ expression1 ] [ expression2 ];
Notice the parentheses that surround the array name and the preceding asterisk in the pointer
version of each declaration. These parentheses must be present.
Suppose arr is a two-dimensional array with 10 rows and 30 columns then it can be declared
as follows
int (*arr)[30] instead of intx[10][30]
is defined to be a pointer to a group of contiguous, one-dimensional, 30-element integer arrays. arr
points to the first 30 elements i.e. row 0. Similarly arr+1 point to the second 30 elements i.e. row 1
and so on.
arr[10][30] and *arr[30] are both syntactically legal references to a single int. But arr is a true
two-dimensional array: 300 int-sized locations have been set aside, and the conventional rectangular
subscript calculation 30 * row + col is used to find the element a[row, col]. For *arr, however, the
definition only allocates 10 pointers and does not initialize them; initialization must be done explicitly,
either statically or with code. Assuming that each element of *arr does point to a thirty-element
array, then there will be 300 ints set aside, plus ten cells for the pointers. The important advantage
of the pointer array is that the rows of the array may be of different lengths. That is, each element
of *arr need not point to a thirty -element vector; some may point to two elements, some to fifty,
and some to none at all.
Now consider a three-dimensional floating-point array t. This array can be defined as
float (*t)[20][30] instead of float t[10][20][30]
t is defined as a pointer to a group of contiguous two-dimensional, 20 x 30 floating-point
arrays.

CU IDOL SELF LEARNING MATERIAL (SLM)


210 Computer Programming

8.9 Pointers as Function Arguments


Functions also take pointer as parameters. This allows the data items of the program inside
the calling function to be accessed, altered and then returned to the calling function with the new
changes reflected in the data item passed. This use of pointer is referred to as passing arguments by
reference (address/location). [recall: passing arguments by value discussed in the earlier chapter on
functions].
When an argument is passed by value, the data item is copied in function and any change done
to it is not reflected in the calling function. However, when an argument is passed by reference, the
address of the data item is passed into the function and any changes/alterations done will be reflected
in both the function and the calling function. Thus, the use of a pointer as a function argument
permits the corresponding data item to be altered globally from within the function.
When pointers are used as arguments to a function, formal pointer arguments must each be
preceded by an asterisk. Function prototypes are written in the same manner. In case the function
declaration does not include variable names, the data type of each pointer argument must be followed
by an asterisk.

Example:
void show_int(int x, int y);//function prototype
void show_int1(int *pt_x, int *pt_y);
void main()
{
int x = 56;
int y = 75;
printf(“\n Original values: x=%d, y=%d”, x, y);
show_int(x,y);
printf(“\n Values of x and y after calling show_int(): x=%d, y=%d”, x, y);
show_int1(&u, &v);
printf(“\n Values of x and y after calling show_int1(): x=%d, y=%d”, x, y);
}

CU IDOL SELF LEARNING MATERIAL (SLM)


Pointers 211

void show_int(int x, int y)


{
x=y=1;
printf(“\n\n Values of x and y inside show_int1(): x=%d, y=%d”, x, y);
}
show_int1(int *pt_x, int *pt_y)
{
*pt_x=*pt_y=1;
printf(“\n\n Values of x and y inside show_int1(): *pt_x=%d, *pt_y=%d”, *pt_x, *pt_y);
}
As seen in the above program, there are two functions show_int() and show_int1() which
accept two arguments. The first function show_int() accepts two integer arguments and modifies
their values to 1. But these changes are not reflected in the main(); as these arguments are passed by
value. The changes done to the arguments are local to the function in which the changes occur.
The second function show_int1() accepts two pointer to integer variable as its arguments. The
arguments are identified as pointers by the indirection operators (i.e., the asterisks) that appear in
the argument declaration. Here the contents of the pointer addresses are reassigned the values to 1.
Since the addresses are recognized in both show_int1() and main(), these changes are reflected in
the main().
The output is generated as follows when the program executes.
Original values: x=56, y=75
Values of x and y inside show_int1(): x=1, y=1
Values of x and y after calling show_int(): x=56, y=75
Values of x and y inside show_int1(): *pt_x=1, *pt_y=1
Values of x and y after calling show_int1(): x=1, y=1
Notice that the values of x and y are unchanged within main after the call to show_int(),
though the values of these variables are changed within main after the call to show_int1(). Thus,

CU IDOL SELF LEARNING MATERIAL (SLM)


212 Computer Programming

the output illustrates the local nature of the alterations within show_int(), and the global nature of
the alterations within show_int1().

8.10 Functions Returning Pointers


C also allows to return a pointer from a function. To do so, you would have to declare a
function returning a pointer as in the following example “
int * myFunction()
{
.
.
}
Second point to remember is that, it is not a good idea to return the address of a local variable
outside the function, so you would have to define the local variable as static variable.
Now, consider the following function which will generate 10 random numbers and return
them using an array name which represents a pointer, i.e., address of first array element.
A function can also return a pointer to the calling function. In this case you must be careful,
because local variables of function doesn’t live outside the function, hence if you return a pointer
connected to a local variable, that pointer be will pointing to nothing when function ends.
#include <stdio.h>
#include <conio.h>
int* larger(int*, int*);
void main()
{
int a=15;
int b=92;
int *p;
p=larger(&a, &b);
printf(“%d is larger”,*p);

CU IDOL SELF LEARNING MATERIAL (SLM)


Pointers 213

}
int* larger(int *x, int *y)
{
if(*x > *y)
return x;
else
return y;
}

Safe Ways to Return a Valid Pointer


1. Either use argument with functions. Because argument passed to the functions are
declared inside the calling function, hence, they will live outside the function called.
2. Or, use static local variables inside the function and return it. As static variables have
a lifetime until main() exits, they will be available throughout the program.

8.11 Summary
Pointers in C language is a variable that stores/points the address of another variable. A Pointer
in C is used to allocate memory dynamically, i.e., at run time. The pointer variable might be belonging
to any of the data type such as int, float, char, double, short etc.
A pointer is a variable that represents the location (rather than the value) of a data item in
memory, such as a variable or an array element. Pointer is a very useful tool of C programming as
it can help improve the programs efficiency and allow the user to handle unlimited amount of data.
Pointers are also closely associated with arrays, and therefore, provide an alternate way to access
individual array elements.
Pointer Variables contains the following points:
1. Defining and Declaration of a Pointer Variable
2. Pointer Initialization and Pointer Assignment
3. Null Pointer
4. What Happens at Memory Level

CU IDOL SELF LEARNING MATERIAL (SLM)


214 Computer Programming

& is called reference operator. It gives you the address of a variable.


Likewise, there is another operator that gets you the value from the address, it is called a
dereference operator (*).
Pointer to Array of String: A pointer which pointing to an array which content is string, is
known as pointer to array of strings.

8.12 Key Words/Abbreviations


 Reference Operator: The reference  operator noted  by  ampersand  ("&"),  is  also  a
unary operator in C languages that uses for assign address of the variables. It returns
the pointer address of the variable. This is called "referencing" operater.
 Dereference Operator: A dereference operator, also known as an indirection operator,
operates on a pointer variable. It returns the location value, or l-value in memory pointed
to by the variable's value. In the C programming language, the deference operator is
denoted with an asterisk (*).

8.13 Learning Activity


1. Explain Pointer Arithmetic
.......................................................................................................................................
.......................................................................................................................................
2. Explain Arrays of Pointers
.......................................................................................................................................
.......................................................................................................................................

8.14 Unit End Questions (MCQ and Descriptive)


A. Descriptive Type: Short Answer Type Questions
1. Explain how variables are represented in memory. How is the address of a variable
determined?
2. What is a pointer? What kind of information is represented by a pointer variable? Explain
with an example.
CU IDOL SELF LEARNING MATERIAL (SLM)
Pointers 215

3. What is the relationship between the address of a variable and the corresponding pointer
variable? Explain with the help of a diagram.
4. What is the relationship between the data item represented by a variable and the
corresponding pointer variable? Explain with the help of a diagram.
5. How is a pointer variable declared? What is the purpose of the data type included in the
declaration?
6. Explain the function prototype when it receives a pointer as an argument. Also explain
how the pointer argument is declared within the function definition.
7. What is the relationship between an array name and a pointer?
8. How can a one-dimensional array of pointers be used to represent a collection of strings?
Explain with an example.
9. Describe the two different ways to specify the address of an array element.
10. Describe the two different ways to access an array element.
11. Explain how functions returning pointer with suitable example.
12. Explain with suitable example how pointer variables can be passed as a function
arguments.
13. Explain array of pointers in detail with example.

B. Multiple Choice/Objective Type Questions


1. What is (void*)0?
(a) Representation of NULL pointer (b) Representation of void pointer
(c) Error (d) None of above
2. A pointer is
(a) A variable that stores address of an instruction
(b) A variable that stores address of other variable
(c) A keyword used to create variables
(d) None of these

CU IDOL SELF LEARNING MATERIAL (SLM)


216 Computer Programming

3. The reason for using pointers in a Cprogram is


(a) Pointers allow different functions to share and modify their local variables.
(b) To pass large structures so that complete copy of the structure can be avoided.
(c) Pointers enable complex “linked" data structures like linked lists and binary trees.
(d) All of the above
4. What do the following declaration signify?
char **argv;
(a) argv is a pointer to pointer.
(b)  argv is a pointer to a char pointer.
(c)  argv is a function pointer.
(d)  argv is a member of function pointer.
5. What do the following declaration signify?
char *arr[10];
(a) arr is a array of 10 character pointers.
(b) arr is a array of function pointer.
(c) arr is a array of characters.
(d) arr is a pointer to array of characters
Answers: 1. (a), 2. (b), 3. (d), 4. (b), 5. (a)

8.15 References
1. https://fresh2refresh.com/c-programming/c-pointer/
2. https://www.studytonight.com/c/pointers-in-c.php
3. C: The complete reference by Herbert Schildt.



CU IDOL SELF LEARNING MATERIAL (SLM)


Structure 217

UNIT 9 STRUCTURE

Structure:
9.0 Learning Objectives
9.1 Introduction
9.2 Basics of Structure
9.3 Declaration of Structure
9.4 Reading and Assignment of Structure Variables
9.5 Array of Structures
9.6 Arrays within Structures
9.7 Nested Structure
9.8 Structures and Pointers
9.9 Summary
9.10 Key Words/Abbreviations
9.11 Learning Activity
9.12 Unit End Questions (MCQ and Descriptive)
9.13 References

CU IDOL SELF LEARNING MATERIAL (SLM)


218 Computer Programming

9.0 Learning Objectives


After studying this unit, you will be able to:
 Describe the basics of structure
 Explain accessing structure members
 Elaborate structure with refence to array, function and pointer

9.1 Introduction
Structure is a user-defined datatype in C language which allows us to combine data of different
types together. Structure helps to construct a complex data type which is more meaningful. It is
somewhat similar to an Array, but an array holds data of similar type only. But structure on the
other hand, can store data of any type, which is practical more useful.

9.2 Basics of Structure


C Structure is a collection of different data types which are grouped together and each element
in a C structure is called member.
In a real world scenario, data items under consideration are a collection of things. These
collections of things can have its own attributes. A single structure might contain integer elements,
floating-point elements and character elements.
Consider a real world data “book”, which is a collection of things like title of book, author,
publisher, no. of pages, etc., all these informations are dissimilar, i.e., author is a string whereas no.
of pages is an integer. For dealing with such collections, C provides a data type called ‘structure’.
A structure gathers together, different atoms of information that comprise a given entity.

Uses of Structures in C
1. C Structures can be used to store huge data. Structures act as a database.
2. C Structures can be used to send data to the printer.
3. C Structures can interact with keyboard and mouse to store the data.
4. C Structures can be used in drawing and floppy formatting.
5. C Structures can be used to clear output screen contents.
6. C Structures can be used to check computer’s memory size, etc.

CU IDOL SELF LEARNING MATERIAL (SLM)


Structure 219

9.3 Declaration of Structure


Declaration of structure starts with struct keyword followed by structure name with list of
members enclosed in curly braces.
A single structure might contain integer elements, floating-point elements and character
elements or maybe combination of integer, float and character. Even, pointers, arrays and other
structures can be included as elements within a structure.
The individual structure elements are referred to as members.
Structure declaration is different and more complicated than array declaration, as individual
members also have to be defined.
struct tag{
member 1;
member 2;

member n;
};
Here, struct is a keyword, tag is the name that identifies the structure of this type, and member
1, member 2, … member n are the individual member declaration.
The member names within a particular structure must be distinct from one another, though a
member name can be the same as the name of a variable that is defined outside of the structure. A
storage class cannot be assigned to an individual member, and individual members cannot be
initialized within a structure type declaration.
Individual structure-type variables can be declared as follows:
storage-class struct tag variable 1, variable 2, … variable n;
where storage-class is an optional storage class specifier, struct and tag refer to the same as discussed
above and variable1, variabel2, … variable n are the structure variables to type tag. The composition
of structure is illustrated in the following diagram.

CU IDOL SELF LEARNING MATERIAL (SLM)


220 Computer Programming

struct struct name {

type varname ;

type varname ;

type varname ;

type varname ;

};

Fig. 9.1: Composition of a Nested Structure

Let’s take an example


struct book {
char title[20];
char author[40];
int no_of_pages;
float cost;
};
The above structure name is book. It contains four members: character array of 20 characters
(title [20]), character array of 40 characters (author [40]), an integer quantity (no_of_pages) and a
floating point quantity (cost).
To define structure variable of type book as follows:
struct book cprog, basicprog;
here two variables of type book are defined whose composition is identified by the tag account.
There is one more way in which the declaration of structure composition and structure variable
can be combined. This is shown below:
storage-class struct tag{
member 1;
member 2;

member n;

CU IDOL SELF LEARNING MATERIAL (SLM)


Structure 221

} variable 1, variable 2, . . ., variable n; // tag is optional


Let’s take an example
struct book {
char title[20];
char author[40];
int no_of_pages;
float cost;
} cprog, basicprog;
Thus cprog and basicprog are structure variables of type book. Because the declaration of
structure and structure variable is combined, tag can be eliminated.
Note the following points while declaring a structure type:
 The closing brace in the structure type declaration must be followed by a semicolon.
 It is important to understand that a structure type declaration does not tell the compiler
to reserve any space in memory. It only defines the ‘form’ of the structure.
 Usually structure type declaration appears at the top of the source code file, before any
variables or functions are defined. In very large programs they are usually put in a
separate header file, and the file is included (using the preprocessor directive #include)
in whichever program the structure type is required

Structure Padding in C
Many processors expect memory for variables to be aligned based on the size of the variable.
A ‘char’ of 1 byte can be allocated anywhere in memory like 0x5000 or 0x5001. And an ‘int’ of 4
bytes, must start at a 4-byte boundary like 0x5004 or 0x5008. The structure padding is automatically
done by the compiler to make sure all its members are byte aligned.
The size of the below structure is 16 bytes due to structure padding:
Struct dummy {
Char ch;
Int num;
Double temp;

CU IDOL SELF LEARNING MATERIAL (SLM)


222 Computer Programming

}
Here ‘char’ is only 1 byte but after 3 byte padding, the number starts at 4 byte boundary. For
‘int’ and ‘double’, it takes up 4 and 8 bytes respectively.

The compiler used the 3 wasted bytes (marked in red) to pad the structure so that all the other
members are byte aligned. Now, the size of the structure is 4 + 1 +3 = 8 bytes. The size of the entire
structure is 8 bytes. On knowing the structured padding, it is easier to redesign or rewrite the
structure.
Let’s look at another example where the syntax is slightly different;

CU IDOL SELF LEARNING MATERIAL (SLM)


Structure 223

#include<stdio.h>
Struct dummy {
Int num;
Double x;
Float f;
};
Struct dummy1 {
Double x;
Int num;
Float f;
};
Int main()
{
Printf(“size:%d %d
”, sizeof(struct dummy ), sizeof(struct dummy1));
System(“PAUSE”);
Return 0;
}
The output will be as shown below;

9.4 Reading and Assignment of Structure Variables


Individual members of a structure variable can be assigned initial values in the same way as
the elements of an array. The initial values must appear in the order in which they will be assigned
to their corresponding structure members, enclosed in braces and separated by commas. The general
form is
CU IDOL SELF LEARNING MATERIAL (SLM)
224 Computer Programming

storage-class struct tag variable = {value 1, value 2, . . ., value tn);


where value1 refer to the value of first member, value2 refer to the value of second member and so
on.
Taking an example for initializing the above defined structure book.
struct book cprog = {“Introduction to C Programming”, “Kiran Gurbani”, 569, 499.55};
cprog is a structure instance variable of type book, whose members are assigned initial values. The
first member (title) is assigned the string “Introduction to C Programming”, the second member
(author) is assigned the string “Kiran Gurbani”, the third member (no_of_pages) is assigned the
integer value 569 and the fourth member (cost) is assigned the floating-point value 499.55.
The members of a structer can be accessed and processed separately. It can be accessed by
writing the following statement:
instance variable. member
where instance variable refers to the structure type variable and member refers to the name of the
member. Note that the period (.) that separates the variable name from the member name.
Consider the following structure:
struct book
{
char title[20];
char author[40];
int no_of_pages;
float cost;
} cprog;
Here the structure instance variable is cprog and to access the cprog’s title and author name
use the following code
cprog.title
cprog.author
The period operator has the highest precedence. Hence the operator will take precedence over
the unary operator as well as the other binary operators. Which means, the expression of the form

CU IDOL SELF LEARNING MATERIAL (SLM)


Structure 225

++variable. member is equivalent to ++(variable. member); i.e., the ++ operator will apply to the
structure member, not the entire structure variable.
Similarly, the expression and instance variable.member is equivalent to & (variable. member);
thus, the expression accesses the address of the structure member, not the starting address of the
structure variable.

Structure Assignment
Normally, can structure variables be treated similar to any regular variables? Especially, when
the value of one structure variable needs to be assigned to other. Well it is a complicated task. Let’s
try to understand. Consider the following structure definition.
struct car
{
char manufacturer[50];
char model[10];
int cost;
};
If two variables c1and c2, structure variables of type car, are to be assigned to each other then
there are three different ways in which it can be done
(i) Assign the members one by one
c1.manufacturer = c2.manufacturer
c1.model = c2.model
c1.cost = c2.cost
(ii) Copy the whole memory contents of c2 to c1
memcpy(&c1,&c2,sizeof(c1));
(iii) Straight assignment using ‘=’
c1=c2;
As shown above, it would be stupid programming if the programmer uses the first approach.
So obviously they would prefer using the 2nd or the 3rd way of structure assignment. But what is
the difference? Is there any drawback?

CU IDOL SELF LEARNING MATERIAL (SLM)


226 Computer Programming

Copying the structure variables using the straight assignment ‘=’ technique is probably the
best as it’s shorter, easier to read and has higher level of abstraction. While the other technique is
more compiler friendly, it just copies the memory of the size specified. This requires the reader to
think about the size argument to copy. When doing a straight assignment, there is no hesitation
about whether or not the size is correct.
The dangerous part of structure assignment is when the structure element is a pointer. Copying
structures that contain pointers can be a bit dangerous, since by doing so those pointers are aliased,
typically making it ambiguous who owns the pointer after the copying operation. If the structure
has char * pointing to a specific string, both structures will point to the same string. Changing the
contents of one of those string fields will change the other as well.
To overcome this, copy the entire contents of the structure and then deep copy the string by
effectively giving a separate string to each structure.
Thing to remember while using structure assignment
 Recommend using straight assignment ‘=’ instead of memcpy.
 If structure has pointer or array member, please consider the pointer alias problem, it
will lead to dangling pointer once incorrect use. Better way is to implement structure
assignment function in C

9.5 Array of Structures


Structure is used to store the information of one particular object but if we need to store such
100 objects then Array of Structure is used.
What is meant by array of structures? It is an array in which each element is a structure itself.
Let’s understand thus using an example
struct author
{
char first_name[15];
char last_name[15];
};
struct book

CU IDOL SELF LEARNING MATERIAL (SLM)


Structure 227

{
char title[20];
struct author book_author;
int no_of_pages;
float cost;
} books[50];
In this declaration books is a 50 elements array of structure. Each element of books is a
separate structure to type book. Each structure of type book in turn includes an array (title) and
another structure (author) as members. This shows how an array and a structure in embedded in
another structure, which itself is an element of an array.
An alternate way to define an array of structure book is shown below
struct author
{
char first_name[15];
char last_name[15];
};
struct book
{
char title[20];
struct author book_author;
int no_of_pages;
float cost;
};
struct book books[50];
an array of structure can be initialized just the way as any other array. Consider the following
declarations

CU IDOL SELF LEARNING MATERIAL (SLM)


228 Computer Programming

struct author
{
char first_name[15];
char last_name[15];
};
struct author author_list[]={ “Kiran”, “Gurbani”}
As seen in this example, the size of the array of structure is not specified. The initial values
will define the size of the array and amount of memory required to store the array.
The use of the period operator can be extended to arrays of structures, by writing array
[expression] .member where array refers to the array name, and array [expression] is an individual
array element (a structure variable). Therefore, array [expression], member will refer to a specific
member within a particular structure.
For the above example, author_list is an array of structures of type author. To access its
second element use the expression author_list[1].
Let’s consider the following example:
struct author
{
char first_name[15];
char last_name[15];
};
struct book
{
char title[20];
struct author book_author;
int no_of_pages;
float cost;
}books[5];

CU IDOL SELF LEARNING MATERIAL (SLM)


Structure 229

The following table gives expression showing how the various members and submembers of
the structure variable can be accessed.
Expression Explanation
book[1].title Access the title member for the second book
&book[1].title Access the address of title member within the second book structure
book[1].title[3] Access the 3rd character within book’s title
book[1].book_author.first_name Access the first_name member of structure of type author within
the structure book
++book[1].no_of_pages Causes the value of no_of_pages to increment

Fig. 9.2: Expressions of Structure

The following program explains all the aspect of array of structures.


struct student
{
int id;
char name[30];
float percentage;
};
void main()
{
int i;
struct student data[2];
// 1st student’s data
data [0].id=1;
strcpy(data [0].name, “Prem”);
data[0].percentage = 68.5;
// 2nd student’s data
data[1].id=2;
strcpy(data[1].name, “Dheeraj”);

CU IDOL SELF LEARNING MATERIAL (SLM)


230 Computer Programming

data[1].percentage = 89.5;
// 3rd student’s data
data[2].id=3;
strcpy(data[2].name, “Swapnil”);
data[2].percentage = 77.5;
for(i=0; i<3; i++)
{
printf(“ Records of STUDENT : %d \n”, i+1);
printf(“ Id is: %d \n”, data[i].id);
printf(“ Name is: %s \n”, data[i].name);
printf(“ Percentage is: %f\n\n”, data[i].percentage);
}
getch( );
}
Output of the above program is
Records of STUDENT : 1
Id is: 1
Name is: Prem
Percentage is: 68.500000
Records of STUDENT : 2
Id is: 2
Name is: Dheeraj
Percentage is: 89.500000
Records of STUDENT : 3
Id is: 3
Name is: Swapnil
Percentage is: 77.500000

CU IDOL SELF LEARNING MATERIAL (SLM)


Structure 231

9.6 Arrays within Structures


Structure is a collection of different data types. As discussed earlier, Structures can contain an
array as its member. Lets once again see the declaration of structure that contains an array within
the structure
struct tag{
data-type var1;
data-type arr[size];
...
data-type varN;
};
Here, struct is a keyword, tag is the name that identifies the structure of this type, and var1,
arr[size], … varN are the individual member declaration. arr[size] is an array of element whose size
is identified by size
//structure variable declaration
struct tag object;
This would define a structure variable object of type tag.

Example:
//structure declaration
struct month
{
int num_of_days;
char name[4];
};
void main()
{
struct month this_month = { 31, “Jan” };
printf(“The month is %s\n”, this_month.name );

CU IDOL SELF LEARNING MATERIAL (SLM)


232 Computer Programming

}
Alternate way to define the array is explained in the following array:
//structure declaration
struct month
{
int num_of_days;
char name[4];
};
void main()
{
this_month.num_of_days = 31;
strcpy( this_month.name, “Jan” );
printf(“The month is %s\n”, this_month.name );
}

Example of Structures Containing Arrays


struct Student
{
int roll_No;
char name[40];
int marks[5];
int total;
float percentage;
};
void main()
{
int i;

CU IDOL SELF LEARNING MATERIAL (SLM)


Structure 233

struct Student s;
printf(“\nEnter Student Roll No: “);
scanf(“%d”, &s.roll_No);
printf(“\n Enter Student Name: “);
scanf(“%s”, &s.name);

s.total = 0;
for(i=0; i<5; i++)
{
printf(“\n Enter Marks %d:”, i+1);
scanf(“%d”, &s.marks[i]);
s.total = s.total + s.marks[i];
}
s.percentage = (s.total/500)*100;
printf(“\n Roll No: %d”,s.roll_No);
printf(“\n Name: %d”,s.Name);
printf(“\n Marks in 5 subjects: %d %d %d %d %d”, s.marks[0], s.marks[1], s.marks[2],
s.marks[3], s.marks[4])
printf(“\n Total: %d”,s.total);
printf(“\n Percentage: %d”,s.percentage);
}

Output:
Enter Student Roll No : 51
Enter Student Name : sravan
Enter Marks 1: 55
Enter Marks 2: 56
Enter Marks 3: 74

CU IDOL SELF LEARNING MATERIAL (SLM)


234 Computer Programming

Enter Marks 4: 81
Enter Marks 5: 45
Roll No: 51
Name: sravan
Marks in 5 subjects: 55 56 74 81 45
Total: 311
Percentage: 62.20000

9.7 Nested Structure


Nested structure in C is nothing but structure within structure. One structure can be declared
inside other structure as we declare structure members inside a structure.
As the complexity of real world data items increases, it may happen that a structure variable
would be defined as a member of another structure. In such situations, the declaration of the embedded
structure must appear before the declaration of the outer structure. This is also called nested structure.
Let’s consider an example
struct author{
char first_name[15];
char last_name[15];
};
struct book {
char title[20];
struct author book_author;
int no_of_pages;
float cost;
} cprog, basicprog;
The second structure (book) now contains another structure (author) as one of its members.
Note that the declaration of author precedes the declaration of book. The composition of nested
structure can be illustrated in the following diagram:

CU IDOL SELF LEARNING MATERIAL (SLM)


Structure 235

struct struct name {

struct struct name {

type varname ;

type varname ;

};

type varname

type varname

};
} varname ;

Fig. 9.3: Composition of Nested Structure

Taking an example for initializing the above defined structure book.


struct book cprog = {“Introduction to C Programming”, “Kiran”, “Gurbani”, 569, 499.55};
cprog is a structure variable of type book, whose members are assigned initial values. The
first member (title) is assigned the string “C Programming”, the second member (author) is itself a
structure that contain two string members (first_name and last_name). Therefore, it will be assigned
the string “Kiran” and “Gurbani”. The third member (no_of_pages) is assigned the integer value
569 and the fourth member (cost) is assigned the floating-point value 499.55.
It’s already seen how a structure member can be accessed using the (.) period operator. The
repeated use of the period operator can also be used when a structure member itself is a structure
shown below:
variable.member.submember
where member refers to the name of the member of the outer structure and submember refers to the
name of the member of the nested structure (which will be shortly addressed).
Similarly if the structure member is an array then it can be accessed as follows
variable.member[expression]
where expression indicates the non-negative value that identifies the array element.

CU IDOL SELF LEARNING MATERIAL (SLM)


236 Computer Programming

Let’s consider the same example


struct author{
char first_name[15];
char last_name[15];
};
struct book {
char title[20];
struct author book_author;
int no_of_pages;
float cost;
} cprog,basicprog;
book_author is the member of the structure, which in turn is a structure of type author. To
access the first_name member of book_author use
cprog.book_author.first_name
Similarly,
cprog.book_author.no_of_pages
This value can be incremented by witing
++cprog.book_author.first_name
The first member title is a character array. The fourth element of this array, can be access by
using
cprog.title[3]
Structure members can be processed in the same manner as ordinary variables of the same
data type. Single-valued structure members can appear in expressions, they can be passed to functions,
and they can be returned from functions, as though they were ordinary single-valued variables.
Complex structure members are processed in the same way as ordinary data items of that same
type.

CU IDOL SELF LEARNING MATERIAL (SLM)


Structure 237

What does this imply? Structure members which are arrays can be processed in the same
manner as an ordinary array. Structure member that is a structure can be processed on member at a
time in the same manner as any other structure. These operations are shown below
Consider the structure
struct author{
char first_name[15];
char last_name[15];
};
struct book {
char title[20];
struct author book_author;
int no_of_pages;
float cost;
} cprog;
Several operations to access structure members
cprog.no_of_pages=455;
This statement assigns the value of 455 to cprog.no_of_pages
printf(“Book title is %s”, cprog.title);
This statement passes the array cprog.title to the printf function, so that it could be printed on
console.
printf(“Author’s name %s %s”, cprog.book_author.first_name,Prog.book_author.first_name);
This statement passes two arrays cprog.book_author.first_name and cprog.book_author
last_name to the printf function, both of which are submembers of structure cprog, so that it could
be printed on console.

CU IDOL SELF LEARNING MATERIAL (SLM)


238 Computer Programming

9.8 Structures and Pointers


This program explains how to use structure within structure in C using pointer variable.
“student_college_detail’ structure is declared inside “student_detail” structure in this program. one
normal structure variable and one pointer structure variable is used in this program.
Note that combination of .(dot) and ->(arrow) operators are used to access the structure
member which is declared inside the structure.
#include <stdio.h>
#include <string.h>
struct student_college_detail
{
int college_id;
char college_name[50];
};
struct student_detail
{
int id;
char name[20];
float percentage;
// structure within structure
struct student_college_detail clg_data;
}
stu_data, *stu_data_ptr;

void main()
{
struct student_detail stu_data = {1, “Raju”, 90.5, 71145,
“Anna University”};

CU IDOL SELF LEARNING MATERIAL (SLM)


Structure 239

stu_data_ptr = &stu_data;

printf(“ 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(“ College Id is: %d \n”, stu_data_ptr->clg_data.college_id);
printf(“ College Name is: %s \n”, stu_data_ptr->clg_data.college_name);
getch( );
}

Output:
Id is: 1
Name is: shruti
Percentage is: 90.500000
College Id is: 71145
College Name is: Mumbai University

9.9 Summary
When you design a program, it is important to choose an optimal way to represent the data
that the program processes. In simple cases, scalar variables and arrays are sufficient. However, in
practical programming context, you need a new form of variable that reflects the real world. For
example, in your program, you may want to refer to an address that holds multiple fields including
house number, street, zip code, state and country.
C provides a special kind of variable called structure. C structure allows you to wrap related
variables that has different data types into a single variable. A structure can contain any valid data
types such as int,char,float,array,pointer or even other structures. Each variable in the structure is
called structure member.

CU IDOL SELF LEARNING MATERIAL (SLM)


240 Computer Programming

9.10 Key Words/Abbreviations


Formatting: Prepare (a storage medium) to receive data.
Structure: It is a user-defined data type of C language which allows us to combine data of
different types together.

9.11 Learning Activity


1. What are the uses of structure?
.......................................................................................................................................
.......................................................................................................................................
2. Explain array of structure.
.......................................................................................................................................
.......................................................................................................................................

9.12 Unit End Questions (MCQ and Descriptive)

A. Descriptive Type: Short Answer Type Questions


1. What is a structure? Give its definition and explain with an example.
2. Explain how structure can be initialized.
3. How is a structure member accessed? How can a structure member be processed?
4. What is a structure? Explain what can be a structure member and how can they be
accessed.
5. Explain the (.) and (->) operators that can be applied onto a structure.
6. Can one structure be assigned to another? If yes, explain how it can be done. Also
mention its advantage and disadvantage.
7. Write a note on nested structure.
8. What is main advantage of using nested structure? Give an example.
9. How is an array of structure initialized?

CU IDOL SELF LEARNING MATERIAL (SLM)


Structure 241

10. Can array be a member of structure? If yes explain.


11. How is an array of structures defined? Give its syntax and explain.

B. Multiple Choice/Objective Type Questions


1. Which of the following operators can be applied on structure variables?
(a) Equality comparison ( == ) (b) Assignment ( = )
(c) Both of the above (d) None of the above
2. Which of the following cannot be a structure member?
(a) Another structure (b) Function
(c) Array (d) None of the mentioned
3. What is the output of this C code?
#include <stdio.h>
struct student
{
int no;
char name[20];
}
void main()
{
struct student s;
s.no = 8;
printf("hello");
}
(a) Compile time error (b) Nothing
(c) hello (d) Varies
4. What is the output of this C code?
#include <stdio.h>
void main()

CU IDOL SELF LEARNING MATERIAL (SLM)


242 Computer Programming

{
struct student
{
int no;
char name[20];
};
struct student s;
s.no = 8;
printf("%d", s.no);
}
(a) Nothing (b) Compile time error
(c) Junk (d) 8
5.
#include<stdio.h>
struct Point
{
   int x, y, z;
};
int main()
{
   struct Point p1 = {.y = 0, .z = 1, .x = 2};
   printf("%d %d %d", p1.x, p1.y, p1.z);
   return 0;
}
(a) Compiler Error (b) 2 0 1
(c) 0 1 2 (d) 2 1 0
Answers: 1. (b), 2. (b), 3. (a), 4. (d), 5. (b)

CU IDOL SELF LEARNING MATERIAL (SLM)


Structure 243

9.13 References
1. https://www.studytonight.com/c/structures-in-c.php
2. https://www.geeksforgeeks.org/structures-c/
3. https://www.zentut.com/c-tutorial/c-structure/
4. https://www.tutorialspoint.com/cprogramming/pdf/c_structures.pdf



CU IDOL SELF LEARNING MATERIAL (SLM)


244 Computer Programming

UNIT 10 DYNAMIC MEMORY ALLOCATION

Structure:
10.0 Learning Objectives
10.1 Introduction
10.2 Dynamic Memory Allocation Functions
10.3 Summary
10.4 Key Words/Abbreviations
10.5 Learning Activity
10.6 Unit End Questions (MCQ and Descriptive)
10.7 References

10.0 Learning Objectives


After studying this unit, you will be able to:
 Describe the concepts of dynamic memory allocation
 Demonstrate the use of malloc and calloc functions
 Differentiate between malloc and calloc functions
 Develop programs using DMA
 Differentiate between static and dynamic memory allocation

10.1 Introduction
Since C is a structured language, it has some fixed rules for programming. One of it includes
changing the size of an array. An array is collection of items stored at continuous memory locations.

CU IDOL SELF LEARNING MATERIAL (SLM)


Dynamic Memory Allocation 245

As it can be seen that the length (size) of the array above made is 9. But what if there is a
requirement to change this length (size). For Example,
 If there is a situation where only 5 elements are needed to be entered in this array. In this
case, the remaining 4 indices are just wasting memory in this array. So there is a
requirement to lessen the length (size) of the array from 9 to 5.
 Take another situation. In this, there is an array of 9 elements with all 9 indices filled.
But there is a need to enter 3 more elements in this array. In this case 3 indices more are
required. So the length (size) of the array needs to be changed from 9 to 12.
This procedure is referred to as Dynamic Memory Allocation in C.
Therefore, C Dynamic Memory Allocation can be defined as a procedure in which the size
of a data structure (like Array) is changed during the runtime.
C provides some functions to achieve these tasks. There are 4 library functions provided by C
defined under <stdlib.h> header  file  to  facilitate  dynamic memory  allocation  in  C  programming.
They are:
1. malloc()
2. calloc()
3. free()
4. realloc()

10.1.1 Memory Allocation Process


Global variables, static variables and program instructions get their memory in permanent
storage area whereas local variables are stored in area called Stack. The memory space between

CU IDOL SELF LEARNING MATERIAL (SLM)


246 Computer Programming

these two region is known as Heap area. This region is used for dynamic memory allocation during
execution of the program. The size of heap keep changing.

Local Variable Stack

Free Memory Heap

Global Variable

Program Permanent
Instruction Storage
Area
Static
Variable

Fig. 10.1: Memory Allocation Process

10.1.2 Allocating Memory Dynamically


While programming, if you are aware of the size of an array, then it is easy and you can define
it as an array. For example, to store a name of any person, it can go up to a maximum of 100
characters, so you can define something as follows “
char name[100];
Now let us consider a situation where you have no idea about the length of the text you need
to store, for example, you want to store a detailed description about a topic. Here we need to define
a pointer to character without defining how much memory is required and later, based on requirement,
we can allocate memory as shown in the below example “
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char name[100];
char *description;

CU IDOL SELF LEARNING MATERIAL (SLM)


Dynamic Memory Allocation 247

strcpy(name, “Zara Ali”);


/* allocate memory dynamically */
description = malloc( 200 * size of(char) );
if(description == NULL ) {
fprintf(stderr, “Error - unable to allocate required memory\n”);
}
else
{
Strcpy (description, “Zara ali a DPS student in class 10th”);
}
printf(“Name = %s\n”, name );
printf(“Description: %s\n”, description );
}
When the above code is compiled and executed, it produces the following result.
Name = Zara Ali
Description: Zara ali a DPS student in class 10th
Same program can be written using calloc(); only thing is you need to replace malloc with
calloc as follows “
calloc(200, sizeof(char));
So you have complete control and you can pass any size value while allocating memory,
unlike arrays where once the size defined, you cannot change it.

10.1.3 Resizing and Releasing Memory


When your program comes out, operating system automatically release all the memory allocated
by your program but as a good practice when you are not in need of memory anymore then you
should release that memory by calling the function free().
Alternatively, you can increase or decrease the size of an allocated memory block by calling
the function realloc(). Let us check the above program once again and make use of realloc() and

CU IDOL SELF LEARNING MATERIAL (SLM)


248 Computer Programming

free() functions –
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char name[100];
char *description;
strcpy(name, “Shrutkirti Shelar”);
/* allocate memory dynamically */
description = malloc( 30 * sizeof(char) );
if( description == NULL ) {
fprintf(stderr, “Error - unable to allocate required memory\n”);
}
else {
strcpy( description, “Shrutkirti Shelar a CS student”);
}
/* suppose you want to store bigger description */
description = realloc( description, 100 * sizeof(char) );
if( description == NULL ) {
fprintf(stderr, “Error - unable to allocate required memory\n”);
}
else {
strcat( description, “She is in Computer Science class”);
}
printf(“Name = %s\n”, name );
printf(“Description: %s\n”, description );

CU IDOL SELF LEARNING MATERIAL (SLM)


Dynamic Memory Allocation 249

/* release memory using free() function */


free(description);
}
When the above code is compiled and executed, it produces the following result.
Name = Shrutkirti Shelar
Description: Shrutkirti Shelar a CS student. She is in Computer Science class
You can try the above example without re-allocating extra memory, and strcat() function will
give an error due to lack of available memory in description.

10.2 Dynamic Memory Allocation Functions


C dynamic memory allocation refers to performing manual memory management for
dynamic memory allocation in the C programming language via a group of functions in the C
standard library, namely malloc, realloc, calloc and free

10.2.1 malloc()
By using malloc() we can create the memory dynamically at initial stage. malloc() required
one argument of type size type that is data type size malloc() will creates the memory in bytes
format. malloc() through created memory initial value is garbage.
 malloc() function is used to allocate space in memory during the execution of the program.
 malloc() does not initialize the memory allocated during execution. It carries garbage
value.
 malloc() function returns null pointer if it couldn’t able to allocate requested amount of
memory.
The name malloc stands for “memory allocation”.
The function malloc() reserves a block of memory of specified size and return apointer of
type void which can be casted into pointer of any form.

Syntax of malloc()
ptr = (cast-type*) malloc(byte-size)

CU IDOL SELF LEARNING MATERIAL (SLM)


250 Computer Programming

Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory
with size of byte size. If the space is insufficient, allocation fails and returns NULL pointer.
ptr = (int*) malloc(100 * sizeof(int));
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively
and the pointer points to the address of first byte of memory.

Example of malloc():
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *mem_allocation;
/* memory is allocated dynamically */
mem_allocation = malloc( 20 * sizeof(char) );
if( mem_allocation== NULL )
{
printf(“Couldn’t able to allocate requested memory\n”);
}
else
{
strcpy( mem_allocation, “God is great”);
}
printf(“Dynamically allocated memory content : “ \
“%s\n”, mem_allocation );
free(mem_allocation);
}

CU IDOL SELF LEARNING MATERIAL (SLM)


Dynamic Memory Allocation 251

Output:
Dynamically allocated memory content: God is great

10.2.2 calloc(),
calloc() function is also like malloc() function. But calloc() initializes the allocated memory
to zero. But, malloc() doesn’t.
 By using calloc() we can create the memory dynamically at initial stage.
 calloc() required 2 arguments of type count, size-type.
 Count will provide number of elements; size-type is data type size.
 calloc() will creates the memory in blocks format.
 Initial value of the memory is zero.

C calloc()
The name calloc stands for “contiguous allocation”
The only difference between malloc() and calloc() is that, malloc() allocates single block of
memory whereas calloc() allocates multiple blocks of memory each of same size and sets all bytes
to zero.

Syntax of calloc()
ptr = (cast-type*)calloc(n, element-size);
This statement will allocate contiguous space in memory for an array of nelements. For
example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for an array of 25 elements each of size
of float, i.e., 4 bytes.

Example of calloc():
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

CU IDOL SELF LEARNING MATERIAL (SLM)


252 Computer Programming

int main()
{
char *mem_allocation;
/* memory is allocated dynamically */
mem_allocation = calloc( 20, sizeof(char) );
if( mem_allocation== NULL )
{
printf(“Couldn’t able to allocate requested memory\n”);
}
else
{
strcpy( mem_allocation, “God is great”);
}
printf(“Dynamically allocated memory content : “ \
“%s\n”, mem_allocation );
free(mem_allocation);
}

Output:
Dynamically allocated memory content: God is great

10.2.3 realloc()
 realloc() function modifies the allocated memory size by malloc() and calloc() functions
to new size.
 If enough space doesn’t exist in memory of current block to extend, new block is allocated
for the full size of reallocation, then copies the existing data to new block and then frees
the old block.
 By using realloc() we can create the memory dynamically at middle stage.
 Generally by using realloc() we can reallocation the memory.

CU IDOL SELF LEARNING MATERIAL (SLM)


Dynamic Memory Allocation 253

 realloc() required 2 arguments of type void*, size_type.


 Void* will indicates previous block base address, size-type is data type size.
 realloc() will creates the memory in bytes format and initial value is garbage.

C realloc()
If the previously allocated memory is insufficient or more than required, you can change the
previously allocated memory size using realloc().

Syntax of realloc()
ptr = realloc(ptr, newsize);
Here, ptr is reallocated with size of newsize.

Example: Using realloc()


#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr, i , n1, n2;
printf(“Enter size of array: “);
scanf(“%d”, &n1);

ptr = (int*) malloc(n1 * sizeof(int));

printf(“Address of previously allocated memory: “);


for(i = 0; i < n1; ++i)
printf(“%u\t”,ptr + i);

printf(“\nEnter new size of array: “);


scanf(“%d”, &n2);
ptr = realloc(ptr, n2);
for(i = 0; i < n2; ++i)

CU IDOL SELF LEARNING MATERIAL (SLM)


254 Computer Programming

printf(“%u\t”, ptr + i);


return 0;
}

10.2.4 free()
free() function frees the allocated memory by malloc(), calloc(), realloc() functions and returns
the memory to the system.

C free()
Dynamically allocated memory created with either calloc() or malloc() doesn’t get freed on
its own. You must explicitly use free() to release the space.

syntax of free()
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void main()
{
char *mem_allocation;
/* memory is allocated dynamically */
mem_allocation = malloc( 20 * sizeof(char) );
if( mem_allocation == NULL )
{
printf(“Couldn’t able to allocate requested memory\n”);
}
else
{

CU IDOL SELF LEARNING MATERIAL (SLM)


Dynamic Memory Allocation 255

strcpy( mem_allocation,” God is great “);


}
printf(“Dynamically allocated memory content : “ \”%s\n”, mem_allocation );
mem_allocation=realloc(mem_allocation,100*sizeof(char));
if( mem_allocation == NULL )
{
printf(“Couldn’t able to allocate requested memory\n”);
}
else
{
strcpy( mem_allocation,”space is extended up to “ \”100 characters”);
}
printf(“Resized memory : %s\n”, mem_allocation );
free(mem_allocation);
getch( );
}

Output:
Dynamically allocated memory content : God is great
Resized memory : space is extended up to 100 characters

10.2.5 Difference between Static Memory Allocation and Dynamic Memory Allocation
in C
Static Memory Allocation Dynamic Memory Allocation
In static memory allocation, memory is allocated In dynamic memory allocation, memory is allocated
while writing the C program. Actually, user while executing the program. That means at run time.
requested memory will be allocated at compile
time.
Memory size can’t be modified while execution. Memory size can be modified while execution.
Example: Array Example: Linked list

CU IDOL SELF LEARNING MATERIAL (SLM)


256 Computer Programming

10.2.6 Difference between malloc() and calloc() Functions


malloc() calloc()

It allocates only single block of requested memory It allocates multiple blocks of requested memory

Syntax :(cast_type *)calloc(blocks , Syntax :(cast_type *)malloc(Size_in_bytes);


size_of_block);

int *ptr;ptr = malloc( 20 * sizeof(int) );For the int *ptr;Ptr = calloc(20, 20 * sizeof(int)); For the
above, 20*4 bytes of memory only allocated in above, 20 blocks of memory will be created and
one block. Total = 80 bytes each contains 20*4 bytes of memory. Total = 1600
bytes

malloc() doesn’t initializes the allocated memory. calloc () initializes the allocated memory to zero
It contains garbage values

type cast must be done since this function Same as malloc() function int *ptr;ptr = (int*)
returns void pointer int *ptr;ptr = calloc( 20, 20 * sizeof(int) );
(int*)malloc(sizeof(int)*20);
calloc() initializes the allocated memory with 0 malloc() initializes the allocated memory with
value. garbage values.

Number of arguments is 2 Number of argument is 1

10.3 Summary
Dynamic memory allocation is an aspect of allocating and freeing memory according to your
needs. Dynamic memory is managed and served with pointers that point to the newly allocated
space of memory in an area which we call the heap. Now you can create and destroy an array of
elements at runtime without any problems.
To sum up, the automatic memory management uses the stack, and the dynamic memory
allocation uses the heap.
The <stdlib.h> library has functions responsible for dynamic memory management.

10.4 Key Words/Abbreviations


 Dynamic: Characterized by constant change, activity, or progress.
 calloc ()=: Allocates the space for elements of an array. Initializes the elements to zero
and returns a pointer to the memory.

CU IDOL SELF LEARNING MATERIAL (SLM)


Dynamic Memory Allocation 257

 malloc (): Allocates the memory of requested size and returns the pointer to the first
byte of allocated space.
 realloc(): It is used to modify the size of previously allocated memory space.
 free(): Frees or empties the previously allocated memory space.

10.5 Learning Activity


1. What is the use of free() method?
.........................................................................................................................................
.........................................................................................................................................
2. Explain Resizing and Releasing Memory
.........................................................................................................................................
.........................................................................................................................................

10.6 Unit End Questions (MCQ and Descriptive)


A. Descriptive Type: Short Answer Type Questions
1. What is dynamic memory allocation? Explain with process.
2. Explain the dynamic memory allocation functions.
3. What is dynamic memory allocation? Explain allocating and releasing memory.
4. What is the use of malloc() and calloc() function?
5. Write a short note on free() and size of operator.

B. Multiple Choice/Objective Type Questions


1. Which of the following is/are true
(a) calloc() allocates the memory and also initializes the allocates memory to zero,
while memory allocated using malloc() has random data.
(b) malloc() and memset() can be used to get the same effect as calloc().
(c) calloc() takes two arguments, but malloc takes only 1 argument.
(d) All of the above

CU IDOL SELF LEARNING MATERIAL (SLM)


258 Computer Programming

2. What is the return type of malloc() or calloc()


(a) void * (b) Pointer of allocated memory type
(c) void ** (d) int *
3. Which of the following is true?
(a) “ptr = calloc(m, n)” is equivalent to following
ptr = malloc(m * n);
(b) “ptr = calloc(m, n)” is equivalent to following
ptr = malloc(m * n);
memset(ptr, 0, m * n);
(c) “ptr = calloc(m, n)” is equivalent to following
ptr = malloc(m);
memset(ptr, 0, m);
(d) “ptr = calloc(m, n)” is equivalent to following
ptr = malloc(n);
memset(ptr, 0, n);
4. Which languages necessarily need heap allocation in the run time environment?
(a) Those that support recursion
(b) Those that use dynamic scoping
(c) Those that use global variables
(d) Those that allow dynamic data structures
5. We use malloc and calloc for
(a) Dynamic memory allocation
(b) Static memory allocation
(c) Both dynamic and static memory allocation
(d) None of the above
Answers: 1. (d), 2. (a), 3. (b), 4. (d), 5. (a)

CU IDOL SELF LEARNING MATERIAL (SLM)


Dynamic Memory Allocation 259

10.7 References
1. https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-
free-and-realloc/
2. https://www.guru99.com/c-dynamic-memory-allocation.html
3. https://www.unf.edu/~wkloster/2220/ppts/malloc.pdf
4. https://www.cs.cmu.edu/~guna/15-123S11/Lectures/Lecture08.pdf



CU IDOL SELF LEARNING MATERIAL (SLM)


260 Computer Programming

UNIT 11 C PREPROCESSOR

Structure:
11.0 Learning Objectives
11.1 Introduction
11.2 Concepts of Preprocessor
11.3 Preprocessor Directives
11.4 Predefined Macros
11.5 Parameterized Macros.
11.6 Summary
11.7 Key Words/Abbreviations
11.8 Learning Activity
11.9 Unit End Questions (MCQ and Descriptive)
11.10 References

11.0 Learning Objectives


After studying this unit, you will be able to:
 Explain the concepts of preprocessor
 Describe preprocessor directives
 Elaborate the concepts of predefined macros
 Discuss the concepts of parameterized macros

CU IDOL SELF LEARNING MATERIAL (SLM)


C Preprocessor 261

11.1 Introduction
In C compilation model and processes, the C source code is passed to a preprocessor before
being transferred to the compiler. The preprocessor interprets all preprocessor directives or macros
by substituting the macros by their contents.
The preprocessor has its own syntax which is different from the C syntax. All the preprocessor
begins with a hash ( #) sign e.g., #define, #include

11.2 Concepts of Preprocessor


A Preprocessor is a system software (a computer program that is designed to run on computer’s
hardware and application programs). It performs preprocessing of the High Level Language (HLL).
Preprocessing is the first step of the language processing system. Language processing system
translates the high level language to machine level language or absolute machine code (i.e., to the
form that can be understood by machine).
 The preprocessor doesn’t know about the scope rules of C. Preprocessor directives like
#define come into effect as soon as they are seen and remain in effect until the end of
the file that contains them; the program’s block structure is irrelevant.

Fig. 11.1: Preprocessing Steps of the High Level Language (HLL)

CU IDOL SELF LEARNING MATERIAL (SLM)


262 Computer Programming

File inclusion: Including all the files from library that our program needs. In HLL we
write #include which is a directive for the preprocessor that tells  it to include the contents of the
library file specified. For example, #include will tell the preprocessor to include all the contents in
the library file stdio.h.
This can also be written using double quotes – #include “stdio.h”
Macro expansion: Macros can be called as small functions that are not as overhead to process.
If we have to write a function (having a small definition) that needs to be called recursively (again
and again), then we should prefer a macro over a function.
So, defining these macros is done by preprocessor.
#define SI 1000

11.3 Preprocessor Directives


Table 11.1: List of Preprocessor Directives

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

It is Constant defining section, this section is prefixed by # sign


# define pi 3.1415
# is preprocessor directive which gives direction to the compiler that define pi as a constant
value for the program.
It is also called as Macro defined.

CU IDOL SELF LEARNING MATERIAL (SLM)


C Preprocessor 263

Macro: #define
This macro defines constant value and can be any of the basic data types. These constants are
usually defined at the beginning of a program. They may then appear later in the program in place
of the numeric constants, character constants, etc. that the macro may represent. The syntax to use
define macro is as follows:
#define name value
Where name represents a symbolic name, typically written in uppercase letters, and text
represents the sequence of characters that is associated with the symbolic name. Note that text does
not end with a semicolon, since a symbolic constant definition is not a true C statement.
Let’s see an example:
#define PI 3.14
void main()
{
float radius=1.2;
float area_of_circle = PI * radius * radius;
float circumference_of_circle = 2 * PI * radius;
printf(“\n Details of circle”);
printf(“\n Area = %f”, area_of_circle);
printf(“\n Circumference = %f”, circumference_of_circle);
}
In the above program, instead of writing the value of 3.14 for calculating area and circumference
of circle, a constant PI which is defined before the main() method is used.
#define PI 3.14
This statement is called ‘macro definition’ or more commonly, just a ‘macro’. The preprocessor
replaces every occurrence of PI in the program with 3.14.

 File Inclusion: #include


The second preprocessor directive causes one file to be included in another. The preprocessor
command for file inclusion looks like this:
#include <file_name>  
CU IDOL SELF LEARNING MATERIAL (SLM)
264 Computer Programming

The source code of the file “file_name” is included in the main( ) function C program where
“#include <file_name>” is mentioned. Of course this assuming that the file being included is existing.
This directive is normally used for very large programs which can be divided into several
different files each containing related functions. These files are #include at the beginning of
main( ) function program file. Secondly, the commonly needed functions and macro definitions can
be stored in a file, and that file can be included in every program later.
The prototypes of all the library functions are grouped into different categories and then
stored in different header files. For example prototypes of all mathematics related functions are
stored in the header file ‘math.h’ which can be included as shown below:
#include<math.h>
The #include directive can be used in two ways as discussed below:
#include “filename”
#include <filename>
#include “sum.c”
#include “c:\employee.c”
It is Link section also called as include section, this section is prefixed by # sign
# include<stdio.h>
# include<conio.h>
# include<math.h>
# include<stdlib.h>
# is preprocessor directive which gives direction to the compiler that include specified
header file from Library to main( ) function program.
Table 11.2: List of Header Files

Header File Description


#include<stdio.h> It is standard input output header files, consist of standard input function
scanf() and standard output function printf()
#include<conio.h> It is console input output header file, consist of clrscr() function to clear
screen and getch() function to get character to see the output on screen.
#include<math.h> It is Math medical Header File Consist of all mathematical functions,
sin( ), cos( ), tan( ), sqrt( ).

CU IDOL SELF LEARNING MATERIAL (SLM)


C Preprocessor 265

#include<stdlib.h It is standard Library File consist of Exit( ) function


#include<string.h> It is string header File consist of string functions, strcmp( ), strlen( ),
strcpy( ), strrev( ), strcat( ).

#include<Ctype.h> All character handling functions are defined in this header file.functionsIt
consist of islower( ), isupper( ), isdigit( )

Preprocessor is also called Macro Definition.


# define max 100
Hence # is a preprocessor directive which directs to the compiler that identifier max as a
token replaced with the string 100.
Hence in the program each occurance of max is automatically replaced by 100.

Examples:
# define true 1
# define false 0
# define EoF – 1
# define product (x, y) ((x) * (y))

11.4 Predefined Macros

Predefined Macros
A predefined macro is a macro that is already understood by the C preprocessor without the
program needing to define it.
Here are some predefined macros in C programming.

Table 11.3: Predefined Macros in C

Macro Value
__DATE__ A string containing the current date
__FILE__ A string containing the file name
__LINE__ An integer representing the current line number
__STDC__ If follows ANSI standard C, then the value is a nonzero integer
__TIME__ A string containing the current date.

CU IDOL SELF LEARNING MATERIAL (SLM)


266 Computer Programming

Let’s try the following example - To Get current time using __TIME__
The following program outputs the current time using __TIME__ macro.

1. #include <stdio.h>
2. int main()
3. {
4. printf(“Current time: %s”,__TIME__);
5. }

Output
Current time: 19:54:39

Example:
#include <stdio.h>
int main() {
printf(“File :%s\n”, __FILE__ );
printf(“Date :%s\n”, __DATE__ );
printf(“Time :%s\n”, __TIME__ );
printf(“Line :%d\n”, __LINE__ );
printf(“ANSI :%d\n”, __STDC__ );
}
When the above code in a file test.c is  compiled  and  executed,  it  produces  the  following
result –
File :test.c
Date :Jun 2 2012
Time :03:36:24
Line :8
ANSI :1

CU IDOL SELF LEARNING MATERIAL (SLM)


C Preprocessor 267

11.5 Parameterized Macros


Parameterized macros can be used to create templates for frequently used parts of code.
Frequently, they serve as simple functions. #define helps to define a macro and the #undefine helps
to remove a macro definition. Syntax of a parameterized macro is as follows:
#define identifier(parameterlist) replacement-list
There should be no spaces between the identifier and the parameter list. There should be no
spaces in the parameter list.

Example:

#define getchar() getc(stdin)


#define IS_EVEN(m) ((m)%2 == 0)
#define max(a,b) (((a)>(b))?(a):(b))
#define toupper(x) ((‘a’<=(x)&&(x) z=”” x=”” -=”” a=”” :=”” br=””> #define print(y)
printf(“%d\n”,y) print(c/d) /* becomes printf(“%d\n”,c/d); */

Advantages of a parameterized macro:


The compiled code will execute more quickly because the macro is substituted in line. No
function calling overhead is wanted.
The parameters of functions are typed but in macros they are not typed. So, they are generic.
The max() macro given example will perform for floats and also for ints.

Disadvantages of a parameterized macro:


The compiled code will often be larger, mostly when macros are nested (e.g.,
max(a,max(b,max(c,d))) ) because each instance of the macro is expanded in line.
A macro may calculate its arguments more than once, producing subtle faults and it is not
achievable to have a pointer to a macro.

CU IDOL SELF LEARNING MATERIAL (SLM)


268 Computer Programming

11.6 Summary
The C preprocessor is a macro processor that is used automatically by the C compiler to
transform your program before actual compilation. It is called a macro processor because it allows
you to define macros, which are brief abbreviations for longer constructs.
The C preprocessor provides four separate facilities that you can use as you see fit:
 Inclusion of header files. These are files of declarations that can be substituted into
your program.
 Macro expansion. You can define macros, which are abbreviations for arbitrary fragments
of C code, and then the C preprocessor will replace the macros with their definitions
throughout the program.
 Conditional compilation. Using special preprocessing directives, you can include or
exclude parts of the program according to various conditions.
 Line control. If you use a program to combine or rearrange source files into an
intermediate file which is then compiled, you can use line control to inform the compiler
of where each source line originally came from.

11.7 Key Words/Abbreviations


 Macro: A macro is a fragment of code which has been given a name. Whenever the
name is used, it is replaced by the contents of the macro. There are two kinds of macros.
They differ mostly in what they look like when they are used. Object-like macros
resemble data objects when used, function-like macros resemble function calls.
 preprocessor: The C Preprocessor is not a part of the compiler, but is a separate step in
the compilation process.

11.8 Learning Activity


1. Explain #define.
.......................................................................................................................................
.......................................................................................................................................

CU IDOL SELF LEARNING MATERIAL (SLM)


C Preprocessor 269

2. Explain predefined Macros.


.......................................................................................................................................
.......................................................................................................................................

11.9 Unit End Questions (MCQ and Descriptive)


A. Descriptive Type: Short Answer Type Questions
1. Explain what is preprocessor in c language.
2. Describe different preprocessor directives in c language
3. Discuss what are predefined Macros in c language.
4. Elaborate Parameterized Macros in c language.

B. Multiple Choice/Objective Type Questions


1. Which file is generated after preprocessing of a C program?
(a) . p (b) .i
(c) o (d) .m
2. C preprocessor
(a) Takes care of conditional compilation
(b) Takes care of macros
(c) Takes care of include files
(d) All of the aboce
3. A preprocessor command
(a) need not start on a new line
(b) need not start on the first column
(c) has # as the first character
(d) comes before the first executable statement

CU IDOL SELF LEARNING MATERIAL (SLM)


270 Computer Programming

4. What is the Output of following code?


#include<stdio.h> 
#define f(g,g2) g##g2
int main()

    int var12 = 100;
    printf("%d", f(var,12));
    return 0;
}
(a) 100 (b)  Compiler Error
(c) 0 (d)  1
5.  What is the Output of following code?
#include <stdio.h>
#define square(x) x*x
int main()
{
   int x;
   x = 36/square(6);
   printf("%d", x);
   return 0;
}
(a) 1 (b) 36
(c) 0 (d) Compiler Error
Answers: 1. (b), 2. (d), 3. (c), 4. (a), 5. (b)

CU IDOL SELF LEARNING MATERIAL (SLM)


C Preprocessor 271

11.10 References
1. https://gcc.gnu.org/onlinedocs/gcc-2.95.3/cpp_1.html
2. https://www.zentut.com/c-tutorial/c-preprocessor/
3. The C Programming Language Ritchie & kernighan
4. http://www2.cs.uregina.ca/~hilder/cs833/Other%20Reference%20Materials/
The%20C%20Programming%20Language.pdf



CU IDOL SELF LEARNING MATERIAL (SLM)


272 Computer Programming

UNIT 12 FILE MANAGEMENT

Structure:
12.0 Learning Objectives
12.1 Introduction
12.2 File Types
12.3 File Handling Functions
12.4 Summary
12.5 Key Words/Abbreviations
12.6 Learning Activity
12.7 Unit End Questions (MCQ and Descriptive)
12.8 References

12.0 Learning Objectives


After studying this unit, you will be able to:
 Describe the concepts of file management
 Know the File Modes
 Discuss types of Files
 Discuss different types of file handling functions

12.1 Introduction
File Handling concept in C language is used for store a data permanently in computer memory.
Using this concept we can store our data in Secondary memory (Hard disk). Afilerepresents a

CU IDOL SELF LEARNING MATERIAL (SLM)


File Management 273

sequence of bytes on the disk where a group of related data is stored. File is created for permanent
storage of data. It is a readymade structure.
All files related function are available instdio.hheader file.
In C language, we use a structurepointer of file typeto declare a file.

File Handling in C:
1. New way of dealing with data is file handling.
2. Data is stored onto the disk and can be retrieve whenever require.
3. Output of the program may be stored onto the disk.
4. In C we have many functions that deals with file handling.
5. A file is a collection of bytes stored on a secondary storage device(generally a disk)
6. Collection of byte may be interpreted as —
– Single character
– Single Word
– Single Line
– Complete Structure.

File Operations
There are 5 major operations can be performed on files
1. Creation of new file
2. Opening an existing file
3. Reading data from file
4. Writing data into file
5. Appending data into file
6. Closing a file.

12.1.1 File Operations


There are 5 major operations can be performed on files
1. Creation of new file
2. Opening an existing file

CU IDOL SELF LEARNING MATERIAL (SLM)


274 Computer Programming

3. Reading data from file


4. Writing data into file
5. Appending data into file
6. Closing a file.

Table 12.1: Different File Operations

File Operation/Syntax Description


file open fopen function is used to open a file.
FILE *fp; Where, fp is file pointer to the data type “FILE”.
fp=fopen (“filename”, “mode”);
file close: fclose function closes the file that is being pointed by
fclose(fp); file pointer fp.
file read: fgets is used to read a file line by line. where, buffer –
fgets (buffer, size, fp); buffer to put the data in.size – size of the buffer fp – file pointer
file write: fprintf writes the data into a file pointed by fp.
fprintf (fp, “some data”);
fprintf (fp, “text %d”, variable_name);

Steps for processing C Files:


1. Declare a file pointer variable
2. Open a file using fopen( ) function by specifying mode of opening of a file.
3. If mode is read mode, then file should be already created with the contents
4. If mode is write mode, then it will create new file and data can be written on to the file.
5. If mode is append, the file should be already created with some contents and then we
can add the contents at the end of the file.
6. Close a file by using fclose( ) function.

Details of Explanation of Steps for Processing C Files:


1. Declare a file pointer variable
When working with files, you need to declare a pointer of type file. This declaration is
needed for communication between the file and program.
FILE *fptr;

CU IDOL SELF LEARNING MATERIAL (SLM)


File Management 275

2. Open a file using fopen( ) function by specifying mode of opening of a file.


Opening a file is performed using the library function in the “stdio.h” header file:
fopen() function.
The syntax for opening a file in standard I/O is:
fptr = fopen(“fileopen”,”mode”)
For Example:
fopen(“E:\\cprogram\\kirantxtfile.txt”,”w”); //For Text Mode
fopen(“E:\\cprogram\\kiranbinfile.bin”,”rb”); // For Binary Mode
3. If mode is read mode, then file should be already created with the contents
Reading a Text File
Reading from text file can be done by getc( ) and gets( ) function
This is the simplest function to read a single character from a file H
int fgetc( FILE * fp );
The fgetc() function reads a character from the input file referenced by fp. The return value is
the character read, or in case of any error, it returns EOF. The following function allows to read a
string from a stream H.
This is the simplest function to read a string from a file H
char *fgets( char *buf, int n, FILE *fp );
The functions fgets() reads up to n-1 characters from the input stream referenced by fp. It
copies the read string into the buffer buf, appending a null character to terminate the string.
If this function encounters a newline character ‘\n’ or the end of the file EOF before they have
read the maximum number of characters, then it returns only the characters read up to that point
including the new line character. You can also use int fscanf(FILE *fp, const char *format, ...)
function to read strings from a file, but it stops reading after encountering the first space character.
#include <stdio.h>
void main()
{
FILE *fp;

CU IDOL SELF LEARNING MATERIAL (SLM)


276 Computer Programming

char buff[255];
fp = fopen(“/tmp/kiran.txt”, “r”);
fscanf(fp, “%s”, buff);
printf(“1 : %s\n”, buff );
fgets(buff, 255, (FILE*)fp);
printf(“2: %s\n”, buff );
fgets(buff, 255, (FILE*)fp);
printf(“3: %s\n”, buff );
fclose(fp);
}
When the above code is compiled and executed, it reads the file created in the previous section
and produces the following result “
1: This
2: is testing for fprintf...
3: This is testing for fputs...
Let’s see a little more in detail about what happened here. First, fscanf() read just This
because after that, it encountered a space, second call is for fgets() which reads the
remaining line till it encountered end of line. Finally, the last call fgets() reads the
second line completely.
 Reading Binary File
fread( ) function is used to read from binary file.
size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE
*a_file);
Both of these functions should be used to read or write blocks of memories - usually
arrays or structures.
4. If mode is write mode, then it will create new file and data can be written on to the
file.

CU IDOL SELF LEARNING MATERIAL (SLM)


File Management 277

Writing a File
fputc( ) and fputs( ) functions are used to write characters and strings into text files.
int fputc( int c, FILE *fp );
The function fputc() writes the character value of the argument c to the output stream
referenced by fp. It returns the written character written on success otherwise EOF if
there is an error. You can use the following functions to write a null-terminated string to
a stream “
int fputs( const char *s, FILE *fp );
The function fputs() writes the string s to the output stream referenced by fp. It returns
a non-negative value on success, otherwise EOF is returned in case of any error. You
can use int fprintf(FILE *fp,const char *format, ...) function as well to write a string
into a file. Try the following example:
Make sure you have /tmp directory available. If it is not, then before proceeding, you must
create this directory on your machine.
#include <stdio.h>
void main()
{
FILE *fp;
fp = fopen(“/tmp/kiranbinary.txt”, “w+”);
fprintf(fp, “This is testing for fprintf...\n”);
fputs(“This is testing for fputs...\n”, fp);
fclose(fp);
}
When the above code is compiled and executed, it creates a new file kiranbinary.txt in /tmp
directory and writes two lines using two different functions. Let us read this file in the next section.
Example: Write to a text file using fprintf()
#include <stdio.h>
void main()

CU IDOL SELF LEARNING MATERIAL (SLM)


278 Computer Programming

{
int num;
FILE *fptr;
fptr = fopen(“C:\\kiran.txt”, “w”);
if(fptr == NULL)
{
printf(“Error!”);
exit(1);
}
printf(“Enter num:”);
scanf(“%d”,&num);
fprintf(fptr,”%d”,num);
fclose(fptr);
getch( );
}
This program takes a number from user and stores in the file kiran.txt.
After you compile and run this program, you can see a text file program.txt created in C
drive of your computer. When you open the file, you can see the integer you entered.
fwrite( ) function is used to write into binary file.
size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements, FILE
*a_file);
5. If mode is append, the file should be already created with some contents and then
we can add the contents at the end of the file.
The syntax for opening a file in append mode is:-
fopen(“E:\\cprogram\\kirantxtfile.txt”,”a”); //For Text Mode
fopen(“E:\\cprogram\\kiranbinfile.bin”, “ab+”); // For Binary Mode
#include <stdio.h>

CU IDOL SELF LEARNING MATERIAL (SLM)


File Management 279

void main()
{
FILE *fp
file = fopen(“kiran.txt”,”a”);
fprintf(fp, “%s”,”This is just an example of text appended by kiran :)”);
/*append some text*/
fclose(fp);
getch( );
}
6. Close a file by using fclose( ) function.
The fclose( ) function is used to close an already opened file.
General Syntax :
int fclose( FILE *fp );
Here fclose() function closes the file and returns zero on success, or EOF (End of File)
if there is an error in closing the file. This EOF is a constant defined in the header file
stdio.h.
FILE *fp;
fclose(fp);

12.1.2 Mode of Operations Performed on a File: (Modes)


There are many modes in opening a file. Based on the mode of file, it can be opened for
reading or writing or appending the texts. They are listed below.

Table 12.2: Different File Modes Types

Opening Mode Purpose Previous Data


Reading File will be opened just for reading purpose Retained
Writing File will be opened just for writing purpose Flushed

Appending File will be opened for appending some thing in file Retained

CU IDOL SELF LEARNING MATERIAL (SLM)


280 Computer Programming

 r – Opens a file in read mode and sets pointer to the first character in the file. It
returns null if file does not exist.
 w – Opens a file in write mode. It returns null if file could not be opened. If file exists,
data are overwritten.
 a – Opens a file in append mode. It returns null if file couldn’t be opened.
 r+ – Opens a file for read and write mode and sets pointer to the first character in the
file.
 w+ – Opens a file for read and write mode and sets pointer to the first character in the
file.
 a+ – Opens a file for read and write mode and sets pointer to the first character in the
file. But, it can’t modify existing contents.

Table 12.3: Different File Modes


File Mode Meaning of Mode During Inexistence of File
r Open for reading. If the file does not exist, fopen()
returns NULL.
rb Open for reading in binary mode. If the file does not exist, fopen()
returns NULL.
w Open for writing. If the file exists, its contents are
overwritten. If the file does not
exist, it will be created.
Wb Open for writing in binary mode. If the file exists, its contents are
overwritten. If the file does not
exist, it will be created.
a Open for append, i.e., Data is added to end of file. If the file does not exists, it will be
created.
ab Open for append in binary mode, i.e., Data is If the file does not exists, it will be
added to end of file. created.
r+ Open for both reading and writing. If the file does not exist, fopen()
returns NULL.
rb+ Open for both reading and writing in binary mode. If the file does not exist, fopen()
returns NULL.
w+ Open for both reading and writing. If the file exists, its contents are
overwritten. If the file does not exist,
it will be created.

CU IDOL SELF LEARNING MATERIAL (SLM)


File Management 281

wb+ Open for both reading and writing in binary mode. If the file exists, its contents are
overwritten. If the file does not exist,
it will be created.
a+ Open for both reading and appending. If the file does not exists, it will be
created.
ab+ Open for both reading and appending in If the file does not exists, it will be
binary mode. created.

12.2 File Types


What is File?
File is a collection of bytes that is stored on secondary storage devices like disk. There are two
kinds of files in a system. They are,
1. Text files (ASCII)
Text files contain ASCII codes of digits, alphabetic and symbols
2. Binary files
Binary file contains collection of bytes (0s and 1s). Binary files are compiled version of
text files.
A file is a collection of bytes stored on a secondary storage device, which is generally a disk
of some kind. The collection of bytes may be interpreted, for example, as characters, words, lines,
paragraphs and pages from a textual document; fields and records belonging to a database; or
pixels from a graphical image.
The meaning attached to a particular file is determined entirely by the data structures and
operations used by a program to process the file. It is conceivable (and it sometimes happens) that
a graphics file will be read and displayed by a program designed to process textual data.
Essentially there are two kinds of files that programmers deal with text files and binary files.

ASCII Text files


Text files are the normal .txt files that you can easily create using Notepad or any simple text
editors.

CU IDOL SELF LEARNING MATERIAL (SLM)


282 Computer Programming

A text file can be a stream of characters that a computer can process sequentially. It is not only
processed sequentially but only in forward direction. For this reason a text file is usually opened
for only one kind of operation (reading, writing, or appending) at any given time.
Similarly, since text files only process characters, they can only read or write data one character
at a time. (In C Programming Language, Functions are provided that deal with lines of text, but
these still essentially process data one character at a time.)
When you open those files, you will see all the contents within the file as plain text. You can
easily edit or delete the contents. They take minimum effort to maintain are easily readable and
provide least security and takes bigger storage space.

Binary Files
Binary file are mostly the .bin files in your computer. Instead of storing data in plain text, they
store it in the binary form (0s and 1s). They can hold higher amount of data are not readable easily
and provides a better security than text files.
Binary files can be either processed sequentially or, depending on the needs of the application,
they can be processed using random access techniques. In C Programming Language, processing a
file using random access techniques involves moving the current file position to an appropriate
place in the file before reading or writing data. This indicates a second characteristic of binary files.
They a generally processed using read and write operations simultaneously.

12.3 File Handling Functions


12.3.1 fopen()
The fopen() function is used to open a file and associates an I/O stream with it. This function
takes two arguments. The first argument is a pointer to a string containing name of the file to be
opened while the second argument is the mode in which the file is to be opened.
FILE *fopen(const char *path, const char *mode);
The mode can be:
‘r’: Open text file for reading. The stream is positioned at the beginning of the file.
‘r+’: Open for reading and writing. The stream is positioned at the beginning of the file.

CU IDOL SELF LEARNING MATERIAL (SLM)


File Management 283

‘w’: Truncate file to zero length or create text file for writing. The stream is positioned at the
beginning of the file.
‘w+’: Open for reading and writing. The file is created if it does not exist, otherwise it is
truncated. The stream is positioned at the beginning of the file.
‘a’: Open for appending (writing at end of file). The file is created if it does not exist. The
stream is positioned at the end of the file.
‘a+’: Open for reading and appending (writing at end of file). The file is created if it does not
exist. The initial file position for reading is at the beginning of the file, but output is
always appended to the end of the file.
The fopen() function returns a FILE stream pointer on success while it returns NULL in case
of a failure.

12.3.2 fclose()
The fclose() function first flushes the stream opened by fopen() and then closes the underlying
descriptor. Upon successful completion this function returns 0 else end of file (eof) is returned. In
case of failure, if the stream is accessed further then the behaviour remains undefined.
int fclose(FILE *fp);
For example, Program to open and close a file:
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fptr;
If((fptr = fopen(“TEST”,”w”))==NULL)
{
printf(“Cannot open file\n”);
exit(1);
}

CU IDOL SELF LEARNING MATERIAL (SLM)


284 Computer Programming

if(fclose(fptr))
pritf(“File close error\n”);
return o;
}

12.3.3 fgetc()
The fgetc() function reads a character from the input file referenced by fp. The return value is
the character read, or in case of any error, it returns EOF. The following function allows to read a
string from a stream
char *fgets( char *buf, int n, FILE *fp );

Example :
#include<stdio.h>
void main()
{
FILE *fp;
char ch;

fp = fopen(“file.txt”, “w”); //Statement 1


if(fp == NULL)
{
printf(“\nCan’t open file or file doesn’t exist.”);
exit(0);
}
while((ch=getchar())!=EOF) //Statement 2
fputc(ch,fp);
printf(“\nData written successfully...”);
fclose(fp);
}

CU IDOL SELF LEARNING MATERIAL (SLM)


File Management 285

Output:
Hello friends, my name is Shruti
Data written successfully...

12.3.4 fputc()
The function fputc() writes the character value of the argument c to the output stream referenced
by fp. It returns the written character written on success otherwise EOF if there is an error. You can
use the following functions to write a null-terminated string to a stream.
int fputs( const char *s, FILE *fp );
The function fputs() writes the string s to the output stream referenced by fp. It returns a non-
negative value on success, otherwise EOF is returned in case of any error.
You can use int fprintf(FILE *fp,const char *format, ...) function as well to write a string
into a file. Make sure you have /tmp directory available. If it is not, then before proceeding, you
must create this directory on your machine.
Following is the simplest function to write individual characters to a stream “
int fputc( int c, FILE *fp );

Example:
#include <stdio.h>
main() {
FILE *fp;
fp = fopen(“/tmp/test.txt”, “w+”);
fprintf(fp, “This is testing for fprintf...\n”);
fputs(“This is testing for fputs...\n”, fp);
fclose(fp);
}
When the above code is compiled and executed, it creates a new file test.txt in /tmp directory
and writes two lines using two different functions.

CU IDOL SELF LEARNING MATERIAL (SLM)


286 Computer Programming

12.3.5 fgets()
The functions fgets() reads up to n-1 characters from the input stream referenced by fp. It
copies the read string into the bufferbuf, appending a null character to terminate the string.
If this function encounters a newline character ‘\n’ or the end of the file EOF before they have
read the maximum number of characters, then it returns only the characters read up to that point
including the new line character. You can also use int fscanf(FILE *fp, const char *format, ...)
function to read strings from a file, but it stops reading after encountering the first space character.
#include <stdio.h>
main() {
FILE *fp;
char buff[255];
fp = fopen(“/tmp/test.txt”, “r”);
fscanf(fp, “%s”, buff);
printf(“1 : %s\n”, buff );

fgets(buff, 255, (FILE*)fp);


printf(“2: %s\n”, buff );

fgets(buff, 255, (FILE*)fp);


printf(“3: %s\n”, buff );
fclose(fp);
}

Output:
1. This
2. is testing for fprintf...
3. This is testing for fputs...

CU IDOL SELF LEARNING MATERIAL (SLM)


File Management 287

12.3.6 fputs()
The fputs() function is used to write string (array of characters) to the file.
fputs(char str[], FILE *fp);
The fputs() function takes two arguments, first is the string to be written to the file and second
is the file pointer where the string will be written.
#include<stdio.h>
void main()
{
FILE *fp;
char str[];
fp = fopen(“kiran.txt”, “w”); //Statement 1
if(fp == NULL)
{
printf(“\nCan’t open file or file doesn’t exist.”);
exit(0);
}
do
{
gets(str);
fputs(str,fp);
}while(strlen(str)!=0);
printf(“\nData written successfully...”);
fclose(fp);
}

Output:
C is a general-purpose programming language.
It is developed by Dennis Ritchie.

CU IDOL SELF LEARNING MATERIAL (SLM)


288 Computer Programming

Data written successfully..


In the above example, statement 1 will create a file named kiran.txt in write mode. Statement
2 is a loop, which take strings from user and write the strings to the file, until user input an empty
string.

12.3.7 fscanf()
The fscanf() function is used to read mixed type form the file.
Syntax of fscanf() function
fscanf(FILE *fp, “format-string”,var-list);
The fscanf() function is similar to scanf() function except the first argument which is a file
pointer that specifies the file to be read.

Example of fscanf() function


#include<stdio.h>
void main()
{
FILE *fp;
char ch;
fp = fopen(“kiran.txt”, “r”); //Statement 1
if(fp == NULL)
{
printf(“\nCan’t open file or file doesn’t exist.”);
exit(0);
}
printf(“\nData in file...\n”);
while((fscanf(fp, “%d%s%f”,&roll,name,&marks))!=EOF) //Statement 2
printf(“\n%d\t%s\t%f”,roll,name,marks);
fclose(fp);
}

CU IDOL SELF LEARNING MATERIAL (SLM)


File Management 289

Output:
Data in file...
1 Shruti 81.65
2 Kiran 82.62
In the above example, Statement 1 will open an existing file file.txt in read mode and statement
2 will read all the data up to EOF(end-of-file) reached.

12.3.8 fprintf()
So far we have seen writing of characters, strings and integers in different files. This is not
enough if we need to write characters, strings and integers in one single file, for that purpose we use
fprintf() function. The fprintf() function is used to write mixed type in the file.
Syntax of fprintf() function
fprintf(FILE *fp, “format-string”,var-list);
The fprintf() function is similar to printf() function except the first argument which is a file
pointer that specifies the file to be written.

Example of fprintf() function


#include<stdio.h>
void main()
{
FILE *fp;
int roll;
char name[25];
float marks;
char ch;
fp = fopen(“file.txt”, “w”); //Statement 1
if(fp == NULL)
{
printf(“\nCan’t open file or file doesn’t exist.”);

CU IDOL SELF LEARNING MATERIAL (SLM)


290 Computer Programming

exit(0);
}
do
{
printf(“\nEnter Roll :”);
scanf(“%d”,&roll);
printf(“\nEnter Name :”);
scanf(“%s”,name);
printf(“\nEnter Marks :”);
scanf(“%f”,&marks);
fprintf(fp, “%d%s%f”,roll,name,marks);
printf(“\nDo you want to add another data (y/n) :”);
ch = getche();
}while(ch==‘y’ || ch==‘Y’);
printf(“\nData written successfully...”);
fclose(fp);
}

Output:
Enter Roll : 11
Enter Name : Shruti
Enter Marks : 78.53
Do you want to add another data (y/n) : y
Enter Roll : 21
Enter Name : Kirti
Enter Marks : 89.62
Do you want to add another data (y/n) : n
Data written successfully...

CU IDOL SELF LEARNING MATERIAL (SLM)


File Management 291

12.3.9 getw()
The getw() function is used to read integer value form the file.
Syntax of getw() function
int getw(FILE *fp);
The getw() function takes the file pointer as argument from where the integer value will be
read and returns returns the end-of-file if it has reached the end of file.

Example of getw() function


#include<stdio.h>
void main()
{
FILE *fp;
int num;
fp = fopen(“file.txt”, “r”); //Statement 1
if(fp == NULL)
{
printf(“\nCan’t open file or file doesn’t exist.”);
exit(0);
}
printf(“\nData in file...\n”);
while((num = getw(fp))!=EOF) //Statement 2
printf(“\n%d”,num);
fclose(fp);
}

CU IDOL SELF LEARNING MATERIAL (SLM)


292 Computer Programming

Output:
Data in file...
78
45
63
In the above example, Statement 1 will open an existing file file.txt in read mode and statement
2 will read all the integer values up to EOF(end-of-file) reached.

12.3.10 putw()
The putw() function is used to write integers to the file.

Syntax of putw() function


putw(int number, FILE *fp);
The putw() function takes two arguments, first is an integer value to be written to the file and
second is the file pointer where the number will be written.
#include<stdio.h>
void main()
{
FILE *fp;
int num;
char ch=‘n’;
fp = fopen(“file.txt”, “w”); //Statement 1
if(fp == NULL)
{
printf(“\nCan’t open file or file doesn’t exist.”);
exit(0);
}
do //Statement 2

CU IDOL SELF LEARNING MATERIAL (SLM)


File Management 293

{
printf(“\nEnter any number :”);
scanf(“%d”,&num);
putw(num,fp);
printf(“\nDo you want to another number :”);
ch = getche();
}while(ch==‘y’||ch==‘Y’);
printf(“\nData written successfully...”);
fclose(fp);
}

Output:
Enter any number : 78
Do you want to another number : y
Enter any number : 45
Do you want to another number : y
Enter any number : 63
Do you want to another number : n
Data written successfully...
In the above example, statement 1 will create a file named file.txt in write mode. Statement 2
is a loop, which take integer values from user and write the values to the file.

12.3.11 fread() and fwrite()


The functions fread/fwrite are used for reading/writing data from/to the file opened by fopen
function. These functions accept three arguments. The first argument is a pointer to buffer used for
reading/writing the data. The data read/written is in the form of ‘nmemb’ elements each ‘size’ bytes
long.

CU IDOL SELF LEARNING MATERIAL (SLM)


294 Computer Programming

In case of success, fread/fwrite return the number of bytes actually read/written from/to the
stream opened by fopen function. In case of failure, a lesser number of byes (then requested to read/
write) is returned.
/* Open, Read and close a file: reading string by string */
# include <stdio.h>
int main( )
{
FILE *fp ;
char data[50] ;
printf(“Opening the file kiran.c in read mode”) ;
fp = fopen(“kiran.c”, “r”) ;
if ( fp == NULL )
{
printf(“Could not open file kiran.c”) ;
}
printf(“Reading the file kiran.c”) ;
while( fgets (data, 50, fp ) != NULL)
printf( “%s”, data ) ;
printf(“Closing the file kiran.c”) ;
fclose(fp) ;
}

Output:
Opening the file kiran.c in read mode
Reading the file kiran.c
Hai, How are you?
Closing the file kiran.c

CU IDOL SELF LEARNING MATERIAL (SLM)


File Management 295

/ * Open, write and close a file : */


# include <stdio.h>
# include <string.h>
int main( )
{
FILE *fp ;
char data[50];
// opening an existing file
printf(“Opening the file kiran.c in write mode”) ;
fp = fopen(“kiran.c”, “w”) ;
if ( fp == NULL )
{
printf(“Could not open file kiran.c”) ;
}
printf(“\n Enter some text from keyboard” \
“to write in the file kiran.c”) ;
// getting input from user
while (strlen ( gets( data ) ) > 0)
{
// writing in the file
fputs(data, fp) ;
fputs(“\n”, fp) ;
}
// closing the file
printf(“Closing the file kiran.c” ;
fclose(fp) ;
}

CU IDOL SELF LEARNING MATERIAL (SLM)


296 Computer Programming

Output:
OpenIng The File Kiran.c In Write Mode
Enter Some Text From Keyboard To Write In The File Kiran.c
Hai, How are you?
Closing the file kiran.c

12.3.12 fseek()
The fseek() function is used to set the file position indicator for the stream to a new position.
This function accepts three arguments. The first argument is the FILE stream pointer returned by
the fopen() function. The second argument ‘offset’ tells the amount of bytes to seek. The third
argument ‘whence’ tells from where the seek of ‘offset’ number of bytes is to be done. The available
values for whence are SEEK_SET, SEEK_CUR, or SEEK_END. These three values (in order)
depict the start of the file, the current position and the end of the file.
Upon success, this function returns 0, otherwise it returns -1.
int fseek(FILE *stream, long offset, int whence);
To perform Input/Output Operation on files we need below functions.

Table 12.4: Input/Output Functions

S. No. Function Operation Syntax


1 getc() Read a character from a file getc( fp)
2 putc() Write a character in file putc(c, fp)

3 fprintf() To write set of data in file fprintf(fp, “control string”, list)


4 fscanf() To read set of data from file. fscanf(fp, “control string”, list)
5 getw() To read an integer from a file. getw(fp)

6 putw() To write an integer in file. putw(integer, fp)

#include<stdio.h>
#include<string.h>
#define SIZE 1
#define NUMELEM 5

CU IDOL SELF LEARNING MATERIAL (SLM)


File Management 297

void main(void)
{
FILE* fd = NULL;
char buff[100];
memset(buff,0,sizeof(buff));
fd = fopen(“kiran.txt”, “rw+”);
if(NULL == fd)
{
printf(“\n fopen() Error!!!\n”);
return 1;
}
printf(“\n File opened successfully through fopen()\n”);
if(SIZE*NUMELEM != fread(buff,SIZE,NUMELEM,fd))
{
printf(“\n fread() failed\n”);
return 1;
}
printf(“\n Some bytes successfully read through fread()\n”);
printf(“\n The bytes read are [%s]\n”,buff);

if(0 != fseek(fd,11,SEEK_CUR))
{
printf(“\n fseek() failed\n”);
return 1;
}
printf(“\n fseek() successful\n”);
if(SIZE*NUMELEM != fwrite(buff,SIZE,strlen(buff),fd))

CU IDOL SELF LEARNING MATERIAL (SLM)


298 Computer Programming

{
printf(“\n fwrite() failed\n”);
return 1;
}
printf(“\n fwrite() successful, data written to text file\n”);
fclose(fd);
printf(“\n File stream closed through fclose()\n”);
getch( );
}
The code above assumes that you have a test file “kiran.txt” placed in the same location from
where this executable will be run.
Initially the content in file is:
$ cat kiran.txt
hello everybody
Now, run the code :
$ ./fileHandling
File opened successfully through fopen()
Some bytes successfully read through fread()
The bytes read are [hello]
fseek() successful
fwrite() successful, data written to text file
File stream closed through fclose()
Again check the contents of the file kiran.txt. As you see below, the content of the file was
modified.
$ cat kiran.txt
hello everybody
hello

CU IDOL SELF LEARNING MATERIAL (SLM)


File Management 299

Inbuilt File Handling Functions in C Language


C programming language offers many inbuilt functions for handling files. They are given
below:
Table 12.5: File Handing Functions

File handling functions Description


fopen () fopen () function creates a new file or opens an existing file.
fclose () fclose () function closes an opened file.
getw () getw () function reads an integer from file.
putw () putw () functions writes an integer to file.
getc (), fgetc () getc () and fgetc () functions read a character from file.
putc (), fputc () putc () and fputc () functions write a character to file.
fgets () fgets () function reads string from a file, one line at a time.
fputs () fputs () function writes string to a file.
feof () feof () function finds end of file.
fgetchar () fgetchar () function reads a character from keyboard.
fgetc () fgetc () function reads a character from file.
fprintf () fprintf () function writes formatted data to a file.
fscanf () fscanf () function reads formatted data from a file.
fgetchar () fgetchar () function reads a character from keyboard.
fputchar () fputchar () function writes a character from keyboard.
fseek () fseek () function moves file pointer position to given location.
SEEK_SET SEEK_SET moves file pointer position to the beginning of the file.
SEEK_CUR SEEK_CUR moves file pointer position to given location.
SEEK_END SEEK_END moves file pointer position to the end of file.
ftell () ftell () function gives current position of file pointer.
rewind () rewind () function moves file pointer position to the beginning of the file.
scanf () scanf () function reads formatted data from keyboard.
sscanf () sscanf () function Reads formatted input from a string.
remove () remove () function deletes a file.
fflush () fflush () function flushes a file.

CU IDOL SELF LEARNING MATERIAL (SLM)


300 Computer Programming

12.4 Summary
So far the operations using C program are done on a prompt / terminal which is not stored
anywhere. But in the software industry, most of the programs are written to store the information
fetched from the program. One such way is to store the fetched information in a file. Different
operations that can be performed on a file are:
1. Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w++”)
2. Opening an existing file (fopen)
3. Reading from file (fscanf or fgetc)
4. Writing to a file (fprintf or fputs)
5. Moving to a specific location in a file (fseek, rewind)
6. Closing a file (fclose)
The text in the brackets denotes the functions used for performing those operations.

12.5 Key Words/Abbreviations


File: While doing file handling we often use FILE for declaring the pointer in order to point
to the file we want to read from or to write on.
Append: Append mode  is  used  to append or  add  data  to  the  existing  data  of  file  (if  any).
Hence, when you open a file in Append(a) mode, the cursor is positioned at the end of the present
data in the file.
ASCII: Abbreviated from American Standard Code for Information Interchange.

12.6 Learning Activity


1. Write a program in C to copy contents of one file into other file..
.......................................................................................................................................
.......................................................................................................................................
2. Write a program in C to write a string into file 5 times.
.......................................................................................................................................
.......................................................................................................................................

CU IDOL SELF LEARNING MATERIAL (SLM)


File Management 301

3. Write a program in C to combine contents of two files in third file.


.......................................................................................................................................
.......................................................................................................................................

12.7 Unit End Questions (MCQ and Descriptive)


A. Descriptive Type: Short Answer Type Questions
1. Write a short note on file handling in C.
2. What are the two types of file handling in C?
3. Explain different input/output functions for C.
4. Explain different file operations in C language.
5. Explain different file Modes in C Language.
6. Explain difference between text file and binary file handling in C programming language.
7. Distinguish between (1) fprintf() (ii) fscanf()
8. Explain what are different methods to read text file with syntax and suitable example.
9. Explain how to read and write binary files with suitable example.
10. Explain what are different methods to write into a file with syntax and suitable example.
11. Explain fopen( ), fclose( ) functions with suitable example.
12. Explain fgetc( ) and fgets( ) functions with suitable examples.
13. Explain getw( ) and putw( ) functions with suitable example.
14. Explain fread( ) and fwrite( ) and fseek( ) functions with suitable example.

B. Multiple Choice/Objective Type Questions


1. What is the function of the mode ‘w+’?
(a) create text file for writing, discard previous contents if any
(b) create text file for update, discard previous contents if any
(c) create text file for writing, do not discard previous contents if any
(d) create text file for update, do not discard previous contents if any

CU IDOL SELF LEARNING MATERIAL (SLM)


302 Computer Programming

2. EOF is an integer type defined in stdio. hand has a value ____________.


(a) 1 (b) 0
(c) NULL (d) – 1
3. fwrite() can be used only with files that are opened in binary mode.
(a) true (b) false
4.  Which of the following true about FILE *fp?
(a) FILE is a keyword in C for representing files and fp is a variable of FILE type.
(b) FILE is a stream
(c) FILE is a buffered stream
(d) FILE is a structure and fp is a pointer to the structure of FILE typ
5. The first and second arguments of fopen() are
(a) A character string containing the name of the file & the second argument is the
mode
(b) A character string containing the name of the user & the second argument is the
mode
(c) A character string containing file pointer & the second argument is the mode
(d) None of the mentioned
Answers: 1. (b), 2. (d), 3. (a), 4. (d), 5. (a)

12.8 References
1. https://www.geeksforgeeks.org/basics-file-handling-c/
2. http://letsfindcourse.com/technical-questions/c/file-handling



CU IDOL SELF LEARNING MATERIAL (SLM)


C Basics and Control Structure 303

PRACTICAL C BASICS AND CONTROL


UNIT 1 STRUCTURE

PROGRAMS TO UNDERSTAND THE BASIC DATA TYPE AND I/O

1. Write a program that reads two nos. from keyboard and gives their addition,
subtraction, multiplication, division and modulo

/* program to print sum,sub,mul,div of two numbers */


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,sum,mul,div,sub;
clrscr();
printf("Enter First number ");
scanf("%d",&a);
printf("enter Second number ");
scanf("%d",&b);
sum=a+b;
printf("\n Addition of two numbers is %d",sum);
sub=a-b;
printf("\n substraction of two numbers is %d",sub);
mul=a*b;
printf("\n multiplication of two numbers is %d",mul);
div=a/b;
printf("\ndivision of two numbers is %d",div);
mod=a%b;

CU IDOL SELF LEARNING MATERIAL (SLM)


304 Computer Programming

printf("\nModulus of two numbers is %d",mod);


getch();
}
Output:

2. The distance between two cities (In KM) is input through keyboard. Write a
program to convert and print this distance in metres, feet, inches and centimetres.

#include<stdio.h>
#include<conio.h>
void main()
{
float km,m,cm,f,in;
clrscr();
printf("Enter distance in kilometres: ");
scanf("%f",&km);
m=km*1000;
cm=km*1000*100;
f=km*3280.84;
in=km*39370.08;
printf("The distance in feet: %f\n"f);
printf("The distance in inches: %f\n"in);
printf("The distance in metres: %f\n"m);
printf("The distance in Centifeet: %f\n"cm);
getch();
}

CU IDOL SELF LEARNING MATERIAL (SLM)


C Basics and Control Structure 305

Output:

3. Write a C program to perform post and preincrement, post and pre-decrement


operations.

/* Increment and Decrement Operators in C Example */


#include <stdio.h>
int main()
{
int x = 10,y = 20;
printf("----INCREMENT OPERATOR EXAMPLE---- \n");
printf("Value of x : %d \n", x); //Original Value
printf("Value of x : %d \n", x++); // Using increment Operator
printf("Value of x : %d \n", x); //Incremented value
printf("----DECREMENT OPERATOR EXAMPLE---- \n");
printf("Value of y : %d \n", y); //Original Value
printf("Value of y : %d \n", y--); // using decrement Operator
printf("Value of y : %d \n", y); //decremented value
return 0;
}
Output:

CU IDOL SELF LEARNING MATERIAL (SLM)


306 Computer Programming

4. Write a program which implements the working of all Bitwise operators

#include <stdio.h>
  int main()
{
int m = 40,n = 80,AND_opr,OR_opr,XOR_opr,NOT_opr ;
AND_opr = (m&n);
OR_opr = (m|n);
NOT_opr = (~m);
XOR_opr = (m^n);
printf("AND_opr value = %d\n",AND_opr );
printf("OR_opr value = %d\n",OR_opr );
printf("NOT_opr value = %d\n",NOT_opr );
printf("XOR_opr value = %d\n",XOR_opr );
printf("left_shift value = %d\n", m << 1);
printf("right_shift value = %d\n", m >> 1);
}
Output:
AND_opr value = 0
OR_opr value = 120
NOT_opr value = -41
XOR_opr value = 120
left_shift value = 80
right_shift value = 20

5. Write a program to select and print the largest of the three nos. using Nested-If-
Else statement.

1. #include <stdio.h>
2. int main() {
3. double n1, n2, n3;
4. printf("Enter three numbers: ");
5. scanf("%lf %lf %lf", &n1, &n2, &n3);

CU IDOL SELF LEARNING MATERIAL (SLM)


C Basics and Control Structure 307

6.
7. if (n1 >= n2) {
8. if (n1 >= n3)
9. printf("%.2lf is the largest number.", n1);
10. else
11. printf("%.2lf is the largest number.", n3);
12. } else {
13. if (n2 >= n3)
14. printf("%.2lf is the largest number.", n2);
15. else
16. printf("%.2lf is the largest number.", n3);
17. }
18.
19. return 0;
20. }
Output:

Enter three numbers: -4.5


3.9
5.6
5.60 is the largest number.

6. Write a program to perform arithmetic operations using switch case.

1. #include <stdio.h>
2. int main() {
3. char operator;
4. double first, second;
5. printf("Enter an operator (+, -, *,): ");
6. scanf("%c", &operator);
7. printf("Enter two operands: ");
8. scanf("%lf %lf", &first, &second);
9.

CU IDOL SELF LEARNING MATERIAL (SLM)


308 Computer Programming

10. switch (operator) {


11. case '+':
12. printf("%.1lf + %.1lf = %.1lf", first, second, first + second);
13. break;
14. case '-':
15. printf("%.1lf - %.1lf = %.1lf", first, second, first - second);
16. break;
17. case '*':
18. printf("%.1lf * %.1lf = %.1lf", first, second, first * second);
19. break;
20. case '/':
21. printf("%.1lf / %.1lf = %.1lf", first, second, first / second);
22. break;
23. // operator doesn't match any case constant
24. default:
25. printf("Error! operator is not correct");
26. }
27.
28. return 0;
29. }
Output:

Enter an operator (+, -, *,): *


Enter two operands: 1.5
4.5
1.5 * 4.5 = 6.8

7. Write a program to find sum of all integers greater than 100 and less than 200
and are divisible by 5.

#include<stdio.h>
#include<conio.h>
void main()

CU IDOL SELF LEARNING MATERIAL (SLM)


C Basics and Control Structure 309

{
int i, sum=0;
clrscr();
printf("\n Numbers between 100 and 200 which is divisible by 5");
for(i=101;i<200;i++)
     {
if(i%5==0)
          {
               printf("\n %d",i);
              sum= sum + i;
          }
     }
printf("\n sum = %d",sum);
     getch();
}
Output:
Numbers between 100 and 200 which is divisible by 5
105
110
115
120
125
130
135
140
145
150
155
160
165
170
175

CU IDOL SELF LEARNING MATERIAL (SLM)


310 Computer Programming

180
185
190
195
sum = 2850

x x x2 x3
8. Write a C program to implement e  1    ,
1! 2! 3!

/* Program for Exponential Series */


#include<stdio.h>
#include<conio.h>
void main()
{
int i, n;
float x, sum=1, t=1;
clrscr();
printf(“Enter the value for x : “);
     scanf(“%f”, &x);
  printf(“\nEnter the value for n : “);
     scanf(“%d”, &n);
 /* Loop to calculate the value of Exponential */
for(i=1;i<=n;i++)
{
t=t*x/i;
sum=sum+t;
}
printf(“\nThe Exponential Value of %f = %.4f”, x, sum);
getch();
}
Output:

CU IDOL SELF LEARNING MATERIAL (SLM)


Arrays, Strings, Functions and Structure 311

PRACTICAL ARRAYS, STRINGS,


UNIT 2 FUNCTIONS AND STRUCTURE

PROGRAMS TO UNDERSTAND THE BASIC DATA TYPE AND I/O

1. Write a program to perform various matrix operations Addition, Subtraction,


Multiplication, Transpose using switch-case statement

1. #include<stdio.h>
2. #define MAX 15
3. void main()
4. {
5. int A[MAX][MAX],B[MAX][MAX],C[MAX][MAX],I,J,K,M,N,R,S,CH;
6. clrscr();
7. printf("ENTER THE SIZE OF A MATRIX (M X N) : \n");
8. printf("ENTER VALUE FOR M (LESS THAN 15) :");
9. scanf("%d",&M);
10. printf("ENTER VALUE FOR N (LESS THAN 15) :");
11. scanf("%d",&N);
12. printf("\nENTER THE SIZE OF B MATRIX (R X S) : \n");
13. printf("ENTER VALUE FOR R (LESS THAN 15) :");
14. scanf("%d",&R);
15. printf("ENTER VALUE FOR S (LESS THAN 15) :");
16. scanf("%d",&S);
17. printf("\nSELECT UR CHOICE (1.ADD 2.SUB 3.MULT) : ");
18. scanf("%d",&CH);

CU IDOL SELF LEARNING MATERIAL (SLM)


312 Computer Programming

19. switch(CH)
20. {
21. case 1 :
22. {
23. if(M==R && N==S)
24. {
25. printf("ENTER %d X %d MATRIX A VALUES\n",M,N);
26. for(I=0;I<M;I++)
27. {
28. for(J=0;J<N;J++)
29. {
30. scanf("%d",&A[I][J]);
31. }
32. }
33. printf("ENTER %d X %d MATRIX B VALUES\n",R,S);
34. for(I=0;I<R;I++)
35. {
36. for(J=0;J<S;J++)
37. {
38. scanf("%d",&B[I][J]);
39. }
40. }
41. for(I=0;I<M;I++)
42. {
43. for(J=0;J<N;J++)
44. {
45. C[I][J]=A[I][J]+B[I][J];
46. }
47. }
48. printf("\nRESULT %d X %d MATRIX C VALUES ARE :\n",M,N);
49. for(I=0;I<M;I++)

CU IDOL SELF LEARNING MATERIAL (SLM)


Arrays, Strings, Functions and Structure 313

50. {
51. for(J=0;J<N;J++)
52. {
53. printf("%d\t",C[I][J]);
54. }
55. printf("\n");
56. }
57. }
58. else
59. {
60. printf("\nERROR : CONDITION FOR ADDITION");
61. printf(" MATRICES IS NOT SATISFIED!");
62. }
63. break;
64. }
65. case 2 :
66. {
67. if(M==R && N==S)
68. {
69. printf("ENTER %d X %d MATRIX A VALUES\n",M,N);
70. for(I=0;I<M;I++)
71. {
72. for(J=0;J<N;J++)
73. {
74. scanf("%d",&A[I][J]);
75. }
76. }
77. printf("ENTER %d X %d MATRIX B VALUES\n",R,S);
78. for(I=0;I<R;I++)
79. {
80. for(J=0;J<S;J++)

CU IDOL SELF LEARNING MATERIAL (SLM)


314 Computer Programming

81. {
82. scanf("%d",&B[I][J]);
83. }
84. }
85. for(I=0;I<M;I++)
86. {
87. for(J=0;J<N;J++)
88. {
89. C[I][J]=A[I][J]-B[I][J];
90. }
91. }
92. printf("\nRESULT %d X %d MATRIX C VALUES ARE :\n",M,N);
93. for(I=0;I<M;I++)
94. {
95. for(J=0;J<N;J++)
96. {
97. printf("%d\t",C[I][J]);
98. }
99. printf("\n");
100. }
101. }
102. else
103. {
104. printf("\nERROR : CONDITION FOR SUBTRACTION");
105. printf(" MATRICES IS NOT SATISFIED!");
106. }
107. break;
108. }
109. case 3 :
110. {
111. if(N==R)

CU IDOL SELF LEARNING MATERIAL (SLM)


Arrays, Strings, Functions and Structure 315

112. {
113. printf("ENTER %d X %d MATRIX A VALUES\n",M,N);
114. for(I=0;I<M;I++)
115. {
116. for(J=0;J<N;J++)
117. {
118. scanf("%d",&A[I][J]);
119. }
120. }
121. printf("ENTER %d X %d MATRIX B VALUES\n",R,S);
122. for(I=0;I<R;I++)
123. {
124. for(J=0;J<S;J++)
125. {
126. scanf("%d",&B[I][J]);
127. }
128. }
129. for(I=0;I<M;I++)
130. {
131. for(J=0;J<S;J++)
132. {
133. C[I][J]=0;
134. for(K=0;K<R;K++)
135. {
136. C[I][J]=C[I][J]+A[I][K]*B[K][J];
137. }
138. }
139. }
140. printf("\nRESULT %d X %d MATRIX C VALUES ARE :\n",M,S);
141. for(I=0;I<M;I++)
142. {

CU IDOL SELF LEARNING MATERIAL (SLM)


316 Computer Programming

143. for(J=0;J<S;J++)
144. {
145. printf("%d\t",C[I][J]);
146. }
147. printf("\n");
148. }
149. }
150. else
151. {
152. printf("\nERROR : CONDITION FOR MULTIPLICATION");
153. printf(" MATRICES IS NOT SATISFIED!");
154. }
155. break;
156. }
157. default:
158. {
159. printf("YOU ENTERED WRONG CHOICE !!!");
160. }
161. }
162. getch();
163. }
Output:

CU IDOL SELF LEARNING MATERIAL (SLM)


Arrays, Strings, Functions and Structure 317

2. Programs based on String Handling

(a) Program to accept name of the user through gets() and print string through puts()
function.
#include<stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
gets(name); //Function to read string from user.
printf("Name: ");
puts(name); //Function to display string.
return 0;
}
(b) Write a program in c to Calculate Length of String without Using strlen() Function

#include <stdio.h>
int main() {
char s[] = "Programming is fun";
int i;
for (i = 0; s[i] != '\0'; ++i);
printf("Length of the string: %d", i);
return 0;
}
Output:
Length of the string: 18
(c) Write a program in c to Copy String Without Using strcpy()

#include <stdio.h>
int main() {
char s1[100], s2[100], i;
printf("Enter string s1: ");
fgets(s1, sizeof(s1), stdin);

CU IDOL SELF LEARNING MATERIAL (SLM)


318 Computer Programming

for (i = 0; s1[i] != '\0'; ++i) {


s2[i] = s1[i];
}
s2[i] = '\0';
printf("String s2: %s", s2);
return 0;
}
Output:

Enter string s1: Hey fellow programmer.


String s2: Hey fellow programmer.

(d) Write a program in c to Remove Characters in String Except Alphabets


#include <stdio.h>
int main() {
char line[150];
printf("Enter a string: ");
gets(line);
for (int i = 0; line[i] != '\0'; ++i) {
while (!((line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' && line[i] <= 'Z') ||
line[i] == '\0')) {
for (int j = i; line[j] != '\0'; ++j) {
line[j] = line[j + 1];
}
line[j] = '\0';
}
}
printf("Output String: ");
puts(line);
return 0;
}

CU IDOL SELF LEARNING MATERIAL (SLM)


Arrays, Strings, Functions and Structure 319

Output:

Enter a string: p2'r-o@gram84iz./


Output String: programiz

3. Write a program using function to implement Pascal Triangle

#include<stdio.h>
int main() {
int rows, coef=1, space, i, j;
printf("Enter number of rows: ");
scanf("%d", &rows);
for (i=0; i<rows; i++) {
for (space=1; space <= rows-i; space++)
printf(" ");
for (j=0; j<=i; j++) {
if (j==0 || i==0)
coef = 1;
else
coef=coef*(i-j+1)/j;
printf("%4d", coef);
}
printf("\n");
}
return 0;
}

CU IDOL SELF LEARNING MATERIAL (SLM)


320 Computer Programming

4. Write a program that used user Defined Function


Swap ( ) and interchange the value of two variable.
#include <stdio.h>
// This function swaps values pointed by xp and yp
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
   int main()
{
int x, y;
printf("Enter Value of x ");
scanf("%d", &x);
printf("\nEnter Value of y ");
scanf("%d", &y);
swap(&x, &y);
     printf("\nAfter Swapping: x = %d, y = %d", x, y);
return 0;
}
Output:
Enter Value of x 12
Enter Value of y 14
After Swapping: x = 14, y = 12

5. Write a function prime that return 1 if it ‘s argument is prime and return 0


otherwise
#include
#include
int prime(int);
int main()

CU IDOL SELF LEARNING MATERIAL (SLM)


Arrays, Strings, Functions and Structure 321

{
int n,p;
clrscr();
printf(“Enter a number : “);
scanf(“%d”,&n);
p=prime(n);
if(p==1)
printf(“%d is prime\n”,n);
else
printf(“%d is not prime\n”,n);
getch();
return 0;
}
int prime(int n)
{
int i;
for(i=2;i<n;i++)
{
if(n%i==0)
return 0;
}
return 1;
}
Output:

Enter a number : 18
18 is not prime
Enter a number : 5
5 is prime

CU IDOL SELF LEARNING MATERIAL (SLM)


322 Computer Programming

6. Define a structure type, personal, that would contain person name, date of joining
and salary. Using this structure, write a program to read this information for one
person from the key board and print the same on the screen.

#include <stdio.h>
struct personal
{
char person_name[100];
char join_date[100];
float salary;
};
struct personal p;
int main()
{
printf("Enter Name of the person :- ");
scanf("%s",p.person_name);
printf("Enter Joining Date of the person :- ");
scanf("%s",p.join_date);
printf("Enter Salary of the person :- ");
scanf("%f",&p.salary);
printf("\nName of the person :- %s\n",p.person_name);
printf("Joining Date of the person :- %s\n",p.join_date);
printf("Salary of the person :- %0.2f\n",p.salary);
}
Output:

Enter Name of the person :- Kiran


Enter Joining Date of the person :- 6th Dec,2000
Enter Salary of the person :- 25000
Name of the person :- Kiran
Joining Date of the person :- 6th Dec,2000
Salary of the person :- 25000

CU IDOL SELF LEARNING MATERIAL (SLM)


Arrays, Strings, Functions and Structure 323

7. Define a structure called cricket that will describe the following


information:player name,team name,batting average.Using cricket,declare an
array player with 5 elements and write a program to read the information about
all the 5 players and print a teamwise list containing names of player with their
batting average.

#include<stdio.h>
#include<conio.h>
#include<string.h>
struct cricket
{
char nm[20],team[20];
int avg;
};
#define total 5
int main()
{
struct cricket player[total],temp;
int i,j;
clrscr();
for(i=0;i<total;i++)
{
printf(“For player %d\n”,i+1);
printf(“Enter the name of player : “);
fflush(stdin);
gets(player[i].nm);
printf(“Enter the team : “);
fflush(stdin);
gets(player[i].team);
printf(“Enter the batting average : “);
fflush(stdin);
scanf(“%d”,&player[i].avg);
}
printf(“\nTeam Name Average\n”);

CU IDOL SELF LEARNING MATERIAL (SLM)


324 Computer Programming

printf(” \n”);
for(i=0;i<total;i++)
{
printf(“%-10s %-10s %7d\n”,player[i].team,player[i].nm,player[i].avg);
}
getch();
return 0;
}

Output:
For player 1
Enter the name of player : Radhe
Enter the team : India
Enter the batting average : 100
For player 2
Enter the name of player : Tiwari
Enter the team : Pakistan
Enter the batting average : 5
For player 3
Enter the name of player : Tendulkar
Enter the team : India
Enter the batting average : 45
For player 4
Enter the name of player : Dhoni
Enter the team : India
Enter the batting average : 48
For player 5
Enter the name of player : Yuvi
Enter the team : India
Enter the batting average : 39
Team Name Average
India Radhe 100
Pakistan Tiwari 5
India Tendulkar 45
India Dhoni 48
India Yuvi 39

CU IDOL SELF LEARNING MATERIAL (SLM)


Pointers and DMA 325

PRACTICAL POINTERS AND DMA


UNIT 3

PROGRAMS ON POINTERS

1. Write a program using pointer and function to determine the length of string.

#include <stdio.h>
#include <string.h>
int main()
{
char a[100];
int length;
printf("Enter a string to calculate its length\n");
gets(a);
length = strlen(a);
printf("Length of the string = %d\n", length);
return 0;
}
Output:

CU IDOL SELF LEARNING MATERIAL (SLM)


326 Computer Programming

2. Write a program using pointer to compare two strings

#include <stdio.h>
//Macro for maximum number of characters in a string
#define MAX 100
int main()
{
//declare string variables
char str1[MAX]={0};
char str2[MAX]={0};

int loop; //loop counter


int flag=1;

//declare & initialize pointer variables


char *pStr1=str1;
char *pStr2=str2;

//read strings
printf("Enter string 1: ");
scanf("%[^\n]s",pStr1);
printf("Enter string 2: ");
getchar(); //read & ignore extra character
scanf("%[^\n]s",pStr2);

//print strings
printf("string1: %s\nstring2: %s\n",pStr1,pStr2);

//comparing strings
for(loop=0; (*(pStr1+loop))!='\0'; loop++)
{
if(*(pStr1+loop) != *(pStr2+loop))
{
flag=0;

CU IDOL SELF LEARNING MATERIAL (SLM)


Pointers and DMA 327

break;
}
}
if(flag)
printf("Strings are same.\n");
else
printf("Strings are not same.\n");
return 0;
}
Output:

3. Write a program using pointer to concatenate two strings.


#include <stdio.h>
#include <string.h>
int main()
{
char a[1000], b[1000];
printf("Enter the first string\n");
gets(a);
printf("Enter the second string\n");
gets(b);
strcat(a, b);
printf("String obtained on concatenation: %s\n", a);
return 0;
}

CU IDOL SELF LEARNING MATERIAL (SLM)


328 Computer Programming

Output:

4. Write a program using pointer to copy one string to another string

#include <stdio.h>
#include <string.h>
int main()
{
char source[1000], destination[1000];
printf("Input a string\n");
gets(source);
strcpy(destination, source);
printf("Source string: %s\n", source);
printf("Destination string: %s\n", destination);
return 0;
}
Output:

CU IDOL SELF LEARNING MATERIAL (SLM)


Pointers and DMA 329

5. Write a program using pointer to read an array if integer and print element in
reverse order.

#include <stdio.h>
int main()
{
   int n, c, d, a[100], b[100];
printf("Enter the number of elements in array\n");
scanf("%d", &n);
printf("Enter array elements\n");
for (c = 0; c < n ; c++)
     scanf("%d", &a[c]);
// Copying elements into array b starting from the end of array a
for (c = n - 1, d = 0; c >= 0; c--, d++)
b[d] = a[c];
// Copying reversed array into the original, we are modifying the original array.
for (c = 0; c < n; c++)
    a[c] = b[c];
printf("The array after reversal:\n");
for (c = 0; c < n; c++)
printf("%d\n", a[c]);
return 0;
}
Output:

CU IDOL SELF LEARNING MATERIAL (SLM)


330 Computer Programming

6. Write a program that uses a table of integers whose size will be specified
interactively at run time.

#include <stdio.h>
#include <stdlib.h>
void main()
{
int *p, *table;
int size;
printf("\nWhat is the size of table?");
scanf("%d",&size);
printf("\n");
if((table = (int*)malloc(size *sizeof(int))) == 0)
        {
            printf("No space available \n");
            exit(1);
        }
printf("\n Address of the first byte is %u \n", table);
/* Reading table values*/
printf("\nInput table values\n");
for (p=table; p<table + size; p++)
scanf("%d",p);
     /* Printing table values <span id="IL_AD3" class="IL_AD">in reverse</span>
order*/
     for (p = table + size -1; p >= table; p --)
        printf("%d is stored at address %u \n",*p,p);
getch();
}

CU IDOL SELF LEARNING MATERIAL (SLM)


Pointers and DMA 331

Output:
What is the size of the table? 5
Address of the first byte is 2262
Input table values
11 12 13 14 15
15 is stored at address 2270
14 is stored at address 2268
13 is stored at address 2266
12 is stored at address 2264
11 is stored at address 2262
7. C program to input and print text using Dynamic Memory Allocation

/*C program to input and print text


using Dynamic Memory Allocation.*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
char *text;
printf("Enter limit of the text: ");
scanf("%d",&n);
/*allocate memory dynamically*/
text=(char*)malloc(n*sizeof(char));
printf("Enter text: ");
scanf(" "); /*clear input buffer*/
gets(text);
printf("Inputted text is: %s\n",text);
/*Free Memory*/
free(text);
return 0;
}

CU IDOL SELF LEARNING MATERIAL (SLM)


332 Computer Programming

Output:

Enter limit of the text: 100


Enter text: I am mike from California, I am computer geek.
Inputted text is: I am mike from California, I am computer geek.

CU IDOL SELF LEARNING MATERIAL (SLM)


C Pre-Processor and File Management 333

PRACTICAL C PRE-PROCESSOR AND


UNIT 4 FILE MANAGEMENT

PROGRAMS ON BASIC FILE HANDLING OPERATIONS

1. Write a program which reads diameter and height of a cone and calculate its
volume using macros.
*
* C Program to Find the volume and surface area of cone
*/
#include <stdio.h>
#include <math.h>
int main()
{
  float radius, height;
float surface_area, volume;
  printf("Enter value of radius and height of a cone :\n ");
scanf("%f%f", &radius, &height);
surface_area = (22 / 7) * radius * (radius + sqrt(radius * radius + height * height));
volume = (1.0/3) * (22 / 7) * radius * radius * height;
printf("Surface area of cone is: %.3f", surface_area);
printf("\n Volume of cone is : %.3f", volume);
return 0;
}

CU IDOL SELF LEARNING MATERIAL (SLM)


334 Computer Programming

2. Write a C program to read file kiran.txt and all data character wise.

#include<stdio.h>
void main()
{
FILE *fp;
char ch;
clrscr();
fp=fopen("kiran.txt","r");
if(fp==NULL)
{
printf("file does not exists");
}
else
{
while(ch!=EOF)
{
ch=getc(fp);
putch(ch);
}
}
fclose(fp);
getch();
}
3. Write a program in C program to illustate fgetc() function

#include <stdio.h>
int main ()
{
// open the file
FILE *fp = fopen("test.txt","r");
   // Return if could not open file

CU IDOL SELF LEARNING MATERIAL (SLM)


C Pre-Processor and File Management 335

     if (fp == NULL)


       return 0;
   do
     {
// Taking input single character at a time
         char c = fgetc(fp);
   // Checking for end of file
         if (feof(fp))
             break ;
         printf("%c", c);
     }   while(1);
   fclose(fp);
     return(0);
}
4. Write a C program to illustate fputc() function

#include<stdio.h>
int main()
{
     int i = 0;
     FILE *fp = fopen("output.txt","w");
     // Return if could not open file
     if (fp == NULL)
       return 0;
     char string[] = "good bye", received_string[20];
   for (i = 0; string[i]!='\0'; i++)
   // Input string into the file
// single character at a time
         fputc(string[i], fp);
   fclose(fp);
     fp = fopen("output.txt","r");

CU IDOL SELF LEARNING MATERIAL (SLM)


336 Computer Programming

   // Reading the string from file


     fgets(received_string,20,fp);
   printf("%s", received_string);
   fclose(fp);
return 0;
}
Output:
good bye

CU IDOL SELF LEARNING MATERIAL (SLM)

You might also like