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

Arthi

The document is a textbook titled 'Structured Programming Using C' authored by Dr. R.J. Aarthi and R. Vaishali, published by Bharath Institute of Higher Education and Research in 2025. It covers various aspects of structured programming, including problem-solving, program design, implementation issues in C, algorithms, and data structures. The content is organized into units that address topics such as arrays, strings, pointers, and file handling, aimed at equipping students with essential programming skills.

Uploaded by

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

Arthi

The document is a textbook titled 'Structured Programming Using C' authored by Dr. R.J. Aarthi and R. Vaishali, published by Bharath Institute of Higher Education and Research in 2025. It covers various aspects of structured programming, including problem-solving, program design, implementation issues in C, algorithms, and data structures. The content is organized into units that address topics such as arrays, strings, pointers, and file handling, aimed at equipping students with essential programming skills.

Uploaded by

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

STRUCTURED PROGRAMMING USING C

(U24CSTJ02)

Dr. R.J. Aarthi

Assistant Professor, Computer Science and Engineering Department,

School of Computing,

Bharath Institute of Higher Education and Research,

Chennai.

R.Vaishali

Assistant Professor, Computer Science and Engineering Department,

School of Computing,

Bharath Institute of Higher Education and Research,

Chennai.
Title : Structured Programming Using C

Author : Dr. R.J.Aarthi, First Edition

Copyright © 2025 Bharath Institute of Higher Education and Research, Chennai, India

All rights reserved. No part of this publication may be reproduced or transmitted in any form or by any
means, electronic or mechanical, including photocopy, recording or any information storage or retrieval
system, without permission in writing from the publisher

ISBN : 978-93-342-0987-7

Product code : BIHER-CSE-2025-01-002

Pages : 129

Price : 100/-

Published by :

Bharath Institute of Higher Education and Research

173 Agharam Road,

Selaiyur,

Chennai 600073,

India

Phones : 91- 044-22290125, 22290742

E-mail :[email protected]

Website : www.bharathuniv.ac.in

Printed at Bharath Institute of Higher Education and Research, Chennai, India


ACKNOWLEDGEMENT
I express my thankfulness to the Higher Authorities of Bharath Institute of Higher Education and
Research for providing adequate facilities to carry out this text book work.

I express my sincere and profound thanks to Dr.S.Neduncheliyan, Professor and Dean, School of
Computing, Bharath Institute of Science and Technology, Bharath Institute of Higher Education and
Research, for his sustained constant support and encouragement during the crucial hours of this text
book preparation.

I am deeply grateful to Dr. S. Maruthuperumal, Professor, HoD, Department of Computer


Science and Engineering, School of Computing, Bharath Institute of Science and Technology, Bharath
Institute of Higher Education and Research, for his enduring, consistent inspiration and support
throughout the critical hours of the preparation of this textbook.

I appreciate the teamwork and dedication of my colleague Ms. R. Vaishali for her timely help in
accomplishing this work.

I express my sincere thanks to the Teaching Staff and Non-Teaching Staff of the Department of
CSE, Bharath Institute of Higher Education and Research, for their help and encouragement throughout
the tenure of this book work.

I record a cordial acknowledgement to the Librarian, General Library and Department Library for
their encouragement and assistance for their constant support and encouragement during this book
preparation.

My heartfelt thanks go to my husband in helping to complete the textbook in a stipulated time


period.

Dr.R.J.Aarthi

Assistant Professor/CSE/BIHER
Contents
1 UNIT-I PROBLEM SOLVING

1.1. Computer-Based Problem Solving 1

1.2. Program Design Issues 2

1.3. Program Implementation Issues in C 3

1.4. Algorithms for Problem solving 5

1.5. Number theory algorithm 5

1.6. Algorithm on ordered set of elements 7

1.7. Solving quadratic equations 10

1.8. Tower of Hanoi Algorithm 12

1.9. Operations on Matrices 14

2 UNIT-II : OVERVIEW OF C, FUNCTIONS

2.1. Overview 18

2.2. Data Types 20

2.3. Type Qualifiers 22

2.4. Tokens 24

2.5. Scope of a variable 47

2.6. Scope Rules 49

2.7. Storage Classes 51

2.8. Designing Structured Programs 54

2.9. Function 56

2.10. Types of Functions 57

2.11. Parameter Passing Techniques 59

2.12. Categories of Functions 61

2.13. Recursion: Recursive Functions 62

3 UNIT III: ARRAYS, STRINGS

3.1. Accessing Array Elements 65

3.2. Initialization of Arrays 66

3.3. Applications of Arrays 66


3.4. Two Dimensional Array 74

3.5. Introduction to multi-dimensional arrays 77

3.6. Strings and String Handling Functions 79

4 UNIT IV POINTERS

4.1. Introduction 86

4.2. Pointers arithmetic 88

4.3. Pointers for Inter-Function Communications 90

4.4. Pointer to Pointers 91

4.5. Arrays and Pointers 92

4.6. Array of Pointers 94

4.7. Pointer to Array 96

4.8. Pointers to void 97

4.9. Command Line arguments 98

4.10. Array of Pointers 99

4.11. Pointers as Function Arguments 100

4.12. Dynamic Memory Allocation 101


5 UNIT 5 STRUCTURES, UNIONS, ENUMERATED TYPES AND FILES

5.1. Type Definition 104

5.2. Enumerated types 105

5.3. Structure: Introduction 108

5.4. Nested structures 113

5.5. Arrays of Structures 115

5.6. Structures and Functions 117

5.7. Functions using structure 120

5.8. Pointers to Structures 121

5.9. Self Referential Structures 122

5.10. Union 124


5.11. Files 126

5.12. Introduction to Files 126

5.13. Modes of File Operations 127


Structured Programming Using C

1. UNIT-I PROBLEM SOLVING

Introduction to computer based problem solving-, Program design and


implementation issues, Algorithms for problem solving: Simple problems based
on number theory, Operations on ordered set of elements, Solving quadratic
equations, Operations on matrices.-Tower of Hanoi

1.1. Computer-Based Problem Solving

Computer-based problem solving is a process of using computers and related


technologies to analyze, design, and implement solutions to various challenges or tasks. In
today’s world, where computers play a significant role in almost every field, learning how to use
them effectively for problem-solving is an essential skill. It helps students and professionals
tackle complex issues with precision, speed, and efficiency.

The process of computer-based problem solving typically involves the following steps:

Figure 1.1

Computer-based problem solving is used in a wide range of fields, such as:

1
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

 Education: Automating tasks like grading exams, managing student records, and
designing learning tools
 Healthcare: Developing software for patient management, diagnosing diseases, and
designing medical equipment
 Business: Analyzing customer data, managing inventory, and optimizing supply chains
 Science and Engineering: Simulating experiments, solving mathematical equations, and
designing complex systems

It is generally known that there are several advantages in using computers for problem
solving. Some of the key benefits are:

 Speed and Accuracy: Computers can process large amounts of data quickly and perform
calculations with high precision
 Automation: Repetitive tasks can be automated, saving time and effort
 Scalability: Solutions can be designed to handle large-scale problems
 Creativity and Innovation: Computers enable users to explore new ideas and create
innovative solutions

For students, learning computer-based problem solving involves understanding basic


programming concepts, algorithms, and logic. Popular tools and languages like C, Python, and
Java are excellent starting points. Students can practice by solving real-world problems, such as
designing a program to calculate budgets, create games, or manage to-do lists.

In conclusion, computer-based problem solving equips individuals with the tools to


address challenges effectively in a technology-driven world. By mastering this skill, students can
unlock a world of possibilities and make meaningful contributions to society.

1.2. Program Design Issues

Program design issues refer to challenges and considerations that arise during the
planning and development of a software program. These issues are critical to ensuring that the
program is efficient, maintainable, reliable, and meets the user’s requirements. Addressing
design issues early in the development process helps to avoid problems later during
implementation, testing, or deployment.

1. Lack of Clear Problem Definition


o Issue: Without a clear understanding of the problem to solve, the design can
become chaotic
o Solution: Spend time defining the problem clearly. Identify input, output,
constraints, and edge cases before coding
2. Poor Structuring of Programs
o Issue: C does not offer object-oriented programming (OOP) natively, so
structuring large programs can be difficult
2
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

o Solution: Use modular programming principles, splitting code into separate


header (.h) and source files (.c) based on functionality. Organize code into
functions that perform distinct tasks
3. Global State Mismanagement
o Issue: Relying too much on global variables makes the program hard to debug,
maintain, and test
o Solution: Minimize global variables. Instead, pass data between functions using
arguments or return values. If state is required, encapsulate it using structs
4. Insufficient Error Handling Strategy
o Issue: Error cases are often neglected, leading to crashes or undefined behavior
o Solution: Include comprehensive error handling strategies for all system calls and
external dependencies. Use error codes, errno, and logging to ensure robustness
5. Misuse of Data Structures
o Issue: Choosing the wrong data structure can lead to performance bottlenecks or
incorrect behavior
o Solution: Choose appropriate data structures based on the problem at hand. For
example, arrays for contiguous data, linked lists for dynamic data, and hash tables
or binary trees for fast lookups
6. Undefined and Unclear Interfaces
o Issue: Poorly defined interfaces between functions or modules make integration
difficult and lead to coupling
o Solution: Design clear, simple, and well-documented interfaces. Use header files
for declarations and avoid exposing internal implementation details

1.3. Program Implementation Issues in C

Program implementation issues refer to challenges and considerations that arise during
the process of translating a program's design into actual working code. These issues can affect
the functionality, performance, and maintainability of the software and may involve technical,
logical, or practical difficulties encountered during coding, testing, or deployment.

1. Memory Management
o Issue: Manual memory management (using malloc, calloc, realloc, and free) can
lead to memory leaks, segmentation faults, and dangling pointers
o Solution: Always free memory when no longer needed, and ensure every malloc
has a corresponding free. Use tools like Valgrind to detect memory leaks
2. Buffer Overflows
o Issue: C lacks bounds checking for arrays, which can lead to buffer overflows and
security vulnerabilities
o Solution: Always ensure that you are not writing beyond the bounds of an array.
Use functions like snprintf instead of sprintf to limit buffer sizes. Be careful with
functions like strcpy, gets, and scanf
3. Pointer Mismanagement

3
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

o Issue: Pointers are a powerful but dangerous feature in C. Misusing them can lead
to crashes, memory corruption, or undefined behavior
o Solution: Ensure proper initialization, dereferencing, and freeing of pointers.
Avoid wild, dangling, or null pointers. Prefer using NULL over uninitialized
pointers
4. Concurrency and Race Conditions
o Issue: In multithreaded programs, improper handling of shared resources can lead
to race conditions
o Solution: Use synchronization primitives like mutexes (pthread_mutex_lock/
pthread_mutex_unlock) to protect shared resources. Design thread-safe functions
5. Off-by-One Errors
o Issue: Common in loops and array handling, where a loop runs one time too many
or too few, leading to incorrect results or crashes
o Solution: Double-check boundary conditions in loops and array indexing. Use
clear loop conditions and be mindful of zero-based indexing in C arrays
6. Inefficient Algorithms
o Issue: The algorithm chosen for a task may perform poorly as data size grows
o Solution: Analyze algorithm complexity and choose efficient algorithms for
sorting, searching, and other operations. Consider the trade-offs between time and
space complexity
7. Unintended Side Effects
o Issue: Modifying a variable unintentionally inside a function can lead to bugs that
are hard to trace
o Solution: If a function does not need to modify data, pass parameters by value
rather than by reference. Use the const keyword to prevent accidental
modification
8. Portability Issues
o Issue: C programs might not be portable across different platforms due to system-
specific dependencies
o Solution: Write platform-independent code by adhering to standard libraries
(stdio.h, stdlib.h, etc.) and using macros for system-specific behavior
9. Undefined Behavior
o Issue: Certain actions in C (e.g., dividing by zero, using uninitialized variables)
lead to undefined behavior
o Solution: Avoid risky operations and ensure all variables are initialized before
use. Use static analysis tools to catch potential undefined behavior
10. Compilation and Linking Errors
o Issue: Misconfigured makefiles, unresolved symbols, and header file
dependencies can cause build issues
o Solution: Use tools like make and gcc flags (-Wall, -Wextra) to catch issues
early. Ensure proper inclusion of libraries and header files. Use dependency
management tools when applicable

By being aware of these design and implementation issues, common mistakes can be
4
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

proactively avoided and robustness, maintainability, and performance of programs can be


improved.

1.4. Algorithms for Problem solving

Algorithms are step-by-step procedures or formulas designed to solve specific problems


systematically. In problem-solving, they provide a structured approach to achieve the desired
outcome. Algorithms help in breaking down complex tasks into smaller, manageable steps,
ensuring clarity and precision in execution. They are widely used in various domains like
mathematics, computer programming, and data analysis. An effective algorithm is efficient,
accurate, and scalable, making it a fundamental tool in tackling real-world challenges and
developing innovative solutions.

1.5. Number theory algorithm

Number theory is a branch of mathematics focused on the study of integers and integer-
valued functions. It explores properties of numbers, particularly prime numbers, and other
mathematical concepts such as rational numbers and modular arithmetic.

This field has significant applications in modern computing, including cryptography,


coding theory, random number generation, and computer graphics. Its principles form the
backbone of secure communication systems and various algorithmic processes.

Number Theory Algorithms

Number theory algorithms are a specialized category within data structures and
algorithms. They are used for tasks like primality testing, which determines whether a given
number is prime, and other operations involving divisibility, modular arithmetic, and number
factorization.

Here are some of the examples of number theory algorithms.

Greatest Common Divisior (GCD) Least Common Multiple (LCM)


The GCD of a given set of two or The LCM of a given set of two or
more numbers is the largest number that more numbers in the smallest number that can
divides all of the numbers. The GCD of two be divided by all the numbers. The LCM of a
numbers can be determined using the given set of numbers can be determined using
following method: the following method:
 Write the divisors of all numbers  Write the given number in the form of
separately. prime factors
 List the common divisors of all the  Multiply all the prime factors but
numbers. remember to inclufe the common
factors only once.
 Now, check which divisor is the highest
5
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

in all the numbers.  LCM of 60 and 90,


60 = 2 x 2 x 3 x 5
For example, GCD of 20, 28 can be 90 = 2 x 3 x 3 x 5
computed as , The product of all prime
Divisors of 20 : 1, 2, 4, 5, 10, 20 factors = 2 x 2 X 3 x 3 x 5 = 180
Divisors of 28 : 1, 2, 4, 7, 14, 28 LCM of 60, 90 is 180.
GCD of 20, 28 is 4

Euclidean Algorithm
To find Greatest Common Divisor GCD(A,B), the below algorithm can be used

 If A = 0, then GCD(A,B) = B, since the GCD(O,B) = B and it can be stopped


 If B = 0, then GCD(A<B) = A, since the GCD(A,0) = A and it can be stopped
 Write A in quotient, remainder form,
A=B*Q+R
where A and B are input numbers, Q is the quotient and R is the remainder.
 Iteration 1 : Find GCD(B,R) using the Euclidean algorithm, since GCD(A,B) = GCD(B,R).
Example: GCD(270, 192)
Given A = 270 B = 192
Here, A ≠ 0, and B ≠ 0,
Using Long division method to find , 270 / 192 = 1 with a remainder of 78, this can be
written as, 270 = 192 * 1 +78.
 Iteration 2 : Find GCD(192,78), since GCD(270,192) = GCD(192,78).
Given A = 192 B = 78
Here, A ≠ 0, and B ≠ 0,
Using Long division method to find , 192 / 78 = 2 with a remainder of R = 36, this can be
written as, 192 = 78 * 2 +36.
 Iteration 3 : Find GCD(78,36), since GCD(192,78) = GCD(78, 36).
Given A = 78 B = 36
Here, A ≠ 0, and B ≠ 0,
Using Long division method to find, 78 / 36 = 2 with a remainder of R = 6, this can be
written as, 78 = 36 * 2 + 6.
 Iteration 4 : Find GCD(36, 6), since GCD(78, 36) = GCD(36, 6).
Given A = 36 B=6
Here, A ≠ 0, and B ≠ 0,
Using Long division method to find, 36 / 6 = 6 with a remainder of R = 0, this can be written
as, 36 = 6 * 6 + 0.
 Iteration 5 : Find GCD(36, 6) = GCD(6, 0).
Given A = 6 B=0
Here, A ≠ 0, and B = 0,

6
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

It is shown that,
GCD(270,192) = GCD(192,78) = GCD(78, 36) = GCD(36, 6)= GCD(6, 0) = 6.
In general, GCD(A,0) = A and GCD(0, B) = B, If A = B * Q + R and B ≠ 0, then,
GCD(A,B) = GCD(B,R), where Q is an integer, R is an integer between 0 and B-1.

There are numerous applications of number theory including


 Prime numbers in cryptography.
 The Euclidean algorithm is used to compute modular multiplicative inverse in the
RSA (Rivest-Shamir-Adleman) – key encryption method in cryptography.

1.6. Algorithm on ordered set of elements

An algorithm on an ordered set of elements refers to a systematic procedure designed to


perform operations on a collection of items arranged in a specific sequence (e.g., ascending or
descending order). A data structure known as an ordered set maintains elements in a certain
order, such as the order in which they were added. A set data structure is defined in computer
science as a data structure that holds a group of unique components. When storing and working
with a collection of distinct items, this basic data structure is utilized. The set's signature attribute
is that it does not allow duplicate elements.

Among the operations that can be carried out on ordered sets are:

 Finding the k-th element in a set


 Finding the order of an element in a set
 Inserting an element into a set
 Checking if a set contains an element
 Deleting an element from a set

Some implementations of ordered sets include:


Hash based set and Tree based set such as Binary balanced trees, Segment trees, and
Binary indexed trees, arrays, linked lists, and hash tables.

Need for Set Data Structure

A Set is a data structure that is reliant on the programming language. Every language uses
a different data structure to implement a set data structure internally like C++ uses Self-
Balancing BST. Java, Python, C#, and JavaScript use Hash tables. In C programming ordered set
of elements can be implemented with the basic data structure array with the indexing.

7
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

In many computer science applications, including as databases, data analysis, and


algorithms, set data structures are frequently utilized. Using a set data structure has the primary
benefit of enabling you to efficiently and systematically carry out actions on a group of elements.

Ordered Set

An Ordered set is the common set data structure and is generally implemented using
balanced Binary Search Tree (BST) and it supports O(log n) lookups, insertions and deletion
operations.

The basic operations on ordered set of elements are insertion, deletion, searching, sorting
in the array of elements in C programming language.

Self-Balancing Binary Trees (BST) are used in C++ sets. With this method, the elements
are kept in binary tree nodes, which have the characteristic that only elements smaller than the
node's value may be found in the left subtree of any node, and only elements bigger than the
node's value can be found in the right subtree. This characteristic guarantees that the tree's
components are consistently arranged in ascending order.

The nodes in the BST can be implemented in C language with the help of self-referential
structure which contains the struct node *ptr which points to the members of the same structure.
This will create the nodes of the linked list. Many nodes can be created using the above structure.
Link can be implemented with the pointer variable as the member of the node of struct datatype.

Also basic insertion, deletion, and searching a value in an array can be implemented.

 To insert an element in an array of n elements:


o Input the position in an array, which is the index+1 element of the array
o Input the value of the element to be inserted into the array at that position
o Starting from the n-1 element of the array till the index of the input position are
pushed back, to create a space to insert
o If it reaches the position index, insert the new value at the index

Figure 1.2

 To delete an element in an array of n elements:


o Input the position in an array, which is the index+1 element of the array
8
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

o From the positional index, till the end of the array the elements at position is replaced
with the consecutive elements

Figure 1.3

o The array size is reduced to n-1 after removing the element

 To search an element in an array by providing the input value:


o Begin from the 0th index till the n-1 index, the values are checked with the matching
input value
o If the value exists , the index is returned with the value
o If the value does not exist throughout the traversal of array, it concludes the non-
existence of the value

 To add an element to the set implemented with a BST, start at the root of the tree and
compare the element to the node’s value:
o If the element is less than the node’s value, traverse to the left subtree and repeat
the process
o If the element is greater than the node’s value, traverse to the right subtree and
repeat the process
o If a node with the same value as the element is reached, the element is not added
to the tree, as duplicates are not allowed
 To remove an element from the set implemented with a BST, you first search for the node
containing the element, following the same process as adding an element
o If the element is not found in the tree, there is nothing to remove
o If the element is found, there are three cases to consider:
 The node has no children: In this case, the node is simply removed
from the tree
 The node has one child: In this case, the node can be replaced with
its child
 The node has two children: In this case, the minimum element in
the right subtree of the node is found out (i.e., the leftmost node in
the right subtree) and replaces the node’s value with that element.
Then, the duplicate element from the right subtree is removed

9
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

In the case of implementation of Set using Hash table (as happens in Python) the
implementation happens in the following way:
 To add an element to the set:
o Generate a hash value (say entry) for the key to be inserted
o Go to the entry in the hash table and check if there are already other entries or not
o If the slot is empty add the new element there
o Otherwise, if there are other entries, traverse to the end of that entry list and add
the new element there
 To remove an element from the set:
o First, generate the hash value for the element
o If the hash value is invalid or there are no entries then return an error message
o Otherwise, go to that slot and find the element from the list present in that slot
o Then remove that element from the hash table
 Applications of Set Data Structure:
Sets are abstract data types that can be used to store unique elements in a collection. Here
are some common applications of sets:
o Removing duplicates: If you have a large collection of data, you can use a set to
easily remove duplicates and store only unique elements
o Membership testing: Sets provide efficient operations for checking if an element
is a member of the set, which is useful in various algorithms and data structures
o Set operations: Sets can be used to perform operations such as union,
intersection, and difference, which are useful in mathematical set theory and
computer science
o Graph algorithms: Sets can be used to represent vertices and edges in graph
algorithms, allowing for efficient operations such as finding connected
components, detecting cycles, and computing minimum spanning trees
o Cache replacement: Sets can be used to implement cache replacement policies,
where the oldest or least recently used elements are removed when the cache is
full
o Database indexing : Sets can be used to implement indexes in databases,
allowing for fast searching and retrieval of data based on specific keys or
attributes

1.7. Solving quadratic equations

The equation ax2 + bx + c = 0 is a quadratic equation, which is a second-degree


polynomial equation. In this equation, a, b, and c are constants, x is an unknown variable, and a
is not equal to zero. Here, a and b are the coefficients of x2 and x terms respectively, and c is the
constant term. The roots of a quadratic equation are the solutions to the equation. Graphing,
factoring, completing the square, and the quadratic formula are among techniques for locating
these roots.

Value of Discriminant (D = b2 – 4*a*c ) Type of Roots


D>0 Two Real and Distinct Roots
10
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

D=0 Two real and equal roots.


D<0 Two Imaginary or complex roots

Positive Coefficient (a > 0):


 If b and c are both positive, the polynomial will have no positive roots
 If b and c are both negative, the polynomial will have two positive roots
 If b and c have opposite signs, the polynomial will have one positive root

Negative Coefficient (a < 0):
 If b and c are both positive, the polynomial will have two negative roots
 If b and c are both negative, the polynomial will have no negative roots
 If b and c have opposite signs, the polynomial will have one negative root

For a Quadratic equation, f(x) = ax2+ bx + c where a is not equal to 0 and a, b, and c are real
numbers; solution of f(x) = 0 is given by Quadratic Formula i.e.,

−𝑏 ± √𝑏 2 − 4𝑎𝑐
𝑥=
2𝑎
Analysis
 If the value of discriminant (b²-4*a*c) > 1, then the value of root1 and root2 of the
equation can be calculated as:
root1 = (-b + √d) / 2a
root2 = (-b - √d) / 2a
For example, the roots of a quadratic equation x2 - 7x - 12 are 3 and 4, which are real and
distinct.
 If the value of discriminant (b²-4*a*c) = 1, then the value of both the roots is -b / 2a.
For example, the roots of x2 - 2x + 1 are 1 and 1, which are real and equal.
 If the value of discriminant (b²-4*a*c) < 1, then the value of root1 and root2 of the
quadratic equation can be calculated as:
root1 = -b / 2a + i (√d / 2a)
root2 = -b / 2a - i (√d / 2a)
For example, the roots of the quadratic x2 + x + 1, roots are -0.5 + i0.86603 and -0.5 -
i0.86603, as we can see roots are real and imaginary.

Algorithm

1. Start
2. Take the input of coefficients a, b and c from the user.
3. Find the value of discriminant (d) = (b * b) - (4 * a * c)
4. if discriminant > 1
−𝑏+√𝑏2 −4𝑎𝑐
root1 = 2𝑎
11
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

−𝑏−√𝑏2 −4𝑎𝑐
root2 = 2𝑎
5. if discriminant = 1
−𝑏
root1 = 2𝑎
6. if discriminant < 1
−𝑏 √𝑑
root1 = + 𝑖 2𝑎
2𝑎
−𝑏 √𝑑
root2 = = 2𝑎 − 𝑖 2𝑎
7. Print the roots
8. Stop

In summary

 Quadratic equations are polynomial equations having a degree of 2. It is represented by


the equation, ax² + bx +c = 0, where a, b and c are the coefficients.
 The value of a in the equation cannot be zero, and the value of x is used to find the roots
of the quadratic equation in c.
 The roots of the quadratic equations can be defined in three ways: real and distinct, real
and equal, and real and imaginary.
 The nature of the root is decided by the discriminant and the discriminant has a value
of (b²-4ac).
 If the value of the discriminant comes to less than zero, then the roots are imaginary and
hence can not be computed.
 If the value of the discriminant is greater than zero, then the roots are real.
 If the value of the discriminant is equal to zero, then both the roots are equal.

In daily life we use quadratic formula as for calculating areas, determining a product’s
profit or formulating the speed of an object. In addition, quadratic equations refer to an equation
that has at least one squared variable and also problems of motion.

1.8. Tower of Hanoi Algorithm


Tower of Hanoi is a mathematical puzzle where there are three rods (A, B, and C)
and N disks. Initially, all the disks are stacked in decreasing value of diameter i.e., the smallest
disk is placed on the top and they are on rod A. The objective of the puzzle is to move the entire
stack to another rod (here considered C), obeying the following simple rules:
 Only one disk can be moved at a time
 Each move consists of taking the upper disk from one of the stacks and placing it on top of
another stack i.e. a disk can only be moved if it is the uppermost disk on a stack
 No disk may be placed on top of a smaller disk

Examples
 Input: 2 Disks
Output: Disk 1 moved from A to B

12
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

Disk 2 moved from A to C


Disk 1 moved from B to C

 Input: 3 Disks
Output: Disk 1 moved from A to C
Disk 2 moved from A to B
Disk 1 moved from C to B
Disk 3 moved from A to C
Disk 1 moved from B to A
Disk 2 moved from B to C
Disk 1 moved from A to C

Tower of Hanoi using Recursion


The idea is to use the helper node to reach the destination using recursion. Below is the
pattern for this problem:
 Shift ‘N-1’ disks from ‘A’ to ‘B’, using C
 Shift last disk from ‘A’ to ‘C’
 Shift ‘N-1’ disks from ‘B’ to ‘C’, using A

Follow the steps below to solve the problem:


 Create a function towerOfHanoi where pass the N (current number of
disk), from_rod, to_rod, aux_rod
 Make a function call for N – 1 th disk
 Then print the current the disk along with from_rod and to_rod
 Again make a function call for N – 1 th disk

In the case of N number of disks, minimum number of moves to solve the tower of Hanoi
problem is 2N – 1.
If N = 3, number of moves = 23 – 1 =7.
If N = 4, number of moves = 24 – 1 =15.
The disk movements are shown in figure with 3 disks.

13
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

Figure 1.4

1.9. Operations on Matrices


Various operations on matrices are listed below:
 Matrices Addition
 Matrices Subtraction
 Scalar multiplication on matrices
 Matrices Multiplication

Algorithm for Matrix Addition


Matrix addition involves adding two matrices of the same dimensions element by
element. Here's the step-by-step algorithm:
Input
 Two matrices A and B of dimensions m×n.
Output
 A resulting matrix C of dimensions m×n such that
C[i][j]=A[i][j]+B[i][j] for all valid i and j.
Steps
1. Start.
2. Input Dimensions:
o Read the number of rows mmm and columns nnn.
3. Input Matrices:
o Read the elements of matrix A of size m×n
o Read the elements of matrix B of size m×n.
4. Initialize Result Matrix:
o Create an empty matrix C of size m×n.

14
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

5. Perform Addition:
o For each row i from 0 to m−:
 For each column j from 0 to n−1:
 Compute C[i][j]=A[i][j]+B[i][j]
End For
End For
6. Output Result:
o Print the resulting matrix C.
7. Stop.
For example, the addition of two matrices A m*n and B m*n gives a matrix C m*n. The
elements of C are the sum of corresponding elements in A and B which can be shown as:
1 2 5 6 6 8
( ) +( ) =( )
3 4 8 7 11 11

Algorithm for matrix multiplication(A,B)

Input A matrix of order m x n


Input B matrix of order n x p
Output C matrix of order m x p

Begin
for (i=0;i<m;i++)
for (j=0;j<p;j++)
c[i][j] = 0;
end for
end for

for (i=0;i<m;i++)
for (j=0;j<p;j++)
for(k=0;k<n;k++)
C[i][j]+= A[i][k] * B[k][j];
end for
end for
end for
end matrixmultiplication

Applications of matrices

 Image processing (e.g., blending two images).


 Signal processing.
 Error calculation in machine learning.
 Differencing signals in signal processing.

15
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

 Matrices are used to study electrical circuits, quantum mechanics, and optics. They can
also be used to calculate battery power outputs and convert electrical energy into other
useful energies.
 Programmers use matrices and inverse matrices to encrypt messages and for coding.
 Matrices are used to project 3D images onto 2D screens to create realistic motions.
 Matrices are used to calculate GDP and measure goods production.
 Matrix rank reduction is often used in data compression.
 The rank of the Jacobian matrix affects the mobility and control of robotic arms.
 Matrix algebra is used to calculate financial ratios, such as profitability ratios, liquidity
ratios, and efficiency ratios. It can also be used to analyze and interpret accounting
data.
 Matrices can be used to represent real-world statistics such as population and infant
mortality rate.
 Google search uses matrices in its page rank algorithm to rank search results

The advantages of matrix algorithm are:


 Simple and fast.
 Widely used in linear systems and data transformations.
 Essential for operations like error minimization.
 Versatility: Applicable in diverse fields, from computer graphics to quantum
mechanics.
 Efficiency: Optimized algorithms like Strassen’s and SVD handle large datasets
efficiently.
 Data Representation: Easy representation of transformations, equations, and
relations.
 Scalability: Advanced methods scale well for large data and sparse matrices.

In this chapter beginning with the program implementations issues and mitigations,
algorithms on number theory by adopting Euclidean algorithm, various operations on ordered
set of elements in different data structure, recursive solution for Tower of Hanoi puzzle,
Solving quadratic equations, the operations on matrices and its applications in real life
applications are clearly explained.

Exercise
1. What are the steps involved in solving a problem using a computer?
2. How does abstraction help in problem-solving?
3. Compare and contrast algorithm design and program implementation.
4. What is the role of pseudocode in problem-solving?
5. Explain the importance of debugging and testing in computer-based problem solving.
6. How do modular programming and code reuse improve program design?
7. Discuss common challenges faced during program implementation.
8. What are the best practices for writing maintainable and efficient code?
9. Explain the role of flowcharts and algorithms in program design.
16
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

10. Write an algorithm to check whether a number is prime.


11. Write an algorithm to compute the GCD of two numbers using the Euclidean method.
12. Write a program to generate the first 100 prime numbers.
13. Write a program logic to list the Armstrong numbers from 100 to 999.
14. Calculate GCD(270, 192) using the Euclidean Algorithm
15. Explain the difference between searching and sorting operations on ordered elements.
16. Write an algorithm for binary search and explain its working with an example.
17. What are the advantages of maintaining elements in an ordered set?
18. Design an algorithm to merge two ordered lists into a single ordered list.
19. Derive the quadratic formula and discuss its use in solving equations.
20. Explain the significance of the discriminant in determining the nature of roots.
21. What are the basic operations that can be performed on matrices? Explain each with
examples.
22. Write an algorithm for matrix addition.
23. How is matrix multiplication different from scalar multiplication? Provide examples.
24. Write pseudocode to calculate the transpose of a matrix.
25. What is the Tower of Hanoi problem? Explain its rules.
26. Write an algorithm to solve the Tower of Hanoi problem.
27. How many moves are required to solve the Tower of Hanoi problem with n disks?
28. Discuss the applications of the Tower of Hanoi problem in computer science.
29. What are the characteristics of a good algorithm?
30. How do you analyze the time and space complexity of an algorithm?
31. Discuss the importance of iterative and recursive approaches in problem-solving.
32. Why is optimization important in problem-solving, and how can it be achieved?

17
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

2. UNIT-II : OVERVIEW OF C, FUNCTIONS

Basic Data types, Modifying the Basic Data types, Identifier-Names,


Variables, Type Qualifiers, Constants, Operators, Expressions, Selection, Iteration
and Jump Statements. Designing Structured Programs, Functions Basics,
Standard Library Functions, User Defined Functions, Categories of Functions,
Parameter Passing Techniques, Scope, Scope Rules, Storage Classes and Type
Qualifiers, Recursion: Recursive Functions, Preprocessor Directives.

2.1. Overview

Ken Thompson at Bell Labs, USA, wrote the variant of Basic Combined Programming
Language (BCPL) and called it as B. Dennis Ritchie at Bell Labs, designed C in 1970. Thereafter
UNIX operating system was written in C. In 1983, an ANSI standard for C emerged as a token of
International acceptance of the programming language.

The elegance, brevity and versatility of the operators and control structures of C language
is welcomed by the software developers worldwide.

C programming language in software field plays important role in developing software


required for operating electronic gadgets. This plays a key role in invoking specific function by
the processor. So, C is declared as middle-level language, instead of high-level language as
BASIC, COBOL, not as low-level language as Assembly language.

Importance of C

C programming is a powerful and versatile programming language that plays a significant


role in software development. With its simplicity, efficiency, and wide range of applications, C
has stood the test of time and continues to be a popular choice among programmers worldwide.

C is a procedural language that supports structured programming; it has a static system


comprising of various functions and libraries and a compiler written in C language itself. Since
its release, C has become a milestone in computing history and has become the most critical
component throughout the computer industry.
Dennis Ritchie wrote an article explaining the reason for C's success which are
enumerated as follows:
 The success of Unix was the most important factor as Unix used C for building its utilities,
and its success had carried C.
 C remained a simple and small language meant for building system components. C was held
to be sufficiently abstract that humans can read – which is why C is considered as a middle-
level language.
 C was not designed in isolation but to write useful tools that interact with large systems. C is
18
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

regarded as a tool for building larger tools. Moreover, C's core library covers the essential
needs of most programmers.

Because C works very closely with the processor, performance-critical applications are
mostly written in C, and because of its unmatched popularity programming languages derived a
familiar C-style syntax along with the set of constructs that came with C (e.g., pointers, macros,
etc.). C has become the backbone of modern computing systems – operating systems, compilers,
interpreters, third-party libraries, and databases. In addition, C is a small language that is
designed to cost minimal performance overhead which makes it ideal for embedded systems.

Advantages of C programming language

 Efficiency: C allows for direct memory manipulation and low-level access to system
resources. This results in highly efficient code execution.
 Portability: C code can be easily ported to different platforms without major modifications,
due to its wide availability of compilers and libraries.
 Speed: C is known for its fast execution speed, making it suitable for developing
performance-critical applications.
 Control: C gives programmers fine-grained control over memory management and system
resources.
 Compatibility: C code can be easily integrated with code written in other languages like C++,
Java, and Python.

Practical Applications of C Language

Even though most people may not directly use C programming language in their daily
lives, its impact is widespread. Many devices and technologies rely on software developed using
C, including:
Operating systems: All modern operating systems, such as Windows, Linux, and macOS,
have a significant portion of their codebase written in C.
Embedded systems: Devices like washing machines, smart TVs, and medical equipment
often run on embedded systems programmed using C.
Mobile applications: Some parts of mobile applications, including high-performance
tasks and system-level operations, may be implemented in C for efficiency.
Gaming consoles: Popular gaming consoles’ core software and engines are often
developed using C.
Network infrastructure: Routers and networking devices rely on software written in C to
handle complex networking protocols.

The Future of C Programming


19
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

Advancements in C Programming
The C programming language continues to evolve, with new standards introduced to
address technological advancements and programming practices. The C18 Standard, released in
2018, introduced several new features to the language, such as complex floating-point types,
type-generic expressions, and improved alignment control. The latest version of the standard,
C20, was released in 2020, further refining and improving the language.

Integration of C Programming with Modern Technologies


C programming is increasingly being integrated with modern technologies, such as the
Internet of Things (IoT) and cloud computing. With the growing number of connected devices
and the increasing demand for cloud-based services, C is well-suited for developing low-level
systems and drivers and creating high-performance, scalable cloud-based applications.

Use of C Programming in Emerging Fields


C programming is also being used in emerging fields, such as artificial intelligence (AI)
and machine learning (ML). C is being used as a low-level language for performance-critical
code in AI applications, such as deep learning algorithms, and in ML systems, such as decision
trees and neural networks. The efficiency and speed of C programming make it an ideal choice
for these types of applications, where performance is critical.

The Role of C Programming in the Programming World

C as a Foundational Language
C programming is often considered a foundational language, as it provides a solid
understanding of computer systems, algorithms, and software development practices. Many
programming languages and technologies have borrowed concepts and syntax from C, making it
a valuable language for developers to learn.

System Programming using C


C programming plays a major role in system programming, particularly in the
development of operating systems and embedded systems. This language develops low-level
system software, such as device drivers, kernels, and operating system components, making it an
important language for many critical systems.

Software Development using C


C programming is also widely used in software development, particularly in developing
database systems and mobile applications. C is well-suited for performance-critical applications,
such as database systems, where efficiency and speed are critical. Additionally, C is often used
as a low-level language for developing mobile applications, particularly for developing the low-
level components of the application stack.

2.2. Data Types


C language is rich in supporting various data types suitable for all purpose of applications

20
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

and the machines.

The data types supported by C are classified into three major categories:

1. Primary or Basic data types.


2. Derived data types
3. User-defined data types

Figure 2.1

Basic Data Types

C provides a standard, minimal set of basic data types, also called as primitive data types.
These data types are generally provided by all programming languages. The complex data types
are built on top of the five basic data types.

The basic data types are as follows:

 int – For whole numbers e.g. 1234, 4567


 float – For real numbers (decimal) e.g. 1098.32
 double - For larger decimal numbers, generally used for scientific calculation requiring
accuracy, e.g. 3.141592653589793
 char - For storing alphanumeric of one or more characters in length
 void – Meaning nothing and used generally for functions that do not return any value,
explicitly indicate that a function does not require any parameter

Derived data types

Derived data types in C are data types created using the basic or fundamental data types
to build more complex structures. These types are essential for organizing, storing, and managing
data efficiently in programming. Some of the key derived data types are:

21
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

Array
The purpose of array is to store multiple values of the same type in a contiguous block of
memory like a matrix.

The Array is useful in handling lists of numbers like student marks, stock prices and in
matrix operations in scientific computations.

Pointer
The purpose of the pointers is to store memory addresses of variables, enabling dynamic
memory manipulation and function interaction.

The Pointers are mainly used in Dynamic memory allocation, Efficient array and string
manipulation and Accessing data structures like linked lists and trees.

Structure
The purpose of structure is to group related variables of different data types into a single
unit.

They are mainly used in representing real-world entities like a student detail with
attributes like name, roll_no, marks etc, creating custom data formats for files and databases.

Enumeration (enum)
The Enumeration is used to define a set of named integral constants for better code
readability and maintainability.

They are mainly used in defining options or states like days of the week, error codes and
menu items etc

2.3. Type Qualifiers


Type qualifiers are keywords that can be used to change a data type's behavior in the C
programming language. These qualifiers can be used to describe a variable or
pointer's constancy, volatility, restrictions, and others.

The type qualifiers used in C language are:

1. Const Example
If any variable is declared as a
const in the code and is initialized with a #include <stdio.h>
value, its value cannot be modified in any int main()
part of the code. It results in a compile-
{
time error if the programmer attempts to
modify the value of such variables, which const int phi = 3.14; // phi is a constant
printf("Value of phi is : %d\n", phi);
22
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

are declared const. return 0;


}

2. Volatile Example

The type qualifier volatile can be #include <stdio.h>


used to describe a variable whose value is int main() {
subject to sudden change. It is typically volatile int sensor_data = 0; // Simulating a
used for variables that can be accessed by hardware register
hardware, updated by several threads or
while (sensor_data = 0) {
processes, or both. The volatile qualifier
informs the compiler that any reads or // Compiler won't optimize this loop
writes to the variable should not be away
optimized away since the variable's value printf("Waiting for sensor data...\n");
might change without the program's }
permission. printf("Sensor data received: %d\n",
In the example, the program is not sensor_data);
allowed to modify the value of return 0;
sensor_data. This will be modified by }
another program outside.

3. Restrict

23
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

The restrict keyword is a Example


type qualifier applied to pointers. #include <stdio.h>
It informs the compiler that the void add_arrays(int *restrict a, int *restrict b, int
pointer is the only reference to the *restrict result, int n) {
object it points to for the duration for (int i = 0; i < n; i++) {
of its scope. This allows the
result[i] = a[i] + b[i];
compiler to optimize code more
efficiently by assuming that no }
other pointer will modify the }
object. In performance-sensitive int main() {
code, such as numerical int arr1[] = {1, 2, 3, 4, 5};
algorithms, the restrict qualifier is int arr2[] = {5, 4, 3, 2, 1};
often used. int result[5];
// Adding two arrays
In the example, the restrict add_arrays(arr1, arr2, result, 5);
keyword tells the compiler that the
pointers a, b, and result in
add_arrays point to distinct, non- // Printing the result
overlapping memory locations. for (int i = 0; i < 5; i++) {
This allows the compiler to printf("%d ", result[i]);
perform aggressive optimizations }
internally. return 0;
}

2.4. Tokens

Every C program is a collection of instructions and every instruction is a collection of


certain individual units. Every smallest individual unit of a C program is called token. Every
instruction in a C program is a collection of tokens. Tokens are used to construct C programs and
they are said to the basic building blocks of a C program.
In a C program, token refers to one of the following:
1. Keywords
2. Identifiers
3. Operators
4. Special Symbols
5. Constants
6. Strings
7. Data values

24
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

Keywords Example
#include<stdio.h>
As every language has words to construct #include<conio.h>
statements, C programming also has words with int main() {
a specific meaning which are used to construct C int i;
program instructions. In the C programming clrscr();
language, keywords are special words with printf("ASCII ==> Character\n");
predefined meaning. Keywords are also known for(i = -128; i <= 127; i++)
as reserved words in C programming language. printf("%d ==> %c\n", i, i);
In the C programming language, there getch();
are 32 keywords. All the 32 keywords have their return 0;
meaning which is already known to the }
compiler.

Properties of Keywords

1. All the keywords in C programming


language are defined as lowercase letters so
they must be used only in lowercase letters
2. Every keyword has a specific meaning, users
can not change that meaning
3. Keywords cannot be used as user-defined
names like variable, functions, arrays,
pointers, etc.,
In the example program, to print all the
characters in the character set, there are 22
keywords.

Sl
Keyword Purpose
No.
1 auto Represent automatic storage class
Unconditional control statement terminate switch and looping
2 break statements
3 case Represent a case (option) in switch statement
4 char Represent character data type
5 const Define a constant
Unconditional control statement pass the control to the beginning of
6 continue looping statements
7 default Represent a default case (option) in switch statement
8 do Define do block in do-while statement
9 double Present double datatype
25
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

10 else Define FALSE block of if statement


11 enum Define enumarated datatypes
12 extern Floating point datatypes
13 float Looping statement
14 for Represent external storage class
15 goto Represent unconditional control statement
16 if Define a conditional control statement
17 int Represent integer datatype
18 long It is a type modifier that alters the basic datatype
19 register Represent register storage class
20 return Terminate a function execution
21 short It is a type modifier that alters the basic datatype
22 signed It is a type modifier that alters the basic datatype
23 sizeof It is an operator that gives size of the memory of a variable
24 static Create static variables - constants
25 struct Create structures - Userdefined datatypes
26 switch Define switch - case statement
27 typedef Specify temporary name for the datatypes
28 union Create union for grouping different types under a name
29 unsigned It is a type modifier that alters the basic datatype
30 void Indicate nothing - return value, parameter of a function
31 volatile Creating volatile objects
32 while Define a looping statement

Identifiers

In C programming language, programmers can specify their name to a variable, array,


pointer, function, etc... An identifier is a collection of characters which acts as the name of
variable, function, array, pointer, structure, etc... In other words, an identifier can be defined as
the user-defined name to identify an entity uniquely in the C programming language that name
may be of the variable name, function name, array name, pointer name, structure name or a label.

Example
int marks;
char studentName[30];

Here, marks and studentName are identifiers.

26
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

Rules for Creating Identifiers


1. An identifier can contain letters (UPPERCASE and lowercase), numerics & underscore
symbol only.
2. An identifier should not start with a numerical value. It can start with a letter or an
underscore.
3. We should not use any special symbols in between the identifier even whitespace.
However, the only underscore symbol is allowed.
4. Keywords should not be used as identifiers.
5. There is no limit for the length of an identifier. However, the compiler considers the first
31 characters only.
6. An identifier must be unique in its scope.

Variables

Variables in a C programming language are the named memory locations where the user
can store different values of the same datatype during the program execution. That means a
variable is a name given to a memory location in which we can store different values of the same
data type. In other words, a variable can be defined as a storage container to hold values of the
same datatype during the program execution.

Every variable in C programming language must be declared in the declaration section


before it is used. Every variable must have a datatype that determines the range and type of
values be stored and the size of the memory to be allocated.

A variable name may contain letters, digits and underscore symbol. The following are the
rules to specify a variable name:

1. Variable name should not start with a digit.


2. Keywords should not be used as variable names.
3. A variable name should not contain any special symbols except underscore ‘_’.
4. A variable name can be of any length but compiler considers only the first 31 characters
of the variable name.

Declaration of Variable
Declaration of a variable tells the compiler to allocate the required amount of memory
with the specified variable name and allows only specified datatype values into that memory
location. In C programming language, the declaration can be performed either before the
function as global variables or inside any block or function. But it must be at the beginning of
block or function.

Declaration Syntax
Datatype variableName;
27
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

Example

int mynumber;
The above declaration tells the compiler that it allocates 2 bytes of memory with the
name mynumber and allows only integer values into that memory location.

Constants

In C programming language, a constant is similar to the variable but the constant hold
only one value during the program execution. That means, once a value is assigned to the
constant, that value can't be changed during the program execution. Once the value is assigned to
the constant, it is fixed throughout the program.
A constant can be of any data type like integer, floating-point, character, string and
double, etc.,

Integer constants
An integer constant can be a decimal integer or octal integer or hexadecimal integer. A
decimal integer value is specified as direct integer value whereas octal integer value is prefixed
with 'o' and hexadecimal value is prefixed with 'OX'. An integer constant can also be unsigned
type of integer constant or long type of integer constant. Unsigned integer constant value is
suffixed with 'u' and long integer constant value is suffixed with 'l' whereas unsigned long integer
constant value is suffixed with 'ul'.

Example
125 Decimal Integer Constant
O76 Octal Integer Constant
OX3A Hexa Decimal Integer Constant
50u Unsigned Integer Constant
30l Long Integer Constant
100ul Unsigned Long Integer Constant

Floating Point constants


A floating-point constant must contain both integer and decimal parts. Some times it may
also contain the exponent part. When a floating-point constant is represented in exponent form,
the value must be suffixed with 'e' or 'E'.

Example
The floating-point value 3.14 is represented as 3E-14 in exponent form.
28
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

Character Constants
A character constant is a symbol enclosed in single quotation. A character constant has a
maximum length of one character.

Example
'A'
'2'
'+'
In the C programming language, there are some predefined character constants called
escape sequences. Every escape sequence has its own special functionality and every escape
sequence is prefixed with '\' symbol. These escape sequences are used in output function called
'printf()'.

String Constants
A string constant is a collection of characters, digits, special symbols and escape
sequences that are enclosed in double quotations.
We define string constant in a single line as follows:
"This is B.Tech smart class".
We can define string constant using multiple lines as:
"This\
is\
B.Tech smartclass"

We can also define string constant by separating it with white space as:
"This" "is" "btechsmartclass"
All the above three defines the same string constant.

Creating constants

Constants can be created using one of the two concepts:

1. Using the 'const' keyword


2. Using '#define' preprocessor

Using the 'const' keyword


A constant of any datatype can be Example
defined using 'const' keyword. To create a #include<stdio.h>
constant, the variable declaration needs to prefix void main(){
with 'const' keyword. The general syntax for int i = 9 ;
creating constant using 'const' keyword is: const int x = 10 ;
i = 15 ;
const datatype constantName; or x = 100 ; // creates an error
const datatype constantName = value ; printf("i = %d\nx = %d", i, x ) ;
29
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

}
For example,
const int x = 10 ; The above program gives an error
because there is an attempt to alter the
Here, 'x' is a integer constant with fixed value constant value (x = 100).
10.

Using '#define' preprocessor

Example Constants can also be created


using the #define preprocessor directive.
#include<stdio.h> When using this directive to define a
#define PI 3.14 constant, it must be declared at the
void main(){ beginning of the program, as all
int r, area ; preprocessor directives must appear
printf("Please enter the radius of circle : ") ; before any global declarations.
scanf("%d", &r) ; The syntax for defining a constant
area = PI * (r * r) ; with the #define directive is as follows:
printf("Area of the circle = %d", area) ;
} #define <CONSTANTNAME> <value>

Operators

An operator is a symbol used to perform arithmetic and logical operations in a program.


That means an operator is a special symbol that tells the compiler to perform mathematical or
logical operations. C programming language supports a rich set of operators that are classified as
follows.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Increment & Decrement Operators
5. Assignment Operators
6. Bitwise Operators
7. Conditional Operator
8. Special Operators

Arithmetic Operators (+, -, *, /, %)


The arithmetic operators are the symbols that are used to perform basic mathematical
operations like addition, subtraction, multiplication, division and percentage modulo. The
30
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

following table provides information about arithmetic operators.

Operator Purpose Example


+ Addition 10 + 5 = 15
- Subtraction 10 - 5 = 5
* Multiplication 10 * 5 = 50
/ Division 10 / 5 = 2
% Remainder of the Division 5%2=1

The addition operator can be used with numerical data types and character data type.
When it is used with numerical values, it performs mathematical addition and when it is used
with character data type values, it performs concatenation (appending). The remainder of the
division operator is used with integer data type only.

Relational Operators (<, >, <=, >=, ==, !=)


The relational operators are the symbols that are used to compare two values. That means
the relational operators are used to check the relationship between two values. Every relational
operator has two results TRUE or FALSE. In simple words, the relational operators are used to
define conditions in a program. The following table provides information about relational
operators.

Operator Purpose Example


Returns TRUE if the first value is smaller than second 10 < 5 is
<
value otherwise returns FALSE FALSE
Returns TRUE if the first value is larger than second 10 > 5 is
>
value otherwise returns FALSE TRUE
Returns TRUE if the first value is smaller than or equal 10 <= 5 is
<=
to second value otherwise returns FALSE FALSE
Returns TRUE if the first value is larger than or equal to 10 >= 5 is
>=
second value otherwise returns FALSE TRUE
Returns TRUE if both values are equal otherwise 10 == 5 is
==
returns FALSE FALSE
Returns TRUE if both values are not equal otherwise 10 != 5 is
!=
returns FALSE TRUE

Logical Operators (&&, ||, !)


The logical operators are the symbols that are used to combine multiple conditions into
one condition. The following table provides information about logical operators.

Operator Purpose Example


31
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

&& Logical AND - Returns TRUE if all conditions are 10 < 5 && 12 >
TRUE otherwise returns FALSE 10 is FALSE

|| Logical OR - Returns FALSE if all conditions are 10 < 5 || 12 > 10


FALSE otherwise returns TRUE is TRUE

! Logical NOT - Returns TRUE if condition is FLASE !(10 < 5 && 12


and returns FALSE if it is TRUE > 10) is TRUE

Logical AND - Returns TRUE only if all conditions are TRUE, if any of the conditions is
FALSE then complete condition becomes FALSE. Logical OR - Returns FALSE only if all
conditions are FALSE, if any of the conditions is TRUE then complete condition becomes
TRUE.

Increment & Decrement Operators (++ & --)


The increment and decrement operators are called unary operators because both need
only one operand. The increment operators adds one to the existing value of the operand and the
decrement operator subtracts one from the existing value of the operand. The following table
provides information about increment and decrement operators.

Operator Purpose Example


++ Increment - Adds one to existing value int a = 5;
a++; ⇒ a = 6
-- Decrement - Subtracts one from existing value int a = 5;
a--; ⇒ a = 4

The increment and decrement operators are used infront of the operand (++a) or after the
operand (a++). If it is used infront of the operand, we call it as pre-increment or pre-decrement
and if it is used after the operand, we call it as post-increment or post-decrement.

Pre-Increment or Pre-Decrement

In the case of pre-increment, the value of Example


the variable is increased by one before the
expression evaluation. In the case of pre- #include<stdio.h>
decrement, the value of the variable is decreased #include<conio.h>
by one before the expression evaluation. That void main(){
means, when we use pre-increment or pre- int i = 5,j;
decrement, first the value of the variable is j = ++i; // Pre-Increment
incremented or decremented by one, then the printf("i = %d, j = %d",i,j);
modified value is used in the expression }
evaluation.
32
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

Post-Increment or Post-Decrement
Example In the case of post-increment, the value
#include<stdio.h> of the variable is increased by one after the
void main(){ expression evaluation. In the case of post-
int i = 5,j; decrement, the value of the variable is
j = i++; // Post-Increment decreased by one after the expression
printf("i = %d, j = %d",i,j); evaluation. That means, when we use post-
} increment or post-decrement, first the
expression is evaluated with existing value,
then the value of the variable is incremented or
decremented by one.

Assignment Operators (=, +=, -=, *=, /=, %=)


The assignment operators are used to assign right-hand side value (Rvalue) to the left-
hand side variable (Lvalue). The assignment operator is used in different variants along with
arithmetic operators. The following table describes all the assignment operators in the C
programming language.

Operator Purpose Example


= Assign the right-hand side value to left-hand side variable A = 15

+= Add both left and right-hand side values and store the result A += 10
into left-hand side variable ⇒ A = A+10
-= Subtract right-hand side value from left-hand side variable A -= B
value and store the result into left-hand side variable ⇒ A = A-B
*= Multiply right-hand side value with left-hand side variable A *= B
value and store the result into left-hand side variable ⇒ A = A*B
/= Divide left-hand side variable value with right-hand side A /= B
variable value and store the result into the left-hand side ⇒ A = A/B
33
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

variable
%= Divide left-hand side variable value with right-hand side A %= B
variable value and store the remainder into the left-hand ⇒ A = A%B
side variable

Bitwise Operators (&, |, ^, ~, >>, <<)


The bitwise operators are used to perform bit-level operations in the C programming
language. When we use the bitwise operators, the operations are performed based on the binary
values. The following table describes all the bitwise operators in the C programming language.
Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).

Operator Purpose Example


& the result of Bitwise AND is 1 if all the bits are 1 otherwise A&B
it is 0 ⇒ 16 (10000)
| the result of Bitwise OR is 0 if all the bits are 0 otherwise it A|B
is 1 ⇒ 29 (11101)
^ the result of Bitwise XOR is 0 if all the bits are same A^B
otherwise it is 1 ⇒ 13 (01101)
~ the result of Bitwise once complement is negation of the bit ~A
(Flipping) ⇒ 6 (00110)
<< the Bitwise left shift operator shifts all the bits to the left by A << 2
the specified number of positions ⇒ 100 (1100100)
>> the Bitwise right shift operator shifts all the bits to the right A >> 2
by the specified number of positions
⇒ 6 (00110)

Conditional Operator (? :)
The conditional operator is also called a ternary operator because it requires three
operands. This operator is used for decision making. In this operator, first we verify a condition,
then we perform one operation out of the two operations based on the condition result. If the
condition is TRUE the first option is performed, if the condition is FALSE the second option is
performed. The conditional operator is used with the following syntax.

Condition ? TRUE Part : FALSE Part;


Example
A = (10<15)?100:200; ⇒ A value is 100

34
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

Special Operators (sizeof, pointer, comma, dot, etc.)


The following are the special operators available.
sizeof operator
This operator is used to find the size of the memory (in bytes) allocated for a variable.
This operator is used with the following syntax.

sizeof(variableName);

Example: sizeof(A); ⇒ the result is 2 if A is an integer

Pointer operator (*)


This operator is used to define pointer variables.

Comma operator (,)


This operator is used to separate variables while they are declaring, separate the
expressions in function calls, etc.
Dot operator (.)
This operator is used to access members of structure or union.

Expressions

In any programming language, if we want to perform any calculation or to frame any


condition etc., we use a set of symbols to perform the task. These set of symbols makes an
expression. An expression is a collection of operators and operands that represents a specific
value.
An operator is a symbol that performs tasks like arithmetic operations, logical operations, and
conditional operations, etc. Operands are the values on which the operators perform the task.
Here operand can be a direct value or variable or address of memory location.

Expression Types
In the C programming language, expressions are divided into three types. They are as
follows:
1. Infix Expression
2. Postfix Expression
3. Prefix Expression

The above classification is based on the operator position in the expression.


Infix Expression
The expression in which the operator is used between operands is called infix expression.
The infix expression has the following general structure.
35
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

Operand1 operator Operand2


Example
(a+b)
Postfix Expression
The expression in which the operator is used after operands is called postfix expression.
The postfix expression has the following general structure.
Operand1 Operand2 Operator
Example
ab+
Prefix Expression
The expression in which the operator is used before operands is called a prefix
expression.
The prefix expression has the following general structure.
Operator Operand1 Operand2
Example
+ab

Operator Precedence and Associativity

Operator Precedence
Operator precedence is used to determine the order of operators evaluated in an
expression. Every operator has a pre-defined precedence (priority). When there is more than one
operator in an expression the operator with higher precedence is evaluated first and the operator
with the least precedence is evaluated last.

Operator Associativity
Operator associativity is used to determine the order of operators with equal precedence
evaluated in an expression.

Operator
Precedence Operator Associativity
Meaning

() function call Left to Right

1 [] array reference
structure member
->
access

36
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

structure member
.
access

! negation Right to Left

~ 1's complement

+ Unary plus

- Unary minus
2 ++ increment operator
-- decrement operator
& address of operator
* pointer
returns size of a
sizeof variable
(type) type conversion

* multiplication Left to Right


3 / division
% remainder
+ addition Left to Right
4
- subtraction
<< left shift Left to Right
5
>> right shift
< less than Left to Right
<= less than or equal to
6 > greater than
greater than or
>= equal to
== equal to Left to Right
7
!= not equal to
8 & bitwise AND Left to Right
bitwise
9
^ EXCLUSIVE OR Left to Right
| bitwise OR Left to Right
10
11 && logical AND Left to Right
12 || logical OR Left to Right
conditional
13
?: operator Left to Right
37
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

= assignment Right to Left


assign
*= multiplication
/= assign division
%= assign remainder
+= assign addition
14 -= assign subtraction
assign bitwise
&= AND
^= assign bitwise XOR
|= assign bitwise OR
<<= assign left shift
>>= assign right shift
15 , separator Left to Right

Expression Evaluation

An expression is evaluated based on the operator precedence and associativity. When


there are multiple operators in an expression, they are evaluated according to their precedence
and associativity. The operator with higher precedence is evaluated first and the operator with
the least precedence is evaluated last.
To understand expression evaluation, consider the following simple example expression.

10 + 4 * 3 / 2
In the above expression, there are three operators +, * and /. Among these three operators,
both multiplication and division have the same higher precedence and addition has lower
precedence. So, according to the operator precedence both multiplication and division are
evaluated first and then the addition is evaluated. As multiplication and division have the same
precedence they are evaluated based on the associativity. Here, the associativity of multiplication
and division is left to right. So, multiplication is performed first, then division and finally
addition. So, the above expression is evaluated in the order of * / and +. It is evaluated as
follows:

4 * 3 ====> 12
12 / 2 ====> 6
10 + 6 ====> 16

The expression is evaluated to 16.

Selection/ Decision-making Statements


38
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

Decision-making statements are the statements that are used to verify a given condition
and decide whether a block of statements gets executed or not based on the condition result.
In the C programming language, there are two decision-making statements they are as
follows.
1. if statement
2. switch statement

if statement
A if statement is used to make decisions based on a condition. The if statement verifies
the given condition and decides whether a block of statements are executed or not based on the
condition result. The if statement is classified into four types as follows:
1. Simple if statement
2. if-else statement
3. Nested if statement
4. if-else-if statement (if-else ladder)

Simple if statement

Simple if statement is used to verify the #include<stdio.h>


given condition and executes the block of #include<conio.h>
statements based on the condition result. The void main(){
simple if statement evaluates specified int n ;
condition. If it is TRUE, it executes the next clrscr() ;
statement or block of statements. If the printf("Enter any integer number: ") ;
condition is FALSE, it skips the execution of scanf("%d", &n) ;
the next statement or block of statements. The if ( n%5 == 0 )
general syntax and execution flow of the printf("Given number is divisible by
simple if statement is as follows. 5\n") ;
Simple if statement is used when we printf("statement does not belong to
have only one option that is executed or if!!!") ;
skipped based on a condition. }

if-else statement
#include<stdio.h> The if-else statement is used to verify
#include<conio.h> the given condition and executes only one out
of the two blocks of statements based on the
void main(){ condition result. The if-else statement evaluates
int n ; the specified condition. If it is TRUE, it
clrscr() ; executes a block of statements (True block). If
printf("Enter any integer number: ") ; the condition is FALSE, it executes another
39
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

scanf("%d", &n) ; block of statements (False block). The general


if ( n%2 == 0 ) syntax and execution flow of the if-else
printf("Given number is EVEN\n") ; statement is as follows.
else The if-else statement is used when we
printf("Given number is ODD\n") ; have two options and only one option has to be
} executed based on a condition result (TRUE or
FALSE).

Nested if statement
Writing a if statement inside #include<stdio.h>
another if statement is called nested if #include<conio.h>
statement.
void main(){
The nested if statement can be int n ;
defined using any number of clrscr() ;
combinations of simple if and if-else printf("Enter any integer number: ") ;
statements. scanf("%d", &n) ;
if ( n < 100 )
{
printf("Given number is below 100\n") ;
if( n%2 == 0)
printf("And it is EVEN") ;
else
printf("And it is ODD") ;
}
else
printf("Given number is not below 100")
}

if-else-if statement (if-else ladder)

#include<stdio.h> Writing an if statement inside else of an


#include<conio.h> if statement is called if-else-if statement.
void main(){
int a, b, c ;
clrscr() ; The if-else-if statement can be defined
printf("Enter any three integer numbers: using any combination of simple if & if-else
") ; statements.
scanf("%d%d%d", &a, &b, &c) ;
if( a>=b && a>=c)
printf("%d is the largest number", a) ;
else if (b>=a && b>=c)
40
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

printf("%d is the largest number", b) ;


else
printf("%d is the largest number", c) ;
}

'switch' statement

The switch statement contains one #include<stdio.h>


or more cases and each case has a value #include<conio.h>
associated with it. At first switch void main(){
statement compares the first case value int n ;
with the switchValue, if it gets matched clrscr() ;
the execution starts from the first case. If printf("Enter any digit: ") ;
it doesn't match the switch statement scanf("%d", &n) ;
compares the second case value with the switch( n )
switchValue and if it is matched the {
execution starts from the second case. case 0: printf("ZERO") ;
This process continues until it finds a break ;
match. If no case value matches with the case 1: printf("ONE") ;
switchValue specified in the switch break ;
statement, then a special case called case 2: printf("TWO") ;
default is executed. break ;
case 3: printf("THREE") ;
When a case value matches with break ;
the switchValue, the execution starts case 4: printf("FOUR") ;
from that particular case. This execution break ;
flow continues with the next case case 5: printf("FIVE") ;
statements also. To avoid this, we use the break ;
"break" statement at the end of each case. case 6: printf("SIX") ;
That means the break statement is used break ;
to terminate the switch statement. case 7: printf("SEVEN") ;
However, it is optional. break ;
case 8: printf("EIGHT") ;
break ;
case 9: printf("NINE") ;
break ;
default: printf("Not a Digit") ;
}
getch() ;
}
41
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

Iterative statements
There are mainly two types of loops
1. Entry Controlled loops: In Entry controlled loops the test condition is checked before
entering the main body of the loop. For Loop and While Loop is Entry-controlled
loops.
2. Exit Controlled loops: In Exit controlled loops the test condition is evaluated at the
end of the loop body. The loop body will execute at least once, irrespective of
whether the condition is true or false. do-while Loop is Exit Controlled loop.

Figure 2.2
for Loop
for loop in C programming is a Example:
repetition control structure that allows
programmers to write a loop that will be #include <stdio.h>
executed a specific number of times. for int main()
loop enables programmers to perform n {
number of steps together in a single line. int i = 0;
for (i = 1; i <= 10; i++)
Initialization Expression: In this
42
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

expression, we assign a loop variable or {


loop counter to some value. for example: printf( "Hello World\n");
int i=1; }
return 0;
Test Expression: In this }
expression, test conditions are performed.
If the condition evaluates to true then the Output
loop body will be executed and then an Hello World
update of the loop variable is done. If the Hello World
test expression becomes false then the Hello World
control will exit from the loop. for Hello World
example, i<=9; Hello World
Update Expression: After Hello World
execution of the loop body loop variable Hello World
is updated by some value it could be Hello World
incremented, decremented, multiplied, or Hello World
divided by any value. Hello World

While Loop

Example While loop does not depend upon the


number of iterations. In for loop, the number of
#include <stdio.h> iterations was previously known to us but in the
int main() While loop, the execution is terminated on the
{ basis of the test condition. If the test condition
// Initialization expression will become false then it will break from the
int i = 2; while loop else body will be executed.
// Test expression
while(i < 10) Syntax
{ initialization_expression;
// loop body
printf( "Hello World\n"); while (test_expression)
// update expression {
i++; // body of the while loop
}
return 0; update_expression;
} }

Output
Hello World
Hello World
43
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

Hello World
Hello World
Hello World
Hello World
Hello World
Hello World

do-while Loop

The do-while loop is similar to a Example


while loop but the only difference lies in
the do-while loop test condition which is #include <stdio.h>
tested at the end of the body. In the do- int main()
while loop, the loop body will execute at {
least once irrespective of the test // Initialization expression
condition. int i = 2;
do
Syntax {
initialization_expression; // loop body
printf( "Hello World\n");
do // Update expression
{ i++;
// Test expression
// body of do-while loop } while (i < 1);
return 0;
update_expression;
}
} while (test_expression);
Output
The example program will Hello World
evaluate (i<1) as false since i = 2.
However, as it is a do-while loop the
body will be executed once.

44
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

Loop Control Statements


Loop control statements are used to change execution from its normal sequence.
There are control statements that do not need any condition to control the program
execution flow. These control statements are called as unconditional control statements. C
programming language provides the following unconditional control statements...
● break
● continue
● goto
break statement
A break statement is used to Example
perform the following two things: #include<stdio.h>
void main(){
1. break statement is used to terminate int number1, number2, result ;
the switch case statement char operator;
2. break statement is also used to clrscr() ;
terminate looping statements like printf("Enter any two integer numbers: ") ;
while, do-while and for. scanf("%d%d", &number1, &number2) ;
When a break statement is printf("Please enter any arithmetic operator:
encountered inside the switch case ");
statement, the execution control moves operator = getchar();
out of the switch statement directly. For switch(operator)
example, consider the example program. {
Once a valid operator is encountered, case '+': result = number1 + number2 ;
subsequent case statement will not be printf("Addition = %d", result) ;
validated. break;
case '-': result = number1 - number2 ;
printf("Subtraction = %d", result) ;
break;
case '*': result = number1 * number2 ;
printf("Multiplication = %d",
result) ;

45
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

break;
case '/': result = number1 / number2 ;
printf("Division = %d", result) ;
break;
case '%': result = number1 % number2 ;
printf("Remainder = %d", result) ;
break;
default: printf("\nWrong selection!!!") ;
}
getch() ;
}

continue statement

Example The continue statement is used to


#include<stdio.h> move the program execution control to the
#include<conio.h> beginning of the looping statement. When
void main(){ the continue statement is encountered in a
int number ; looping statement, the execution control
clrscr() ; skips the rest of the statements in the
while( 1 ) looping block and directly jumps to the
{ beginning of the loop. The continue
printf("Enter any integer number: ") ; statement can be used with looping
scanf("%d", &number) ; statements like while, do-while and for.
if(number%2 == 0) When we use continue statement
{ with while and do-while statements the
printf("Entered number is EVEN!!! execution control directly jumps to the
Try another number!!!\n") ; condition. When we use continue
continue ; statement with for statement the execution
} control directly jumps to the modification
else portion of the for loop.
{
printf("You have entered ODD
number!!! Bye!!!") ;
exit(0) ;
}
}
getch() ;
}

46
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

goto statement
The goto statement is used to Example
jump from one line to another line in the #include<stdio.h>
program. Using goto statement we can #include<conio.h>
jump from top to bottom or bottom to void main(){
top. To jump from one line to another clrscr() ;
line, the goto statement requires a label. printf("We are at first printf statement!!!\n")
Label is a name given to the instruction ;
or line in the program. When we use a goto last ;
goto statement in the program, the printf("We are at second printf
execution control directly jumps to the statement!!!\n") ;
line with the specified label. printf("We are at third printf
statement!!!\n") ;
last: printf("We are at last printf
statement!!!\n") ;
getch() ;
}

2.5. Scope of a variable


Scope refers to the visibility and lifetime of variables within a program. It defines where
a variable can be accessed and modified in the code. An application build using C language has
build, function, program components as basic elements. The scope definition of a variable helps
to clarify whether a variable has to be made available within these elements or outside and the
lifetime.

The scope of a variable can be classified into several types, which determines its
accessibility in different parts of a program.

47
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

Types of Scope
Local Scope
A variable declared inside a Example
function or block, in simple words void myfunction()
between {} braces, have local scope. {
These variables are only accessible within int localVar = 10;
the function or block where they are
// Local to myfunction()
declared.
Local variables exist only for the printf("%d", localVar);
duration of the function call or block // Accessible only within this function
execution. They are created when the }
block is entered and destroyed when the
block is exited.
Here, localVar is only accessible
within myfunction() and cannot be used
outside of it.

Global Scope
Variables declared outside all Example
functions have global scope. These int globalVar = 5; // Global variable
variables can be accessed by any function
within the program. void function1()
{
Global variables exist for the
entire duration of the program, i.e., from printf("%d", globalVar); //
the start of execution until the program Accessible here
terminates. }

Here, globalVar can be accessed void function2()


and modified by both function1() and {
function2(). globalVar = 20; // Modified here
printf("%d", globalVar);
}

48
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

Block Scope
Variables declared inside a block Example
(within {}) have block scope. This is void myfunction()
similar to local scope, but even more {
limited to the specific block (like if, for, if (1) {
while loops). int blockVar = 100;
// Block scoped variable
Block-scoped variables are created printf("blockVar accessible here!
and destroyed upon entering and exiting %d", blockVar);
the block. }
printf("blockVar not accessible
here! %d", blockVar);
}

Function Scope
The scope of labels (used with Example
goto statements) is limited to the function void function()
in which they are defined. This is known {
as function scope. goto label; // Label used in function
The function variable exists only scope
for the duration of the function execution. label: printf("This is a label");
}

File Scope
Variables declared with the static Example
keyword outside functions have file
scope. They are similar to global variables static int fileVar = 10;
but are accessible only within the file // File scope, accessible only in this
where they are declared. file
The lifetime of file-scoped
variables is the entire duration of the
program, but they are not accessible
outside the file in which they are defined.

2.6. Scope Rules


C has clearly defined rules to resolve any conflict that can arise out of defines variables
with same name in one or more places.

49
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

Local vs Global Variables (Name Conflict Resolution)

When a global variable and Example:


a local variable have the same int var = 5; // Global variable
name, the local variable takes
precedence within the function or void function() {
block where it is declared. The int var = 10; // Local variable
global variable remains hidden in printf("%d", var); // Prints 10 (local variable takes
that local scope. precedence)
}

void anotherFunction() {
printf("%d", var); // Prints 5 (global variable is
accessed here)
}

Global Variables Across Multiple Files

Example Global variables can be accessed across


// In file1.c multiple files by using the extern keyword in
int globalVar = 100; the file where the variable is declared. This tells
the compiler that the variable is defined in
// In file2.c another file.
extern int globalVar;
// Refers to globalVar in file1.c
printf("%d", globalVar);
// Will print 100

Static Variables

Static Local Variables: Variables Example


declared with static inside a function void function() {
maintain their value across multiple static int count = 0; // Static local variable
function calls but are only accessible count++;
within the function where they are printf("%d", count); // Value persists
declared. across function calls
Static Global Variables: Global }

50
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

variables declared with static are only


accessible within the file in which they are // Output across multiple calls:
defined, providing file-level // 1
encapsulation. // 2
// 3

Block-Level Scope:

Example Variables declared within a block (such


void function() { as inside if, for, or while) are scoped to that
int x = 10; // Outer scope block and cannot be accessed outside of it. This
if (1) { applies even if a variable with the same name
int x = 20; // Block scope (shadows exists in an outer scope.
the outer x)
printf("%d", x); // Prints 20
}
printf("%d", x); // Prints 10 (block-
scope variable is no longer accessible)
}

Understanding of scope rules is critical to avoid variable conflicts and to ensure variables
are used in the right context.

2.7. Storage Classes

The storage class defines the scope, visibility, lifetime, and default initial value of
variables or functions within a program. It tells the compiler where to store a variable, how long
to keep the variable's value in memory, and what part of the program can access the variable.
There are four main storage classes

1. Automatic (auto)
2. Register (register)
3. Static (static)
4. External (extern)

1. Automatic Storage Class (auto)

51
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

 Scope: Local to the block or function in Example:


which it is defined.
 Lifetime: Exists only during the execution of void function()
the block or function. The variable is {
destroyed when the block or function is auto int x = 10;
exited. // x is an automatic (local) variable
 Default Value: Garbage value (undefined printf("%d", x);
value until initialized). }
 Storage: Stored in the stack.
Key Points: Here, x is automatically destroyed when
 ‘auto’ is the default storage class for local function() completes.
variables.
 The explicit use of auto is rarely necessary
since all local variables have auto storage by
default.

2. Register Storage Class (register)


Example  Scope: Local to the block or function in
void function() which it is defined.
{  Lifetime: Exists only during the execution
register int counter = 0; of the block or function.
// Suggest storing counter in a CPU  Default Value: Garbage value (undefined
register value until initialized).
for (counter = 0; counter < 10;  Storage: Stored in CPU registers (if
counter++) available); if not, it behaves like an auto
{ variable stored in the stack.
printf("%d ", counter); Key Points:
}  The register keyword suggests that the
} variable be stored in a CPU register instead
of RAM for faster access.
Here, the variable counter may be stored  Not all variables can be stored in registers
in a CPU register for faster access. (depends on the hardware and compiler) due
to hardware restrictions.
 A register variable address cannot be
accessed sing the address-of operator (&)

3. Static Storage Class (static)

52
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

 Scope: Example (Static Local Variable)


o For local variables: The void count() {
variable is local to the function static int counter = 0; // Static local
or block but retains its value variable
between function calls. counter++;
o For global variables: The printf("%d", counter);
variable is local to the file in }
which it is declared (file scope),
making it invisible to functions int main()
in other files. {
 Lifetime: For the entire lifetime of the count(); // Output: 1
program, but only initialized once. count(); // Output: 2
 Default Value: Zero (if uninitialized). count(); // Output: 3
 Storage: Stored in the data segment of }
memory (not in the stack).
Key Points: In this example, the variable counter retains
 Static local variables retain their its value between function calls.
value even after the function exits.
 Static global variables are restricted Example (Static Global Variable)
to the file where they are defined, static int globalVar = 10; // Static global
providing file-level encapsulation variable, local to this file

void function1()
{
globalVar += 5;
printf("%d", globalVar);
}

Here, globalVar is only accessible in the file


where it is declared.

4. External Storage Class (extern)

Example (Using extern) 1.Scope: Global (accessible by all


File 1 (file1.c) functions in any file that declares
int globalVar = 100; the variable using extern).
// Global variable definition 2. Lifetime: For the entire duration of
File 2 (file2.c) the program.
extern int globalVar; 3. Default Value: Zero (if
// Declaration of the global variable from uninitialized).
file1.c 4. Storage: Stored in the data segment
of memory.
void function() Key Points:
{  The extern keyword is used to
53
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

printf("%d", globalVar); // Accessing the declare a variable that is defined in


global variable defined in file1.c another file or later in the same file.
}  It allows multiple files to share a
global variable or function.
Here, the variable globalVar is defined in
file1.c but accessed in file2.c using the extern
keyword.

Summary of Storage Classes

Storage Default Recommended Usage


Scope Lifetime Storage
Class Value
Local variables in functions.
Until
Local to Garbage This is the default storage
Auto block/func Stack
block/function value class for variables inside
tion exits
functions
Calculation and access
CPU
Until intensive (such as loop
Local to Garbage Register
Register block/func counters) where fast access
block/function value (if
tion exits is needed. Compiler may not
available)
always provide
For local variables that need
to retain their value between
Local (retains Entire function calls.
Data
Static value), File- program Zero For global variables that
Segment
level duration should only be accessed
within the file they are
declared in
Entire For a global variable or
Global across Data
Extern program Zero function that is defined in
files Segment
duration another file.

By understanding the storage classes, the visibility, lifetime, and memory allocation of
variables in the programs, can be controlled and optimizing performance, organizing code
effectively.

2.8. Designing Structured Programs


A function is a self-contained block of program statements designed to perform a specific
task. The concept of functions falls under the broader category of sub-programs.
C programming follows the principles of structured modular programming, as opposed to
being monolithic. A monolithic program is a single, large block of code containing all the
functionality within a single function, making it harder to manage, test, and debug. In contrast,
modular programming divides a program into smaller, independent modules, each focusing on a
54
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

specific task.
These modules can be developed and tested separately, which simplifies debugging and
maintenance. Finally, a linker combines these individual modules to create a complete, cohesive
program. This modular approach enhances code reusability, readability, and scalability.

Basic structure of C program along with multiple function calls is shown below.

Figure 2.3

Advantages of Modular Programming

Since the life time of most of the commercial programs span over decades, it is highly
recommended to write them in a structured way. There are several advantages in maintaining
modularity of programs:

1. Modular programs are composed of small, manageable modules that are easy to code and
debug.
2. The overall program size is reduced, as repeated code can be avoided.
3. Code written for one module can be reused in other programs, improving efficiency and
consistency.
4. Issues or errors can be isolated to specific modules, making it easier to identify and fix
problems.

55
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

2.9. Function
The main function (main()) serves as the entry point of the program. It is identified by the
keyword main followed by parentheses (main()). The operating system calls main() when the
program is loaded and resumes control once the program terminates.

A function has three main components:

1. Declaration: Specifies the function’s name, return type, and parameters (if any).
2. Definition: Contains the body of the function, which includes the code to be executed.
3. Function Call: Invokes the function. This can be done from the main() function or any
other sub-function

Function Declaration:
<return datatype > function_name(datatype parameter1, datatype parameter2, …
datatype parameter);
In classic C programming function is declared above main().
In modern C programming function declaration and definitions are combined and
written before main() function.

Function definition:
<return datatype > function_name(datatype argument1, datatype argument2, …
datatype argument)
{
….local declaration of variables;
….statements;
return;
}

Function call:
int main()
{
….local variable declaration ;
function_name(); // Function is invoked by function call from main()
…statements;
}

Functions are a powerful feature that offer numerous advantages, as outlined below:

1. Functions help reduce redundancy by eliminating the need to repeat the same statements
throughout the program.
2. They enhance code readability by providing modularity, making the program easier to
understand and maintain.

56
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

3. There is no limit to how many times a function can be called; it can be invoked as many
times as needed.
4. Functions reduce the overall size of the program by breaking it into smaller, manageable
parts.
5. Once a function is declared, it can be used directly without needing to understand its internal
workings, promoting code reuse and simplifying development.

2.10. Types of Functions


The functions are classified into two
high level types based on whether it is pre-
supplied by C language or developed for a
specific purpose by the user

Figure 2.4

User-defined functions

Functions created by the Example


programmer are called user-defined #include<stdio.h>
functions or "tailor-made functions." #include<conio.h>
These functions can be customized and int add(int a, int b);
modified to meet the specific int main()
requirements of a program. Whenever a {
task requires functionality not provided int a,b,ans;
by standard library functions, the clrscr();
programmer can declare and define their printf(“enter the values of a and b”);
own functions following the appropriate scanf(“%d%d”,&a,&b);
syntax. ans=add(a,b);
An example of a user-defined printf(“ The sum of two numbers is %d”,c);
function is the main() function. The getch();
main() function serves as the entry point return 0;
of a program, where statements are }
written to accomplish specific tasks. int add(int a, int b)
{
Advantages of User-Defined Functions int result;
result=a+b;
 Adaptable functions can be return(result);
modified to suit specific }
requirements.
 The code for these functions is Output
reusable across multiple Enter the values of a and b 10 20
programs. The sum of two numbers is 30
 These functions are easy to

57
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

understand, debug, and maintain,


enhancing code clarity and
reliability

The example is a C program to


show the use of functions to find the sum
of numbers

Standard Library Functions

A library function, also known as Example


a built-in function, is part of a compiler #include<stdio.h>
package that already contains predefined #include<conio.h>
functions, each with a specific purpose. #include<math.h>
The key advantage of built-in functions is int main()
that they can be used directly without {
needing to be defined, whereas user- double x,y,ans;
defined functions must be declared and clrscr();
defined before they can be used. printf(“enter the values of x and y”);
scanf(“%lf %lf”,&x,&y);
Advantages of C library functions ans=pow(x,y); // to calculate xyv
 C Library functions are easy to use printf(“ The power of y to the base x is
and optimized for better performance %lf”,ans);
 C library functions save a lot of time getch();
by reusing existing function return 0;
 C library functions are convenient as }
they always work
Output
The example on the right is a C Enter the values of x and y 3 4
program to show the use of library The power of y to the base x is 81.000000
functions to find the exponent of a
number.

Below are some of the widely used Library functions.

Library File /
Operations Library Functions
Header File
scanf(), printf(), getchar,
Perform input, output operations stdio.h
putchar()
Perform console operations clrscr(), getch(), getche() conio.h

58
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

sqrt(), pow(), sin(), cos(), tan(),


Perform mathematical operations math.h
log(), log10()
strlen(),strcat(), strcpy(), strcmp(),
Perform string operations string.h
strstr(), strrev(), strchr()
Perform dynamic memory
calloc(), malloc(), free() Stdlib.h
allocation operation
Perform file related operations fopen(), fclose(), fseek() stdio.h
To check and convert the input isalpha(), isnum(), isupper(),
token into an alphabet, number or islower(), tolower(), toupper(), ctype.h
uppercase, lowercase etc. toascii()

2.11. Parameter Passing Techniques

The data passed when the Example


function is being invoked is known as #include <stdio.h>
the Actual parameters. In the below #include<conio.h>
program, 10 and 30 are known as int sum(int a, int b);
actual parameters. Formal Parameters int main()
are the variable and the data type as {
mentioned in the function int a, b, add;
declaration. In the below program, a add = sum(a,b); // Actual Parameter
and b are known as formal printf(“Sum is %d”, add);
parameters. return 0; //Formal Parameters
}
int sum(int a, int b)
{
return(a+b);
}

The arguments can be passed to the C function in two ways:


1. Pass by Value
2. Pass by Reference

1. Pass by Value
Parameter passing in this Example
method copies values from actual #include <stdio.h>
parameters into formal function #include<conio.h>
parameters. As a result, any changes void swap (int a, int b);
made inside the functions do not int main()
reflect in the caller’s parameters. {
The example is a C program int a,b;
to swap two numbers by pass by clrscr();

59
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

value. The output of the program will printf(“enter the values of a and b”);
be as follows: scanf(“%d%d”,&a,&b);
printf(“Before swapping \n”);
Output: printf(“a = %d \t b= %d\n”,a,b);
Enter the values of a and b 10 20 swap(a,b);
Before swapping printf(“After swapping \n”);
a=10 b=20 printf(“a = %d \t b= %d\n”,a,b);
After swapping getch();
a=10 b=20 return 0;
}
void swap(int a, int b)
{
int temp;
temp=a;
a=b;
b=temp;
}

2. Pass by Reference

Example The caller’s actual parameters and the


#include <stdio.h> function’s actual parameters refer to the same
#include<conio.h> locations, so any changes made inside the
void swap (int *a, int *b); // a and b are function are reflected in the caller’s actual
pointer variables parameters.
int main() The example is a C program to swap
{ two numbers by pass by reference. The output
int a,b; of the program will be as follows:
clrscr();
printf(“enter the values of a and b”); Output
scanf(“%d%d”,&a,&b); Enter the values of a and b 10 20
printf(“Before swapping \n”); Before swapping
printf(“a = %d \t b= %d\n”,a,b); a=10 b=20
swap(&a, &b);// Passing the address After swapping
reference to the function a=20 b=10
printf(“After swapping \n”);
printf(“a = %d \t b= %d\n”,a,b);
getch();
return 0;
}
void swap(int *a, int *b)
60
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

{
int temp;
temp = *a;
*a = *b;
*b = temp;
}

2.12. Categories of Functions


There are four categories of functions based on the passing of arguments and the return
statements. They are as follows:

1. No arguments , No return
2. No arguments, With return
3. With arguments, No return
4. With arguments, With return

Category 1: No arguments , No return Category 2: No arguments , With return


C program to find the simple interest // C program to calculate simple interest
calculation without arguments and without by pass by value
return.
#include <stdio.h>
// C program to calculate simple interest by #include<conio.h>
pass by value float simple_interest();
int main()
#include <stdio.h> {
#include<conio.h> float si;
void simple_interest(); clrscr();
si=simple_interest();
int main() printf(“The simple interest is %0.2f\n”,si);
{ getch();
clrscr(); return 0;
simple_interest(); }
getch(); float simple_interest()
return 0; {
} int n;
void simple_interest() float p, r;
{ float ans;
int n; printf(“enter the values of p, n and r”);
float p, r, ans; scanf(“%f%d%f”,&p,&n,&r);
printf(“enter the values of p, n and r”); ans=p*n*r/100.0;
scanf(“%f%d%f”,&p,&n,&r); return(ans);
si=p*n*r/100.0; }
printf(“The simple interest is %0.2f\n”,si); Output:
61
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

} enter the values of p, n and r


Output: 1000.00 2 1.5
enter the values of p, n and r The simple interest is 30.00
1000.00 2 1.5
The simple interest is 30.00

Category 3: With arguments , No return Category 4: With arguments , With


// C program to calculate simple interest by return
pass by value // C program to calculate simple interest by
pass by value
#include <stdio.h>
#include<conio.h> #include <stdio.h>
void simple_interest(float p,int n, float r); #include<conio.h>
int main() float simple_interest(float p,int n, float r);
{ int main()
int n; {
float p, r; int n;
clrscr(); float p, r, si;
printf(“enter the values of p, n and r”); clrscr();
scanf(“%f%d%f”,&p,&n,&r); printf(“enter the values of p, n and r”);
simple_interest(p,n,r); scanf(“%f%d%f”,&p,&n,&r);
getch(); si=simple_interest(p,n,r);
return 0; printf(“The simple interest is %0.2f\n”,si);
} getch();
void simple_interest(float p1,int n1, float return 0;
r1) }
{ float simple_interest(float p1,int n1, float
float ans; r1)
ans=p1*n1*r1/100.0; {
printf(“The simple interest is %0.2f\n”,ans); float ans;
} ans=p1*n1*r1/100.0;
Output: return(ans);
enter the values of p, n and r }
1000.00 2 1.5 Output:
The simple interest is 30.00 enter the values of p, n and r
1000.00 2 1.5
The simple interest is 30.00

2.13. Recursion: Recursive Functions

62
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

Recursion is a technique in #include<stdio.h>


which a function calls itself. It #include<conio.h>
allows complex problems to be unsigned int factorial(int n);
broken down into simpler sub- int main()
problems, making them easier to {
solve. int n;
The example tries to find unsigned int fact=1;
the factorial of a number using the printf(“enter a number”);
below logic: scanf(“%d”, &n);
fact = factorial(n);
n! = n * (n-1)! if n > 1 printf(“The factorial of a number %d is %u”, n, fact);
0! = 1 if n = 0 (Base factor) getch();
1! = 1 if n=1 (Base factor) return 0;
}
unsigned int factorial(int num)
{
unsigned int f=1;
if(num==0 || num==1)
{
return(1);
}
else
{
return(f * factorial(num-1));
}
Output:
Enter the number 5
The factorial of a number 5 is 120

Exercise
1. Define basic data types in programming.
2. What are the rules for naming identifiers?
3. Differentiate between variables and constants.
4. What are type qualifiers? Give examples.
5. Name any four arithmetic operators and their use.
6. Define an expression in programming.
7. List the different types of selection statements.
8. What is the difference between iteration and jump statements?
9. Define recursion.
10. Mention any two standard library functions in C.
11. What is the purpose of storage classes in programming?
12. Define scope with an example.

63
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

13. List the types of preprocessor directives.


14. What is parameter passing in functions?
15. Differentiate between local and global variables.
16. Explain the different types of basic data types with examples.
17. Describe the rules for creating valid identifiers with examples.
18. Explain the concept of variables and constants with examples.
19. Discuss type qualifiers and their role in programming with examples.
20. Write a detailed note on operators and their precedence in expressions.
21. Discuss the different types of selection statements with syntax and examples.
22. Explain iteration statements with examples of for, while, and do-while.
23. What are jump statements? Explain break, continue, and goto with examples.
24. Write a note on the design of structured programs.
25. Explain user-defined functions and their categories with examples.
26. Compare and contrast pass-by-value and pass-by-reference with examples.
27. Explain the scope of variables and scope rules with examples.
28. Discuss storage classes in detail with examples.
29. Describe recursion with an example program for factorial calculation.
30. Write a detailed note on preprocessor directives and their types.

64
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

3. UNIT III ARRAYS, STRINGS:

Concepts, Using Arrays in C, Inter-Function Communication using Arrays, Array


Applications, Two-Dimensional Arrays, Introduction to Multidimensional Arrays,
Concepts, C Strings, String Input / Output Functions, Arrays of Strings, String
Manipulation Functions.

An array is a data structure that allows the user to store multiple elements of the same
data type in a contiguous block of memory. Arrays are used to group related data together, which
can then be accessed using indices. The characteristics of Arrays are with fixed size of an array is
defined at the time of its declaration, and it cannot be changed dynamically. All elements in the
array are of the same data type such as all integers, or floats. Array consists of homogenous data,
are stored in the contiguous memory allocation. In C, array indices start from 0, meaning the first
element is at index 0.

The array declaration is given by,

data_type array_name[array_size];

 data_type: The type of the elements (e.g., int, float, char).


 array_name: The name of the array.
 array_size: The maximum number of elements the array can hold.

Syntax for creating an array with size and initial values

data_type array_name[array_sixe] = { value1, value2, …. };

Example of Array Declaration

int numbers[5]; // An integer array of size 5

Here, numbers is an array that can hold 5 integer elements, with indices ranging from 0 to
4.

3.1. Accessing Array Elements

Each element in an array is # include <stdio.h>


accessed using its index. The index int main( )
starts from 0, to access the first {
element. The index 1 is to access the int avg, sum = 0 ;
second element and so on. int i ;
int marks[ 30 ] ;
printf("%d", numbers[0]); /* array declaration */
65
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

// Prints the first element (10) for ( i = 0 ; i <= 29 ; i++ )


{
An array is a collection of printf ( "Enter marks " ) ;
elements of the same type, stored in scanf ( "%d", &marks[ i ] ) ;
contiguous memory locations, which /* store data in array */
can be accessed using indices. }
for ( i = 0 ; i <= 29 ; i++ )
One dimensional array concept sum = sum + marks[ i ] ;
can be explained using a simple /* read data from an array*/
program to find average marks avg = sum / 30 ;
obtained by a class of 30 students in a printf ( "Average marks = %d\n", avg ) ;
test. return 0 ;
}

3.2. Initialization of Arrays


The array initialization is to store values in them during program execution. The array
initialization can be done while declaring it. Following are a few examples that demonstrate this:

int num[ 6 ] = { 2, 4, 12, 5, 45 } ;


int n[ ] = { 2, 4, 12, 5, 45, 5 } ;
float press[ ] = { 12.3, 34.2, -23.4, -11.3 } ;

 Till the array elements are not given any specific values, they contain garbage values. In
the first example num[4] and num[5] will have any random value
 If the array is initialised where it is declared, mentioning the dimension of the array is
optional as in the 2ndand 3rdexamples.
 If the index is not given, the number of elements in the array will be the count of the
values that are initialised.

3.3. Applications of Arrays

Arrays are widely used in programming due to their simplicity, efficiency, and ability to
handle large amounts of data. Here are some common applications of arrays:

Application
How Used Example
Area
Arrays store multiple int marks[5] = {85, 90, 75, 88, 92};
Storing Data in values in a single // Marks of 5 students
an Organized variable for easy
Way management of related
data.

66
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

Used for storing and int matrix[3][3] = {


Matrix manipulating matrices {1, 2, 3},
Representation in operations like {4, 5, 6},
(2D Arrays) addition, subtraction, {7, 8, 9} };
and multiplication. // 3x3 matrix
Arrays support sorting int arr[5] = {5, 2, 9, 1, 6};
algorithms (e.g., Quick sort(arr, arr+5);
Sorting and
Sort) and search // Sort an array
Searching
algorithms (e.g., Binary
Search).
struct Student { char name[50];
Arrays can store
Storing int age;
records of complex
Records (Data float grade; };
data types using
Structures) struct Student students[3];
structures.
// Student records
Arrays represent states Used in simulations like Sudoku or the Game of
Simulation in simulation problems Life.
Problems like board games or
puzzles.
Arrays store time- float temperature[24];
Storing Time- dependent data like // Hourly temperature for a day
Series Data sensor readings or
stock prices.
Arrays track int occurrences[10] = {0};
Managing and
occurrences or store // Track occurrences of values 0 to 9
Tracking
statistical values for
Statistics
datasets.
Arrays of characters char name[50] = "John Doe";
store strings, enabling // Array to store a string
Storing Strings
manipulation and
operations.
#define MAX 10;
Implementing Arrays implement stack
int stack[MAX];
Queues and (LIFO) and queue
int top = -1;
Stacks (FIFO) data structures.
// Stack operations like push, pop, and peek
Arrays in dynamic int *arr = malloc(n * sizeof(int));
Memory memory allocation // Dynamic array allocation
Management allow flexible runtime
data management.
Arrays simulate #define BUFFER_SIZE 10;
Simulation of
circular buffers for int buffer[BUFFER_SIZE];
Circular
applications like int front = 0,
Buffers
audio/video streaming. rear = 0;

67
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

Arrays store events int events[5] = {10, 20, 30, 40, 50};
Storing Time- occurring at specific // Events occur at intervals of 10, 20, 30, etc. ms
based Events intervals for scheduling
or interrupt handling.

Arrays play a central role in many real-world applications. They provide an efficient way
to store and manipulate large sets of data, and their use in implementing complex data structures,
algorithms, and systems makes them a crucial component.

Boundary Checking

There is no check to see if the subscript used for Example


an array exceeds the size of the array. Data entered with # include <stdio.h>
a subscript exceeding the array size will simply be int main( )
placed in memory outside the array; probably on top of {
other data, or on the program itself. This will lead to int num[ 40 ], i ;
unpredictable results, to say the least, and there will be for ( i = 0 ; i <= 100 ; i++ )
no error message to warn you that you are going beyond num[ i ] = i ;
the array size. The example program may write into the return 0 ;
memory address of some other program or system }
variable. In some cases, the computer may just hang.

Example The programmer needs to


# include <stdio.h> ensure that the array size is
int main( ) properly handled. Any access
{ outside of the boundary of the
int num[ 40 ], i ,n; array will lead to unwanted
printf(“enter the value of n\n”); results or program run time
scanf(“%d”,&n); error.
if(n<40)
/* Using if boundary check can be done */ The example explains
{ how a boundary check can be
for ( i = 0 ; i < n ; i++ ) carried out while handling an
num[ i ] = i ; array.
}
else
{
printf(“the array size is out of
boundary”);
68
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

}
return 0 ;
}

Operations on one dimensional array are :


 Insertion
 Deletion
 Update
 Search
 Merging
 Sorting

The above operations are explained with the algorithm and code as follows.

Algorithm to insert an element in an array:

Step 1: Start /* Program to insert an element */


#include<stdio.h>
Step 2: Read the number of void main()
elements n in the array. {
int i,a[30],element,n,pos;
If n >= 30, print "Array is out printf(“enter number of elements in an array\n”);
of boundary" and terminate. scanf(“%d”,&n);
if(n<30)
Step 3: Read n elements and {
store them in the array a. printf("---------- INPUT------------\n\n");
printf("Enter the Array Elements ...\n");
Step 4:Read the position pos for (i=0;i<n;i++)
where the new element is to {
be inserted. scanf("%d",&a[i]);
}
Read the element element to printf(“enter the position and element\n”);
be inserted. scanf(“%d%d”,&pos,&element);
for(i=n;i>=pos;i--)
Step 5: Loop from the end of {
the array to pos and shift a[i]=a[i-1];

69
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

elements to the right. }


a[pos]=element;
Step 6: Assign the new printf("----------- OUTPUT----------\n\n");
element to the position pos. printf("The Array Elements after inserting
\n");
Step 7: Print the updated for(i=0;i<=n;i++)
array elements. {
printf("%d\n",a[i]);
Step 8: Stop. }
}
else
{
printf(“Array is out of boundary”);
}
}

Output
enter number of elements in an array 5
10 20 30 40 50
enter the position and element
2 100
The Array Elements after inserting
10 20 100 30 40 50

Algorithm to delete an element in an array

Example Step 1: Start


/* Program to delete an element */
#include<stdio.h> Step 2: Read the number of
void main() elements n in the array.
{
int i,a[30],n,pos; If n >= 30, print "Array is out of
printf(“enter number of elements\n”); boundary" and terminate.
scanf(“%d”,&n);
if(n<30) Step 3: Read n elements and
{ store them in the array a.
printf("---------- INPUT------------\n\n");
printf("Enter the Array Elements ...\n"); Step 4: Read the position pos
for (i=0;i<n;i++) where the element is to be
70
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

{ deleted.
scanf("%d",&a[i]);
} Step 5: Loop from the pos to
printf(“enter the position to be deleted \n”); the end of the array and shift
scanf(“%d”,&pos); elements to the left. Reduce the
for(i=pos;i<=n;i++) array size by 1.
{
a[i-1]=a[i]; Step 6: Print the updated array
} elements.
printf("----------- OUTPUT----------\n\n");
printf("The Array Elements after deleting \n"); Step 7: Stop.
for(i=0;i<n-1;i++)
{ The following program
printf("%d\n",a[i]); explains the deletion of an
} element from a one dimensional
} array at any particular position.
else
{
printf(“Array is out of boundary”);
}
}
Output
enter number of elements 5
Enter the Array Elements ...
10 20 30 40 50
enter the position to be deleted
2
The Array Elements after deleting
10 20 40 50

Another operation on one dimensional array is to search for an element in an array.

Step 1: Start Example


/* Program to search an element */
Step 2: Read the number of #include<stdio.h>
elements n in the array. void main()
{
If n >= 30, print "Array is out of int i,a[30],n,element,flag=0;
boundary" and terminate. printf(“Enter number of elements \n”);
scanf(“%d”,&n);
Step 3: Read n elements and store if(n<30)
71
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

them in the array a. {


printf("---------- INPUT------------\n\n");
Step 4:Read the element is to be printf("Enter the Array Elements ...\n");
searched. for (i=0;i<n;i++)
{
Step 5: Loop from the index 0 to scanf("%d",&a[i]);
the end of the array and search }
the existence of the element, printf(“Enter the element to search\n”);
Mark the position of that element. scanf(“%d”,&element);
for(i=0;i<n;i++)
Step 6: Print the searched index {
position along with its value of if(a[i]==element)
the element. {
printf(“Element = %d is present
Step 7: Stop. at position %d”, element, i);
flag=1;
break;
}
}
if(flag==0)
{
printf(“Element does not exist in
the array”);
}
printf("----------- OUTPUT----------\n\n");
}
}
else
{
printf(“Array is out of boundary”);
}
}

Output
Enter number of elements 5
Enter the Array Elements ...
10 20 30 40 50
Enter the element to search 30
Element = 30 is present at position 2

The operation of merging two one dimensional arrays into one by appending the second
with first array in the following program.
72
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

Algorithm /* Program to implement union of two arrays */


Algorithm for Union of Two Arrays #include<stdio.h>
Step 1: Start. void main()
Step 2: Read the size of the arrays n. {
If n >= 30, print "Array is out of int i,a[30],b[30],c[30],n,i,j,k;
boundary" and terminate. printf(“Enter number of elements \n”);
Step 3: Read n elements into two arrays scanf(“%d”,&n);
a[] and b[] of size n. if(n<30)
Step 4: Copy Elements from a to c: {
Loop through array a and copy each printf("---------- INPUT------------\n\n");
element into array c at the same index. printf("Enter the Array Elements ...\n");
Step 5: Copy Elements from b to c: for (i=0;i<n;i++)
Loop through array b and append its {
elements to array c starting from index n. scanf("%d%d",&a[i],&b[i]);
Step 6: Output Array c: A merged }
array c[] containing elements from both for(i=0;i<n;i++)
arrays. {
Print all elements of array c from index 0 c[i]=a[i];
to 2*n – 1. }
Step 7: Stop. k=0;
for(j=i;j<2*n-1;j++)
{
c[j]=b[k++];
}
printf("--------- OUTPUT----------\n\n");
printf("The Array Elements after
merging...\n");
for(i=0;i<2*n-1;i++)
{
printf("%5d",c[i]);
}
}
else
{
printf(“Array is out of boundary”);
}
}

Output
Enter number of elements 5
Enter the Array Elements ...
12
34
73
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

56
78
9 10

--------- OUTPUT----------
The Array Elements after merging
1 3 5 7 9 2 4 6 8 10

3.4. Two Dimensional Array

The two-dimensional array is also called a matrix. Let us see how to create this array and
work with it. Here is a sample program that stores roll number and marks obtained by a student
side-by-side in a matrix.

# include <stdio.h>
int main( )
{
int stud[ 4 ][ 2 ] ;
int i, j ;
for ( i = 0 ; i <= 3 ; i++ )
{
printf ( "Enter roll no. and marks" ) ;
scanf ( "%d %d", &stud[ i ][ 0 ], &stud[ i ][ 1 ] ) ;
}
for ( i = 0 ; i <= 3 ; i++ )
printf ( "%d %d\n", stud[ i ][ 0 ], stud[ i ][ 1 ] ) ;
return 0 ;
}

Initializing a Two-Dimensional Array


How do we initialize a two-dimensional array? There are two methods to initialize the
two dimensional array
(i) int stud[ 4 ][ 2 ] = {
{ 1234, 56 },
{ 1212, 33 },
{ 1434, 80 },
{ 1312, 78 }
};
(ii) int stud[ 4 ][ 2 ] = { 1234, 56, 1212, 33, 1434, 80, 1312, 78 } ;
Thus the declarations,
(iii) int arr[ 2 ][ 3 ] = { 12, 34, 23, 45, 56, 45 } ;
74
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

(iv) int arr[ ][ 3 ] = { 12, 34, 23, 45, 56, 45 } ;


are perfectly acceptable,

Operations on two dimensional array

The below algorithm and program explains how an addition of two two dimensional
matrices can be handled.
Algorithm Example
Step 1: Start #include<stdio.h>
Step 2: Declare matrix main()
matA[r1][c1]; and matrix {
matB[r2][c2]; and matrix int a[10][10],b[10][10],c[10][10],I,j,r1,c1,r2,c2;
matC[row][col]; row= no. of
rows, col= no. of columns printf(“Enter the size of the matrx A”);
Step 3: Read row, col, matA[][] scanf(“%d%d”,&r1,&c1);
and matB[][]
Step 4: Declare variable i=0, j=0 printf(“Enter the size of the matrx B”);
Step 5: Repeat until i < row scanf(“%d%d”,&r2,&c2);
5.1: Repeat until j < col
matC[i][j]=matA[i][j] if (r1==r2 && c1==c2)
+ matB[i][j] {
Set j=j+1 printf(“Enter the elements of A”)
5.2: Set i=i+1 for (i=0;i<r1;i++)
Step 6:matC[i][j] is the required for (j=0;j<c1;j++)
matrix after addition {
Step 7: Stop scanf(“%d”,&matA[i][j]);
}
printf(“Enter the elements of B”)
for (i=0;i<r2;i++)
for (j=0;j<c2;j++)
scanf(“%d”,&matB[i][j]);

for (i=0;i<r2;i++)
{
for (j=0;j<c2;j++)
{
matC[i][j]=matA[i][j]+matB[i][j];
printf(“d\t”,matC[i][j]);
}
printf(“\n”);
}
else
printf(“Addition is not possible”);
}
75
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

Output
Enter the row and column of the matrix A 2 3
Enter the row and column of the matrix B 2 3
Enter the elements of A
123456
Enter the elements of B
666666
The sum of two matrices is
7 8 9
10 11 12

The below algorithm and program explains how a multiplication of two two dimensional
matrices can be handled.

#include<stdio.h> Algorithm
main() Step 1: Start
{ Step 2: Declare matrix
int matA[r1][c1]; and matrix
matA[10][10],matB[10][10],matC[10][10],i,j,k,r1,c1,r2,c2; matB[r2][c2]; and matrix
printf("Enter the size of the matrx A"); matC[r1][c2]; row= no. of rows,
scanf("%d%d",&r1,&c1); col= no. of columns
Step 3: Read matA[r1][c1] and
printf("Enter the size of the matrx B"); matB[r2][c2]
scanf("%d%d",&r2,&c2); Step 4: Declare variable i=0, j=0
Step 5: Set a loop from i=0 to
if (c1==r2) i=r1.
{ Step 6: Set an inner loop for the
printf("Enter the elements of A") above loop from j=0 to j=c2
for (i=0;i<r1;i++) Step 7: Initialize the value of the
for (j=0;j<c1;j++) element (i, j) of the new matrix
scanf("%d",&matA[i][j]); (matC[r1][c2]) to 0.
Step 8: Set an inner loop inside
printf("Enter the elements of B") the above loop from k=0 to k=r1.
for (i=0;i<r2;i++) Step 9: Using the add and assign
for (j=0;j<c2;j++) operator (+=) store the value of
scanf("%d",&matB[i][j]); matA[i][k] * matB[k][j] in the
third matrix, matC[i][j].
for (i=0;i<r1;i++) Step 10: Print the third matrix.
{ Step 11: Stop
for (j=0;j<c2;j++)
{
76
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

matC[i][j]=0;
for(k=0;k<c1;k++)
{
matC[i][j]=matC[i][j]+matA[i][k]*matB[k][j];
}
}
}

printf("The product of two matrices is\n");


for (i=0;i<r1;i++)
{
for (j=0;j<c2;j++)
{ printf("%d\t",matC[i][j]);
}
printf("\n");
}
else
printf("Multiplication is not possible");
}
}

Output
Enter the row and column of the matrx A 2 3
Enter the row and column of the matrx B 3 2
Enter the elements of A
1234 56
Enter the elements of B
666666
The product of two matrices is
36 36
90 90

3.5. Introduction to multi-dimensional arrays

Multi-dimensional arrays provide a way to store data in a grid or table-like structure.


They can be thought of as an array of arrays where each element of the primary array holds a
reference to another array.

A multi-dimensional array is defined by specifying the size of each dimension in the


array declaration. The most common multi-dimensional array is a two-dimensional array, which
77
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

can be visualized as rows and columns.

Storage in Memory

Despite their multi-dimensional structure, multi-dimensional arrays are stored in


contiguous memory locations. This means that the elements are placed in row-major order: the
entire first row is stored, followed by the entire second row, and so on. This storage method
allows for efficient access to elements, but it’s important to understand how indexing works to
avoid accessing incorrect memory locations.

The declaration of three dimensiona array and beyond by adding more sizes:

datatype arrayName[xsize][ysize][zsize];

For example, a 3D array of integers, float and character arrays could be declared as:

int threeDArray[3][4][5];
float twoDArray[5][10][20];
char threeDCharArray[5][10][15];

Initialization of Multi-Dimensional Arrays

Initialization of multi-dimensional arrays can be performed explicitly, implicitly, or


partially.

Type of
Description Example
Initialization
If not all elements are initialized int array[2][3] = { {1, 2}, {4} };
Implicit
explicitly, the remaining
Initialization elements are automatically This initializes array[0][2],
initialized to zero. array[1][1], and array[1][2] to 0

Explicit Explicit initialization involves int matrix[2][3] = {


Initialization specifying the value for each {1, 2, 3},
element in the array at the time {4, 5, 6} };
of declaration.
Partial initialization allows you int partialMatrix[3][3] = {
to initialize only a portion of the {1},
Partial
multi-dimensional array, with {0, 2}
Initialization };
the rest being zero-initialized.
This initializes partialMatrix[0][0] to
This is useful when only certain 1, partialMatrix[1][1] to 2, and all other
elements need to be set to elements to 0.
78
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

specific values at the start.

Applications of multi-dimensional Array

There are many other applications of multidimensional arrays. For example, 3-


dimensional array can be used to store and manipulate data in a 3-dimensional space, such as
a cube or a sphere. Similarly a 4-dimensional array can be used to represent data that varies
across four dimensions, such as time, space, temperature, and pressure.

One common use of multidimensional arrays is for image processing and computer vision
applications. For example, a 2-dimensional array can be used to represent an image, with each
element of the array representing a pixel in the image. By manipulating the values of the
elements in the array, a wide range of operations can be performed on the image, such as scaling,
rotating, cropping, and filtering.

3.6. Strings and String Handling Functions

Strings are used for storing text, characters. Unlike many other programming languages,
C does not have a String type to easily create string variables. Instead, the char type array of
characters is to be created to make a string.

Declaring a string in C is as simple as declaring a one-dimensional array. Below is the


basic syntax for declaring a string.

char string_name[size];

In the above syntax string_name is any name given to the string variable and size is used
to define the length of the string, i.e the number of characters strings will store.

char greet[] = "Good morning!";

For example, "Good morning!" is a string of characters.

To output the string, the printf() function together with the format specifier %s is used to
tell C compiler about the usage of strings:

char greet[]=”Good morning!”;


printf(“Greetings is %s”, greet);
The output is Greetings is Good morning!

The format specifier %c is used to refer a single character. To modify the character of a

79
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

string can be made by accessing the index value. It is shown as follows.

greet[0]=’F’;
printf(“%s”, greet);
The output is Food morning!

Unlike other numeric arrays, the end of the character array is put up with the null
character ‘\0’ by the compiler. The string is traversed from the 0th index till the pointer reaches
the end of the string, otherwise the null character.

Initialization of a string in 4 different ways

1. Assigning a String Literal without Size

String literals can be assigned without size. Here, the name of the string str acts as a
pointer because it is an array.

char str[] = "Welcome to the world!";

2. Assigning a String Literal with a Predefined Size

String literals can be assigned with a predefined size. The array size should always
account for one extra space which will be assigned to the null character. If it is needed to store a
string of size n then it should always be declared a string with a size equal to or greater than n+1.

char str[50] = " Welcome to the world!";

3. Assigning Character by Character with Size

We can also assign a string character by character. But we should remember to set the
end character as ‘\0’ which is a null character.

char str[17] = { 'W','e','l','c','o','m','e',' ','t','o ',' ','I','n',’d’,'i','a','\0'};

4. Assigning Character by Character without Size

Character by character can be assigned without size with the NULL character at the end.
The size of the string is determined by the compiler automatically.

char str[] = {'W','e','l','c','o','m','e',' ','t','o ',' ','I','n',’d’,'i','a','\0'};

Note: When a Sequence of characters enclosed in the double quotation marks is


encountered by the compiler, a null character ‘\0’ is appended at the end of the string by default.

String Manipulation functions


80
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

The C library support variety of string operations that can be used for almost all of string
manipulation needs. The below table summarizes the standard string functions available in C.

Function Name Purpose Example


Calculates the length of a string, excluding int len = strlen("Hello");
strlen()
the null terminator. // Returns 5
char dest[20]; strcpy(dest, "Hello");
strcpy() Copies one string into another.
// Copies "Hello" to dest
char str1[20] = "Hello "; strcat(str1,
Concatenates (appends) one string to the
strcat() "World!");
end of another.
// Result: "Hello World!"
int res = strcmp("abc", "abd");
strcmp() Compares two strings lexicographically. // Returns < 0 since "abc" is less than
"abd"
int res = strncmp("apple", "application",
Compares the first n characters of two
strncmp() 3);
strings lexicographically.
// Compares "app" in both strings
Searches for the first occurrence of a char *ptr = strchr("Hello", 'e');
strchr()
character in a string. // Returns pointer to 'e'
Searches for the last occurrence of a char *ptr = strrchr("Hello", 'l');
strrchr()
character in a string. // Returns pointer to the last 'l'
char *ptr = strstr("Hello World",
Searches for the first occurrence of a
strstr() "World");
substring in a string.
// Returns pointer to "World"
Copies the first n characters of one string char dest[10]; strncpy(dest, "Hello", 3);
strncpy()
to another. // Copies "Hel" to dest
char str1[20] = "Hi "; strncat(str1,
Concatenates the first n characters of one
strncat() "There!", 3);
string to another.
// Result: "Hi The"
char str[] = "a,b,c"; char *token =
Splits a string into tokens based on a
strtok() strtok(str, ",");
delimiter.
// Tokenizes the string by commas

Here are few sample programs that use various string functions.

81
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

1. A C program to get #incluce<conio.h>


a string using void main()
various methods to {
get input string. char str[30],ch;
int i=0;
printf(“Enter a string single word Method 1:\n”);
scanf(“%s”,str);
printf(“Method 1 String = %s\n”,str);
printf(“Enter a string with spaces Method 2:\n”);
scanf(“%[^\n]”,str);
printf(“Method 2 String = %s\n”,str);

printf(“Enter a string in small letters Method 3 \n”);


scanf(“%[a-z]”,str);
printf(“Method 3 String = %s\n”,str);

printf(“Enter a string as a sentence Method 4\n”);


gets(str);
printf(“Method 4 String = %s\n”,str);

printf(“Enter a sentence character by character using for


loop,Method 5\n”);
do
{
ch=getchar();
str[i++]=ch;
}while(ch!='\n');

str[i]='\0';
printf(“Method 5 String = %s\n”,str);
}
2. A C program to find #include<stdio.h>
the length of the
string using Library #incluce<string.h>
functions. void main()
{
char str[30];
int length;
printf(“Enter a string :\n”);
gets(str);
length = strlen(str);
printf(“String = %s is of length = %d\n”,str, length);
getch();
}
82
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

3. A C program to #include<stdio.h>
copy one string to #incluce<conio.h>
another using #incluce<string.h>
Library functions. void main()
{
char str1[30],str2[30];
clrscr();
printf(“Enter a string :\n”);
gets(str1);
strcpy(str2,str1);
printf(“String1 = %s and string 2=%s\n”,str1, str2);
}

4. A C program to #include<stdio.h>
concatenate one #incluce<string.h>
string with the other void main()
string using Library {
functions. char str1[30],str2[30];
printf(“Enter first string :\n”);
gets(str1);
printf(“Enter second string :\n”);
gets(str2);
printf(“Before concatenation \n”);
printf(“String1 = %s and string 2=%s\n”,str1, str2);
strcat(str1,str2);
printf(“After concatenation \n”);
printf(“String1 = %s and string 2=%s\n”,str1, str2);
}

5. A C program to #include<stdio.h>
compare two strings #incluce<string.h>
using Library void main()
functions. {
char str1[30],str2[30];
printf(“enter first string :\n”);
gets(str1);

83
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

printf(“enter second string :\n”);


gets(str2);
if(strcmp((str1,str2)==0)
{
printf(“Strings are same”);
}
else
{
printf(“Strings are not same”);
}
}

6. A C program to # include <stdio.h>


compare two strings # include <string.h>
using Library int main( )
functions and how {
to initialize the char string1[ ] = "Jerry" ;
string in a C // Initialisation of strings
program char string2[ ] = "Ferry" ;
int i, j, k ;
i = strcmp ( string1, "Jerry" ) ;
j = strcmp ( string1, string2 ) ;
k = strcmp ( string1, "Jerry boy" ) ;
printf ( "%d \n%d \n%d\n", i, j, k ) ;
return 0 ;
}

Output
0
4
-32

Exercise
1. What is an array in C?
2. How are arrays stored in memory?
3. Define a two-dimensional array.
4. What is the difference between a 1D and a 2D array?
5. List any two applications of arrays.
6. How are arrays used for inter-function communication?
7. Define a string in C.
8. Mention any two string input/output functions in C.
9. What are multidimensional arrays?
10. Differentiate between arrays and strings.
84
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

11. What is a null-terminated string?


12. List any two standard library functions for string manipulation.
13. What is the role of the gets() and puts() functions?
14. Define an array of strings.
15. Explain the concept of row-major order in arrays.
16. Explain the concept of arrays in C and how they are declared and initialized.
17. Discuss inter-function communication using arrays with examples.
18. Describe the various applications of arrays in C programming.
19. Explain the concept of two-dimensional arrays with an example.
20. Discuss the introduction of multidimensional arrays with an example
21. program.how strings are represented in C with an example.
Explain
22. Describe string input/output functions with appropriate examples.
23. Write a program to illustrate array manipulation (e.g., finding the largest
24. element the
Explain in an array).of an array of strings with an example program.
concept
25. Write a program to demonstrate matrix addition or multiplication using two-
26. dimensional
Compare andarrays.
contrast 1D, 2D, and multidimensional arrays with examples.
27. Discuss the memory layout of two-dimensional arrays and how it affects
28. element access. to reverse a given string using string functions.
Write a program
29. Explain string manipulation functions like strlen(), strcpy(), strcat(), and
30. strcmp()the
Discuss with examples.and similarities between arrays of characters and
differences
strings in C.

85
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

4. UNIT IV POINTERS

Introduction, Pointer Arithmetic, Pointers for Inter-Function Communication, Pointers to


Pointers, Arrays and Pointers, Array of Pointers, Pointer to Array, Pointers to void,
Pointers to Functions, Command Line Arguments, Dynamic Memory Allocation Functions,
Programming Applications.

4.1. Introduction
A variable that contains the value of another variable's memory address is called a
pointer. The * operator is used to create a pointer variable, which points to a data type of the
same type. These variables could be of any type- char, int, function, array, or other pointers. The
pointer sizes depend on their architecture. The pointer size in the 32-bit architecture is 2 bytes.

The pointers are very distinctive features in C. It provides the language with flexibility
and power.

Declaration of pointer variable

The syntax of the pointer variable declaration is,

data_type * name_of_pointer_variable;

 The data_type refers to this pointer’s base type in the variable of C. It indicates which
type of variable is the pointer pointing to in the code.
 The asterisk ( * ) is used to declare a pointer. It is an indirection operator, and it is the
same asterisk that is used in multiplication.

The pointers are declared in the C language with the use of the asterisk symbol ( * ). It is
also called the indirection pointer, as we use it for dereferencing any pointer. Here is how it is
used:
int *q; // a pointer q for int data type

char *x; // a pointer x for char data type

The Initialization of a Pointer


86
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

The pointer variable must be initialized to the address of another variable of same data
type. Declaring pointer variable and using it directly without initialization leads to unpredictable
and disastrous, which shows the significance of the initialization of pointer variable.

Pointer variable declaration is done in two steps. The pointer variable has to be declared
first, and the initialization of the another variable is done in the next step as shown below.

The syntax of the initialization of pointer variable,

pointer = &variable;

Example

int x = 10; // Declaration of variable of integer data type


int *p = &x; // Declaration of pointer variable and pointing to the address of x

x = 10 p = 1000

Figure 4.1

In the above figure, the pointer variable p whose address is 2000, holding the address of
the variable x. The * indirection operator on pointer variable shows the value of 10.

Operator Name Uses and meaning of operator


Declares a pointer in a program; Returns the
* Asterisk
referenced variable’s value
& Ampersand Returns a variable’s address

The pointer to an array

Here is an example to illustrate the topic,


int arr[10];
int *ptr = &arr;
// The pointer variable ptr points to the address of array index of arr[0], base address.

Types of Pointer
There are various types of pointers available in C for specific purpose. The table below

87
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

gives a brief about each pointer.

Type Description Sample


Points to nothing (address 0), used to
Null
indicate the pointer is not assigned a int *ptr = NULL;
Pointer
valid location.
Generic pointer that can store the address
Void
of any data type but needs typecasting to void *ptr; int num = 10; ptr = &num;
Pointer
dereference.
Uninitialized pointer holding a random
Wild
memory address, leading to undefined int *ptr; // Uninitialized wild pointer
Pointer
behavior if used.
Points to memory that has been freed or
Dangling
deallocated, resulting in undefined int *ptr = (int *)malloc(sizeof(int)); free(ptr);
Pointer
behavior if accessed.

4.2. Pointers arithmetic


Pointer arithmetic refers to operations that can be performed on pointers, such as
addition, subtraction, and comparison. These operations enable manipulation of memory
addresses in an efficient way, which is crucial for working with arrays, dynamic memory, and
complex data structures. The pointer arithmetic is useful in traversing arrays, accessing elements
in dynamic memory and manipulating memory buffers.

Consider the following example:

# include <stdio.h>
int main( )
{
int i = 3, *x ;
float j = 1.5, *y ;
char k = 'c', *z ;
printf ( "Value of i = %d\n", i ) ;
printf ( "Value of j = %f\n", j ) ;
printf ( "Value of k = %c\n", k ) ;
x = &i ;
y = &j ;
z = &k ;
printf ( "Original address in x = %u\n", x ) ;
printf ( "Original address in y = %u\n", y ) ;
printf ( "Original address in z = %u\n", z ) ;
x++ ;
y++ ;
88
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

z++ ;
printf ( "New address in x = %u\n", x ) ;
printf ( "New address in y = %u\n", y ) ;
printf ( "New address in z = %u\n", z ) ;
return 0 ;
}

Here is the output of the program.

Value of i = 3
Value of j = 1.500000
Value of k = c
Original address in x = 65524
Original address in y = 65520
Original address in z = 65519
New address in x = 65528
New address in y = 65524
New address in z = 65520

From the above last three lines of the output. 65528 is original value in x plus 4, 65524 is
original value in y plus 4, and 65520 is original value in z plus 1. This so happens because every
time a pointer is incremented, it points to the immediately next location of its type. That is why,
when the integer pointer x is incremented, it points to an address four locations after the current
location, since an int is always 4 bytes long (under TC/TC++, since int is 2 bytes long, new value
of x would be 65526). Similarly, y points to an address 4 locations after the current location and
z points 1 location after the current location. This is a very important result and can be
effectively used while passing the entire array to a function.
It shows that the pointer can be incremented and decremented from the current location.
Only integer arithmetic is possible with pointer variable, addition of two pointers, multiplication,
division is not possible and illegal.
The following operations are shown in the snippets.

a) Addition of a number with the pointer variable.


int i = 4, *j, *k ;
j = &i ;
j=j+1;
j=j+9;
k=j+3;

b) Subtraction of a number from a pointer variable,


int i = 4, *j, *k ;
j = &i ;
j=j-2;
j=j-5;
89
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

k=j-6;

c) Subtraction of one pointer from another.


One pointer variable can be subtracted from another provided both variables point to
elements of the same array. The resulting value indicates the number of elements
separating the corresponding array elements. This is illustrated in the following program:

# include <stdio.h>
int main( )
{
int arr[ ] = { 10, 20, 30, 45, 67, 56, 74 } ;
int *i, *j ;
i = &arr[ 1 ] ;
j = &arr[ 5 ] ;
printf ( "%d %d\n", j - i, *j - *i ) ;
return 0 ;
}
Here i and j have been declared as integer pointers holding addresses of first and fifth
element of the array, respectively. Suppose the array begins at location 65502, then the
elements arr[1 ] and arr[ 5 ] would be present at locations 65506 and 65522
respectively, since each integer in the array occupies 2 bytes in memory. The expression j
- i would print a value 4 and not 8. This is because j and i are pointing to locations that
are 4 integers apart.

4.3. Pointers for Inter-Function Communications


When a function gets executed in the program, the execution control is transferred from
calling a function to called function and executes function definition, and finally comes back to
the calling function. In this process, both calling and called functions have to communicate with
each other to exchange information. The process of exchanging information between calling and
called functions is called inter-function communication.

This can be explained by the following program:

#include <stdio.h>
#define PI 3.14
void areaperi(int, int *,int *);

void main()
{
int r;
float a,p;
printf(“Enter radius of a circle:”);
scanf(“%d”,&r);

90
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

areaperi(r,&a,&p); // calling function to evaluate area and perimeter by call by reference

printf(“Area = %f\n”,a);
printf(“Perimenter = %f”,p);
}

void areaperi(int x, float *p, float *q)


{
*p = PI * x * x;
*q = 2 * PI * x;
}

Output of the above program is:


Enter radius of circle 10
Area = 314
Perimeter = 62.8

The function call consists of integer radius, and address of ‘a’ and address of ‘p’. The
radius is passed to the function and the area, perimeter are calculated in the function. To facilitate
this, interfunction communication pointers are used to return the values of area and perimeter.
This can also be considered an example of returning multiple values by pointers.

4.4. Pointer to Pointers


The pointer to pointers is called as the chain of pointers and double pointer, which stores
the address of another pointer.

Figure 4.2

The declaration of a pointer to pointer is similar to the declaration of a pointer, the only
difference is that an additional asterisk (*) before the pointer variable name is used.

The concept of double pointer can be explained by the example program,

#include<stdio.h>
void main()
{
int a=10;
int *p = &a; // p is the pointer variable to the integer variable a
int **dp = &p; // dp is the pointer variable which points to the address of pointer p
printf(“Printing the value of a in various ways\n”);
91
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

printf(“The value of a = %d using integer variable a\n”, a);


printf(“The value of a = %d using pointer variable p \n”, *p);
printf(“The value of a = %d using pointer to pointer variable dp\n”, **dp);
}

Output:
Printing the value of a in various ways
The value of a = 10 using integer variable a
The value of a = 10 using pointer variable p
The value of a = 10 using double pointer variable dp

4.5. Arrays and Pointers


When an array is declared, the compiler allocates a base address and sufficient amount of
storage to contain all the elements of the array in contiguous memory locations. The base address
is the memory location of the first element (index 0) of the array. The compiler also defines the
array name as a constant pointer to the first element.

For example an array x is declared as follows,


int x[5]={1,2,3,4,5};

Figure 4.3

The name x is defined as a constant pointer pointing to the first element, x[0] and
therefore the value of x is 1000. That is,
x = &x[0] = 1000

If pointer p is declared as an integer pointer, then the pointer p can be made to point the
array x by the intialization of pointer as follows:

p=x;

This is equivalent to,


p=&x[0];

Now every value of array x can be accessed by using p++, to move from one element to
another. The relationship between p and x is shown as:
92
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

p=&x[0] (=1000)
p+1 = &x[1](=1002)
p+2 = &x[2](=1004)
p+3 = &x[3](=1006)
p+4 = &x[4](=1008)
The address of an element is calculated using its index and the scale factor of the data
type. For instance,
Address of x[3] = base address + (3 * scale factor of int)
= 1000 + (3*2) = 1006
When handling arrays, instead of using array indexing, pointers can be used to access the
values of array elements. Note that *(p+3) gives the value of x[3]. The pointer accessing method
is much faster than array indexing.
The above concept can be written in C program as follows,

#include<stdio.h>
void main()
{
int *p, sum, I;
Int x[5] = {10, 20, 30, 40, 50);
i=0;
p=x; //initialization of integer pointer p to the base address of an array x
printf(“Element Value Address\n\n”);
while(i<5)
{
printtf(“ x[%d]\t%d\t%u\n”, i, *p, p);
sum = sum + *p;
i++;
p++;
}
printf(“ \n Sum = %d\n”, sum);
printf(“\n &x[0] = %u\n”, x[0]);
printf(“\n p = %u \n”,p);
}

Output
Element Value Address
x[0] 10 655520
x[1] 20 655522
x[2] 30 655524
x[3] 40 655526
x[4] 50 655528
Sum = 150
&x[0]= 655522
p=655530
93
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

4.6. Array of Pointers


Whenever addresses are stored as array elements, such an array is called an array of
pointers. The format for the declaration of an array of pointers is
data_type *array_name[size];

For example, the declaration.


float *a[5];
allocates the memory for 10 pointers, which are to be stored in the variables a[0], a[1],
…. And a[4]. These variables are not initialized. When the array elements are initialized by the
following statements,

float f1=10.32, f2 =15.89;


a[0] = &f1;
a[2] = &f2;

The storage representation of an array of pointers shown below,


a[0] &f1 10.32
f1
a[1]
a[2] &f2 15.89
f2
a[3]
a[4]
To understand the array of pointers, the simple program of 3 variable and values are
printed without the pointer.

#include <stdio.h>
const int MAX = 3;
int main ()
{
int var[] = {10, 100, 200};
int i;
for (i = 0; i < MAX; i++)
{
printf("Value of var[%d] = %d\n", i, var[i] );
}
return 0;
}

Output
Value of var[0]=10
Value of var[1]=100
Value of var[2]=200
94
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

In the above program the array of pointers to the int datatype array is declared and used.
The results are printed using the pointer variable.
int *ptr[MAX];

This declares ptr as an array of MAX integer pointers. Thus, each element in ptr, now
holds a pointer to an int value. Following example makes use of three integers, which will be
stored in an array of pointers as follows:

#include <stdio.h>
const int MAX = 3;
int main ()
{
int var[] = {10, 100, 200};
int i, *ptr[MAX];
for ( i = 0; i < MAX; i++)
{
ptr[i] = &var[i]; /* assign the address of integer. */
}
for ( i = 0; i < MAX; i++)
{
printf("Value of var[%d] = %d\n", i, *ptr[i] );
}
return 0;
}

Output
Value of var[0]=10
Value of var[1]=100
Value of var[2]=200

By using an array of pointers to character to store a list of strings as follows:


#include <stdio.h>
const int MAX = 4;
int main ()
{
char *names[] = { "New Delhi", "Madhya Pradesh", "Uthra Pradesh", "West Bengal", };
int i = 0;
for ( i = 0; i < MAX; i++)
{
printf("Value of names[%d] = %s\n", i, names[i] );
}
return 0;
95
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

}
Output of the above program using array of pointers:
Value of names[0] = New Delhi
Value of names[1] = Madhya Pradesh
Value of names[2] = Uthra Pradesh
Value of names[3] = West Bengal

4.7. Pointer to Array


An array name is a constant pointer to the first element of the array. Therefore, in this
declaration,

int balance[20];

balance is a pointer to &balance[0], which is the address of the first element of the array.

Example
In this code, the pointer ptr that points to the address of the first element of an integer
array called balance.

#include<stdio.h>
void main()
{
int balance[]={1,2,3,4,5};
int *ptr;
ptr = balance;
printf(“pointer ptr points to the address %u \n”,ptr);
printf(“Address of first element %u\n”, balance);
printf(“Address of first element %u\n”, &balance[0]);
}

Output
pointer ptr points to the address 65500
Address of first element 65500
Address of first element 65500
`
Array Names as Constant Pointers
It is legal to use array names as constant pointers and vice versa. Therefore, *(balance +
4) is a legitimate way of accessing the data at balance[4].

The address of the first element is "ptr", the array elements can be accessed
using *ptr, *(ptr + 1), *(ptr + 2), and so on.

Example
The following example demonstrates all the concepts discussed above,
96
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

#include<stdio.h>
void main()
{
int balance[]={1000, 2, 399, 77,54};
int *ptr = &balance[0];
printf(“Array values using pointer\n”);
printf(“Array values using balance array name\n”)
for(i=0;i<5;i++)
{
printf(“ *(balance + %d) = %d\n”, i, *(balance+i));
}
printf(“Array values using pointer name ptr\n”)
for(i=0;i<5;i++)
{
printf(“ *(ptr + %d) = %d\n”, i, *(ptr+i));
}
}
Output
Array values using pointer
Array values using balance array name
*(balance ) = 1000
*(balance+1) = 2
*(balance+2) = 399
*(balance+3) = 77
*(balance+4) = 54
Array values using pointer name ptr
*(ptr) = 1000
*(ptr+1) = 2
*(ptr+2) = 399
*(ptr+3) = 77
*(ptr+4) = 54

In the above example, ptr is a pointer that can store the address of a variable of integer
type. Once the address in ptr is avaibalbe, *ptr will give the value available at the address stored
in ptr.

4.8. Pointers to void


A void pointer is a special type of pointer. It can point any dataype from an integer, a
float, to a string of characters. It’s sole limitation is that the pointed data cannot be referenced
directly. Therefore typecasting (or) assignment must be used to turn the void pointer to a pointer
of a concrete data type which can be referred.

97
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

Example
#include < stdio.h>
void main()
{
int a = 5;
double b=3.1415;
void *vp;
vp = &a;
printf(“\n a = %d “, *(int *)vp));
vp = &b;
printf(“\n b = %d “, *(double *)vp));
}
Output
a=5
b = 3.1415

4.9. Command Line arguments


The main() function also pass arguments or parameters like other function. It has two
arguments,
argc  argument count
argv  argument vector
Syntax:
main(int argc, char *char [])
(or)
main(int argc, char **argv)

where argc – the number of arguments, argv – is a pointe to an array of strings, (or)
pointer to pointer to character, and it is used to pass strings to the programs.

After successful compilation, the program is executed. For example in Unix operating
system to compile the program saved as trial.c, the command given at the command prompt is
cc trial.c
The execution command is a.out , which is called as command line.
The values of argv are given in the command line. Value of argc is automatically counted
by compiler when main() is invoked. Since the values are available and obtained from the
command line, they are also known as Command line arguments.
a.out line plane circle

The argc value for the above execution command line iwith string constants is 4.
argv[0] – is pointer to first character ‘a’ in the string constant a.out
argv[1] - is pointer to first character ‘l’ in the string constant line
argv[2] - is pointer to first character ‘p’ in the string constant plane
argv[3] - is pointer to first character ‘c’ in the string constant circle
argv[4] – is always NULL pointer to mark the end of the argv array
98
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

The command line argument can be written as program,

main(int argc, char **argv)


{
int i;
if(argc != 3)
{
printf(“ Program parameters missing \n”);
exit(0);
}

for(i=0;i<argc;i++)
printf(“%s\n”, argv[i]);
}

Output
a.out one two three
a.out
one
two
three

4.10. Array of Pointers


One important use of pointers is to handle the table strings. Consider the following array
of strings:
char array[3][25];

The above declarations shows three individual strings will be of equal lengths. Therefore
instead of making each row of fixed number of characters, pointers to the string of variable
length can be made. For example,
char *name[3] = {
“New Zealand”,
“Australia” ,
“India”
};
Declares name to be an array of three pointers to characters, each pointer pointing to a
particular name as :
name[0] --- New Zealand
name[1] --- Australia
name[2] --- India

This is explained with the following C program:


99
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

#include <stdio.h>
void main()
{
char *name[3] = { “New Zealand”,
“Australia”
“India” };
printf(“Using array of poitners\n”);
for(i=0; i<3;i++)
{
printf(“%s\n”, *(name+i));
}
}

Output
New Zealand
Australia
India

4.11. Pointers as Function Arguments

The pointers can be sent as function arguments, which are otherwise named as call by
reference. When the address is passed as the actual argument in main function, the parameters
are received with the pointer as a formal argument in a called function. The process of calling a
function using pointers to pass the addresses of variables is known as ‘Call by Reference’.

Consider the following code,

main()
{
int x;
x = 20;
change(&x);
printf(“%d\n”,x);
}

change(int *p)
{
*p = *p +10;
}

When the function change() is called, the address of the variable x, not its value, is passed
into the function change(). Inside change(), the variable p is declared as a pointer and therefore p
is the address of the variable x. The statement,
100
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

*p = *p + 10;

means ‘add 10 to the value stored at the address p. In the memory of p the value of 20
will become 30.

The call by reference can be explained by another example program as shown below,

#include<stdio.h>
void swap(int *, int *);
void main()
{

int a = 10, b = 20;


printf(“Before swapping: ”);
printf(“a=%d\t b=%d\n”, a,b);

swap(&a,&b);

printf(“After swapping: ”);


printf(“a=%d\t b=%d\n”, a,b);
}

Output
Before swapping: a=10 b=20
After swapping: a=20 b=10

4.12. Dynamic Memory Allocation

The dynamic allocation of memory is performed through the library functions malloc(),
calloc(), realloc() and free() are used. These functions are defined in the <stdlib.h> header file.
The malloc() function reserves a block of memory of the specified number of bytes. And, it
returns a pointer of void which can be casted into pointers of any form.

Syntax of malloc()
ptr = (casttype *) malloc(size)

Example
ptr = (float*) malloc(100 * sizeof(float));

The above statement allocates 400 bytes of memory. It's because the size of float is 4
bytes. And, the pointer ptr holds the address of the first byte in the allocated memory.

The expression results in a NULL pointer if the memory cannot be allocated.


101
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

calloc()
The name "calloc" stands for contiguous allocation. The malloc() function allocates memory and
leaves the memory uninitialized, whereas the calloc() function allocates memory and initializes
all bits to zero.

Syntax
ptr = (castType*) calloc(n,size);

Example
ptr = (float *) calloc(25, sizeof(float));

The above statement allocates contiguous space in memory for 25 elements of type float.
free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed
on their own. An explicit free() statement must be issued to release the space allocated.
free (ptr);

This statement frees the space allocated in the memory pointed by ptr.

Example
// Program to calculate the sum of n numbers entered by the user

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

int main()
{
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) calloc(n, sizeof(int));
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements: ");
for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
102
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

free(ptr);
return 0;
}

Output
Enter number of elements: 3
Enter elements: 100
20
36
Sum = 156

4.13. Pointers in Real time applications


Pointers are a fundamental feature of C programming and are widely used in real-time
applications due to their ability to directly manipulate memory and improve performance. Below
are examples and explanations of real-time applications of pointers.
Dynamic Memory Allocation
Pointers are essential for dynamic memory management using functions like malloc,
calloc, realloc, and free from the <stdlib.h> library. This is particularly useful in applications where
the amount of data to be processed is not known beforehand.
Data Structures (Linked Lists, Trees, Graphs)
Pointers are extensively used to implement dynamic data structures like linked lists, trees,
and graphs. In the C language in the cases of structures, functions, and arrays the pointers are
used. Here, the pointers help in reducing the code and improving the program’s performance.

Exercise
1. Write a program to create a dynamic array using pointers and manipulate its
elements.
2. How can pointers be used to implement data structures like linked lists and trees?
3. What are dynamic memory allocation functions in C? List and explain them.
4. Explain the significance of pointers in dynamic memory allocation.
5. Write a program to demonstrate calling a function using a pointer.
6. What is a void pointer? Why is it considered a generic pointer?
7. Write a program to store and print a list of strings using an array of pointers.
8. Explain how an array name acts as a pointer.
9. Write a program to traverse an array using a pointer.
10. Write a program to demonstrate type casting with void pointers.

103
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

5. UNIT 5 STRUCTURES, UNIONS, ENUMERATED TYPES AND FILES

Type Definition (typedef), Enumerated Types, Structure: Definition and Initialization of


Structures, Accessing Structures, Nested Structures, Arrays of Structures, Structures and
Functions, Pointers to Structures, Self-Referential Structures, Unions, FILES: Introduction
to Files, Modes of File Operations, Text and Binary Files, File I/O Operations.

5.1. Type Definition


C language supports a feature known as “type definition” using the keyword typedef
declaration. Its purpose is to redefine the name of an existing variable type. The main advantage
of typedef is to improve the readability of the programs by defining user friendly names to data
type.

Syntax
typedef datatype identifier;

where “typedef” is the keyword, “datatype” refers one of the basic datatypes, “identifier”
is new name given to the basic data type. The typedef cannot create new datatype.

Some examples of typedef are,

typedef int units;


typedef float marks;

Here units symbolizes int and marks symbolizes float. The declaration of variables now
can be modified as follows,

units home1, home2;


marks class1[30], class2[30];

Here home1, home2 are declared as int datatype, class1[3], class2[3] are declared as float
datatype.

It can be significant when the name of a particular data type is long and unwieldy, as it
often is with structure declarations.

For example, consider the following structure declaration:


struct employee
{
char name[ 30 ] ;
int age ;
float bs ;
};
104
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

struct employee e ;

This structure declaration can be made more handy to use when renamed using typedef as
shown below.
struct employee
{
char name[ 30 ] ;
int age ;
float bs ;
};
typedef struct employee EMP ;
EMP e1, e2 ;

Thus, by reducing the length and apparent complexity of data types, typedef can help to
clarify source listing and save time and energy spent in understanding a program.

The above typedef can also be written as

typedef struct employee


{
char name[ 30 ] ;
int age ;
float bs ;
} EMP ;
EMP e1, e2 ;

typedef can also be used to rename pointer data types as shown below.

struct employee
{
char name[ 30 ] ;
int age ;
float bs ;
};
typedef struct employee * PEMP ;
PEMP p ;
p -> age = 32 ;

5.2. Enumerated types

Enumerated data type is another user defined type provided to ease programming. An
enum data type can hold a list of values provided. This helps in ensuring only valid values are
captured.

105
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

enum identifier {value1, value2, …… valuen};

The “identifier” is a user-defined data type which can be used to declare variables that
can have one of the values enclosed within the braces known as enumeration constants. After this
definition, the variables can be declared which are of ‘new’ type as below:
enum identifier v1,v2, … vn;

The enumerated variables v1,v2, … vn can only have one of the values of value1, value2,
… valuen. The assignments of the following type are valid.
v1 = value2;
v2 = value3;

The format of the enum definition is similar to that of a structure. Here’s how the
example stated above can be implemented.

enum mar_status
{
single, married, divorced, widowed
};
enum mar_status person1, person2 ;

Example 1
Printing the Values of Weekdays
#include <stdio.h>
enum days{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
int main()
{
// printing the values of weekdays
for(int i=Sunday;i<=Saturday;i++)
{
printf("%d, ",i);
}
return 0;
}

Output
1,2,3,4,5,6,7,

Example 2
Assigning and Fetching Custom Values of Enum Elements
#include<stdio.h>
enum containers
{
cont1 = 5,
106
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

cont2 = 7,
cont3 = 3,
cont4 = 8
};

int main()
{
// Initializing a variable to hold enums
enum containers cur_cont = cont2;
printf("Value of cont2 is = %d \n", cur_cont);
cur_cont = cont3;
printf("Value of cont3 is = %d \n", cur_cont);
cur_cont = cont1;
printf("Value of hearts is = %d \n", cur_cont);
return 0;
}

Output
Value of cont2 is = 7
Value of cont3 is = 3
Value of hearts is = 5

We have declared an enum named containers with four different containers as the
elements in the above code. We have then given custom values to the elements and initialized the
variable for the enum multiple times to print the relevant output.

Example 3
enum week{Mon, Tue, Wed, Thurs, Fri, Sat, Sun};

In this case, Mon is assigned a default value of 0, Tue is 1, Wed is 2, and so on. If we
want to assign custom values to these enum members, we can do it as follows:
enum week
{
Mon=10,
Tue=20,
Wed=30,
Thurs=40,
Fri=50,
Sat=60,
Sun=70,
};

107
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

5.3. Structure: Introduction

In earlier chapters we have seen that arrays can be used to represent a group of data items
that belong to the same data types such as int, float, char. In real-world applications, there will be
different data items of different data types under one single frame that have to be handled. C
provides a derived data type structure to address the aforementioned problem. A structure is a
convenient tool for handling a group of logically related data items. For example, it can be used
to represent a set of attributes, such as student_name, roll_number, and marks. The structure is
analogous to that of a ‘record’ in many other languages. More examples of structure are,

Time: seconds, minutes, hours


Date : Day, month, year
Book: name, author, publication, year, price
Address: door number, street, place, pincode

Structure is a powerful concept that helps to organize the complex data in a meaningful
way in the program.

Definition and Initialization of Structures

The structure is a user-defined data type that can be used to group items of possibly
different types into a single type. The struct keyword is used to define the structure. The items in
the structure are called its member and they can be of any valid data type. Additionally, the
values of a structure are stored in contiguous memory locations.

The general format of a structure definition is as follows:

Syntax
struct tag_name
{
data_type member1;
data_type member2;
data_type member3;
------------ ------------;
------------- ------------;
};

In defining a structure,
1. The template is terminated with a semicolon.
2. Each member is declared independently for its name and data type.
3. The tag_name can be used to declare structure variable.

Structure Definition
To use structure in a program, it is necessary to define its instance. The structure
108
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

variables can be declared in two ways.

1. Structure Variable Declaration with Structure Template

struct structure_name
{
data_type member_name1;
data_type member_name2;
....
....
}variable1, varaible2, ...;

2. Structure Variable Declaration after Structure Template

struct structure_name varible1, variable2, …. variablen;

Accessing structure members

The structure members can be accessed by using the (.) dot operator.

structure_name.member1;
structure_name.member2;

In case the structure is pointed by pointer variable, the members can be accessed by 
operator.

pointer_name  member1;
pointer_name  member2;
Example of defining a structure :

struct book_bank
{
char title[50];
char author[40];
int pages;
float price;
};
In this example, book_bank is the structure tag, holds the data fields of title, author,
pages, and price, which are called as members.
Note that the above definition has not declared any variables. It simply describes a
format called template to represent the information as shown below:

title - array of 50 characters


author – array of 40 characters
109
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

pages – integer
price - float

The declaration of the book_bank is given as,

struct book_bank book1,book2,book3;

where book1, book2, and book3 are the variables of structure data type with the members
as shown above in the definition. The members are not variables, they won’t occupy memory
space until they are declared using structure variable names.

struct book_bank
{
char title[50];
char author[40];
int pages;
float price;
}book1,book2,book3;

The above structure declaration is also valid, declared using method 2. The use of
tag_name is optional here, for example,

struct
{ char title[50];
char author[40];
int pages;
float price;
} book1,book2,book3;

declares book1, book2, book3 are structure variables representing three books.

Initialisation of structures

The structure variable can be initialized at compile time.

main()
{
struct
{
int weight;
float height;
} student = {60, 160.78};
……
110
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

……
}

This assigns 60 to student.weight and 160.78 to student.height.

The structure can be initialized in many ways. The following statements initialize two
structure variables. Here it is essential to use tag name.

main()
{
struct st_record
{
int weight;
float height;
};
struct st_record student1 = {60, 160.88);
struct st_record student2 = {55, 152.65);

…..
…..
}

Another method to initialize


struct st_record
{
int weight;
float height;
} student1= {60, 160.78};

main()
{
struct st_record student2 = {55,155.5};
……
……
}

C language does not permit to initialize individually within the template. The
initialization can be done only along with the declaration of actual variables.

Copying and comparing structure variables

Two structure variables of same members inside it, can be copied and compared with the
use of structure variable name.

111
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

If book1 and book2 belong to the same structure, then the following statements are valid.

book1 = book2;
book2 = book1;

But the logical operations on the structure variables shown below are not permitted,

book1 == book2
book1!= book2

In such a cases, comparison should be made member to member, like,

book1.title == book2.title
book1.price != book2.price

The above comparisons are valid ones.

A structure contains a number of data types grouped together. These data types may or
may not be of the same type. The following example illustrates the use of this data type:

# include <stdio.h>
int main( )
{
struct book
{
char name ;
float price ;
int pages ;
};
struct book b1, b2, b3 ;
printf ( "Enter names, prices & no. of pages of 3 books\n" ) ;
scanf ( "%c %f %d", &b1.name, &b1.price, &b1.pages ) ;
scanf ( "%c %f %d", &b2.name, &b2.price, &b2.pages ) ;
scanf ( "%c %f %d", &b3.name, &b3.price, &b3.pages ) ;
printf ( "And this is what you entered\n" ) ;
printf ( "%c %f %d\n", b1.name, b1.price, b1.pages ) ;
printf ( "%c %f %d\n", b2.name, b2.price, b2.pages ) ;
printf ( "%c %f %d\n", b3.name, b3.price, b3.pages ) ;
return 0 ;
}

Output
Enter names, prices and no. of pages of 3 books
A 100.00 354
112
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

C 256.50 682
F 233.70 512
And this is what you entered
A 100.000000 354
C 256.500000 682
F 233.700000 512

Storing Structure Elements

Whatever be the elements of a structure, they are always stored in contiguous memory
locations. The following program would illustrate this.

/* Memory map of structure elements */


# include <stdio.h>
int main( )
{
struct book
{
char name ;
float price ;
int pages ;
};
struct book b1 = { 'B', 130.00, 550 } ;
printf ( "Address of name = %u\n", &b1.name ) ;
printf ( "Address of price = %u\n", &b1.price ) ;
printf ( "Address of pages = %u\n", &b1.pages ) ;
return 0 ;
}

Output
Address of name = 65518
Address of price = 65519
Address of pages = 65523

The structure elements are stored in memory as shown in the table.

Member Name b1.name b1.price b1.pages


Value ‘B’ 130 200
Memory Address 65518 65519 65523

5.4. Nested structures

A nested structure is a structure within structure. One structure can be declared inside
another structure in the same way structure members are declared inside a structure.
113
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

Syntax:
struct structure_name
{
data_type member_name1;
data_type member_name2;
struct nested_structure
{
data_type member_name 3;
data_type member_name 4;
}inner_structure1;
....
....
}outer_structure1;

The member of the nested structure can be accessed with the following syntax.

outer_structure1.inner_structure1.member3
outer_structure1.inner_structure1.member4

Example program to explain the nesting of structures using employee details with date of
joining as the inner structure.

#include <stdio.h>

void main()
{
struct employee
{
int emp_id;
char name[30];
int basic_pay;
int dearness;
int house_rent;
int net_pay;
struct
{
int date;
int month;
int year;
}doj;
}emp1,emp2;

printf(“ enter the employee 1 details”);


scanf(“%d%s%d”, &emp1.emp_id, emp1.name, &emp1.basic_pay);
114
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

printf(“ \nenter the employee 1 date of joining details\n”);


scanf(“%d%d%d”, &emp1.doj.date &emp1.doj.month, &emp1.doj.year);
printf(“\n enter the employee 2 details”);
scanf(“%d%s%d”, &emp2.emp_id, emp2.name, &emp2.basic_pay);
printf(“ \nenter the employee 2 date of joining details\n”);
scanf(“%d%d%d”, &emp2.doj.date &emp2.doj.month, &emp2.doj.year);
emp1.house_rent= emp1.basic_pay * (10/100.0);
emp1.dearness = emp1.basic_pay * (15/100.0);

emp2.house_rent= emp2.basic_pay * (10/100.0);


emp2.dearness = emp2.basic_pay * (15/100.0);

printf(“Calculating Net pay for employee 1 and 2\n”);


emp1.net_pay = emp1.basic_pay + emp1.house_rent+ emp1.dearness;
emp2.net_pay = emp2.basic_pay + emp2.house_rent+ emp2.dearness;

printf(“\t\t\t Employee Details\t\t\n”);


printf(“Emplyee Id\t Name \t\t Basic Pay\t DOJ\t Net Pay\n”);
printf(“%d\t%s\t\t %d\t%d-%d-%d\t%d\n”, emp1.emp_id,emp1.name,emp1.basic_pay,
emp1.doj.date,emp1.doj.month,emp1.doj.year);
printf(“%d\t%s\t\t %d\t%d-%d-%d\t%d\n”, emp2.emp_id,emp2.name,emp2.basic_pay,
emp2.doj.date,emp2.doj.month,emp2.doj.year);
}

Output
enter the employee 1 details
111 Ram 10000
enter the employee 1 date of joining details
13 09 2024
enter the employee 2 details
222 Latha 20000
enter the employee 2 date of joining details
1 1 2022
Employee Details
111 Ram 10000 13-09-2024 12500
222 Latha 20000 01-01-2022 25000

5.5. Arrays of Structures

The data of group of employees or students have to be collected, stored and manipulated,
then array of structures can be declared and used. The general syntax is given by,

struct structure_name
115
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

{
data_type member_name1;
data_type member_name1;
....
....
}array_name[max_size];

The student details of the class of 20 can be declared as given below.

struct class student[20];

The above problem can be written as C program, to calculate the total and average of the
students of n number of students.

#include<stdio.h>
struct student
{
int regno;
char name[30];
int mark1,mark2,mark3;
int total;
float average;
};

void main()
{
struct student stud[3];
int i;
printf(“enter 3 student details\n”);
for(i=0;i<3;i++)
{

scanf(“%d%s%d”, &stud[i].regno, stud[i].name, &stud[i].mark1,


&stud[i].mark2, &stud[i].mark3);

stud[i].total = stud[i].mark1+stud[i].mark2+stud[i].mark3;
stud[i].average=stud[i].total/3.0;
}
printf(“Reg No.\t Name\t\t Mark1\t Mark2\tMark3\tTotal\tAverage\n”);

for(i=0;i<3;i++)
{

116
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

printf(“%d\t%s\t\t%d\t%d\t%d\t%d\t%f\n”, stud[i].regno, stud[i].name,


stud[i].mark1,stud[i].mark2, stud[i].mark3,stud[i].total,stud[i].average);
}
}

Output

enter 3 student details


101 Soorya 98 88 88
102 Srividhya 89 89 78
103 Swathy 78 77 76

Reg No. Name Mark1 Mark2 Mark3 Total Average


101 Soorya 98 88 88 274 91.333333
102 Srividhya 89 89 78 256 85.333333
103 Swathy 78 77 76 231 77.000000

5.6. Structures and Functions

Structure Pointer

A structure pointer is defined as Example


the pointer which points to the address of the
memory block that stores a structure known as int main()
the structure pointer. Complex data structures {
like linked lists, trees, graphs, etc. are created struct point s;
with the help of structure pointers. The structure // Initialization of the structure
pointer tells the address of a structure in memory pointer
by pointing the variable to the structure variable. struct point* ptr = &s;
In the example s is an instance of struct
point and ptr is the struct pointer because it is return 0;
storing the address of struct point. }

Accessing the Structure Member with the Help of Pointers

117
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

// C Program to demonstrate Structure pointer There are two ways to


#include <stdio.h> access the members of the
#include <string.h> structure with the help of a
structure pointer:
struct Student {
int roll_no; 1. With the help of (*)
char name[30]; asterisk or indirection
char branch[40]; operator and (.) dot
int batch; operator.
}; 2. With the help of ( -> )
Arrow operator.
int main()
{
struct Student s1; The example provides a
struct Student* ptr = &s1; program to access the structure
members using the structure
s1.roll_no = 27; pointer with the help of the dot
strcpy(s1.name, "Kamlesh Joshi"); operator.
strcpy(s1.branch, "CSE");
s1.batch = 2019;
printf("Roll Number: %d\n", (*ptr).roll_no);
printf("Name: %s\n", (*ptr).name);
printf("Branch: %s\n", (*ptr).branch);
printf("Batch: %d", (*ptr).batch);

return 0;
}

Below is the program to access the structure members using the structure pointer with the
help of the Arrow operator. In this program, we have created a Structure Student containing
structure variable s. The Structure Student has roll_no, name, branch, and batch.

// C Program to demonstrate Structure pointer


#include <stdio.h>
#include <string.h>

// Creating Structure Student


struct Student {
int roll_no;
char name[30];
char branch[40];
int batch;
};

118
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

// variable of structure with pointer defined


struct Student s, *ptr;

int main()
{

ptr = &s;
// Taking inputs
printf("Enter the Roll Number of Student\n");
scanf("%d", &ptr->roll_no);
printf("Enter Name of Student\n");
scanf("%s", &ptr->name);
printf("Enter Branch of Student\n");
scanf("%s", &ptr->branch);
printf("Enter batch of Student\n");
scanf("%d", &ptr->batch);

// Displaying details of the student


printf("\nStudent details are: \n");

printf("Roll No: %d\n", ptr->roll_no);


printf("Name: %s\n", ptr->name);
printf("Branch: %s\n", ptr->branch);
printf("Batch: %d\n", ptr->batch);

return 0;
}

Output
Enter the Roll Number of Student
27
Enter Name of Student
Kamlesh_Joshi
Enter Branch of Student
CSE
Enter batch of Student
2019
Student details are:
Roll No: 27
Name: Kamlesh_Joshi
Branch: CSE
Batch: 2019

119
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

5.7. Functions using structure

In functions, structure data type can be passed as an argument. The syntax is given as,

Function_name(structure variable_name);

The called function takes the following form:

data_type function_name(struct structure_name)


{
…..
…..
return(expression);
}

This can be explained with the simple programming of passing structure as argument and
returning structure as argument.

#include <stdio.h>
struct student
{
int regno;
char name[30];
int mark[5];
int total;
float average;
};

struct calculate(struct [],int);

int main()
{
struct student std[3],update[3];
int n,i,j;
printf("enter 3 students detail");
for(i=0;i<3;i++)
{
scanf("%d%s",&std[i].regno,std[i].name);
std[i].total=0;
for(j=0;j<5;j++)
{
scanf("%d",&std[i].mark[j]);
120
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

std[i].total+=std[i].mark[j];
}
}
update=calculate(std,3);
for(i=0;i<3;i++)
{
printf("Average of [%d]th student = %f\t",i,update[i].average);
}

return 0;
}

struct calculate(struct std[],int n)


{
int j;
for(j=0;j<n;j++)
{
std[i].average = std[i].total/n;
}
return(std);
}

5.8. Pointers to Structures

A structure pointer is defined as the pointer which points to the address of the memory
block that stores a structure known as the structure pointer. Complex data structures like Linked
lists, trees, graphs, etc. are created with the help of structure pointers. The structure pointer tells
the address of a structure in memory by pointing the variable to the structure variable.

Below is the program to access the structure members using the structure pointer with the
help of the Arrow operator. In this program, we have created a Structure Student containing
structure variable a. The Structure Student has regno, name, mark1, mark2, total and average as
members.

#include <stdio.h>

struct student
{
int regno;
char name[30];
int mark1;
int mark2;
int total;
121
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

float average;
};

void main()
{
struct student a,*p;
p=&a;

printf("Enter the student details\n");


scanf("%d%s%d%d",&p->regno,p->name,&p->mark1,&p->mark2);
p->total = p->mark1+p->mark2;
p->average=p->total/2.0;
printf(“The student details using pointer to the structure\n”);

printf("\n%d\t%s\t%d\t%d\n",p->regno,p->name,p->mark1,p->mark2);
printf(“Total = %d \t Average = %f\n”, p->total, p->average);
}

Output
Enter the student details
1234
Soorya
89
88
The student details using pointer to the structure
1234 Soorya 89 88
Total = 177 Average =88.500000

5.9. Self Referential Structures

Self Referential structures are those structures that have one or more pointers which point
to the same type of structure, as their member.

In other words, structures pointing to the same type of structures are self-referential in
nature.

struct node {
int data1;
char data2;
struct node* link;
};

int main()
122
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

{
struct node ob;
return 0;
}

In the above example ‘link’ is a pointer to a structure of type ‘node’. Hence, the structure
‘node’ is a self-referential structure with ‘link’ as the referencing pointer. An important point to
consider is that the pointer should be initialized properly before accessing, as by default it
contains garbage value.

Self-referential structure with single link

These structures can have only one self-pointer as their member. The following example
will show us how to connect the objects of a self-referential structure with the single link and
access the corresponding data members. The connection formed is shown in the following figure.

ob1 ob2

Figure 4.4

#include <stdio.h>

struct node {
int data1;
char data2;
struct node* link;
};

int main()
{
struct node ob1; // Node1

// Initialization
ob1.link = NULL;
ob1.data1 = 10;
ob1.data2 = 20;

struct node ob2; // Node2

// Initialization
ob2.link = NULL;
ob2.data1 = 30;
123
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

ob2.data2 = 40;

// Linking ob1 and ob2


ob1.link = &ob2;

// Accessing data members of ob2 using ob1


printf("%d", ob1.link->data1);
printf("\n%d", ob1.link->data2);
return 0;
}

Output
30
40

Self-referential structures are very useful in creation of other complex data structures
like:

 Linked Lists
 Stacks
 Queues
 Trees
 Graphs etc.

5.10. Union
The Union is a user-defined data type in C language that can contain elements of the
different data types just like structure. But unlike structures, all the members in the C union are
stored in the same memory location. Due to this, only one member can store data at the given
instance.

Syntax

The syntax of the union can be easily understood by dividing into three section as below:

union union_name
{
datatype member1;
datatype member2;
……
……
};

In this part, the template of the union is declared, i.e., only declare the members’ names
and data types along with the name of the union. No memory is allocated to the union in the
124
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

declaration.

The definition of a variable of the union type is written in C program to start using union
members.

1. Defining Union Variable with Declaration

union union_name
{
datatype member1;
datatype member2;
……
……
}var1,var2,….varn;

where var1,var2,….varn are the variables of union datatype with members within it.
2. Defining Union Variable after Declaration
union union_name var1,var2,….varn;

The union members can be accessed with (.) dot operator, such as var1.member1.
The union can be explained with the program as shown below,
#include <stdio.h>
// union template or declaration
union un {
int member1;
char member2;
float member3;
};
// driver code
int main()
{
// defining a union variable
union un var1;
// initializing the union member
var1.member1 = 15;
printf("The value stored in member1 = %d", var1.member1);
return 0;
}

The table summarizes the differences between Structure and Union.

Aspect Structure Union

125
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

Definition A structure is a user-defined data A union is a user-defined data type that


type that groups variables of allows different variables to share the
different types. same memory location.
Memory Each member of a structure is All members of a union share the same
Allocation allocated separate memory. memory, and its size equals the largest
member.
Access to All members of a structure can be Only one member can be accessed at a
Members accessed simultaneously. time since they share the same memory.
Size The size of a structure is the sum of The size of a union is equal to the size of
the sizes of all its members. its largest member.
Usage Useful when all members need to Useful when a variable needs to store
store independent values. different types of data at different times.
Example struct { int x; float y; }; union { int x; float y; };
Declaration
Performance Accessing structure members is Accessing union members is efficient in
straightforward but uses more terms of memory usage.
memory.
Initialization Multiple members can be Only one member can be initialized at a
initialized at once. time.
Example Employee records, where all Sensor data, where only one value (e.g.,
Usage attributes are needed temperature or pressure) is needed at a
simultaneously. time.
Applications Used to define complex data Used for memory-efficient storage, such
structures like databases, linked as protocol parsers or embedded systems.
lists, etc.

5.11. Files
Unlike variables, which hold data temporarily during the execution of a program, files
allow data to persist even after the program terminates. File handling in C enables reading,
writing, and manipulating data stored in files

5.12. Introduction to Files

The main purpose of using files are:


1. Permanent Storage: Data is retained even after the program ends.
2. Data Sharing: Files allow data to be shared between different programs or users.
3. Large Data Handling: Suitable for handling large datasets that can't be stored in variables
due to memory constraints.

126
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

5.13. Modes of File Operations

The files can be opened in different modes. The mode determines the purpose of opening
the file (e.g., reading, writing, appending).

File Modes
Mode Description
"r" Opens a file for reading. The file must exist.
Opens a file for writing. Creates a new file if it doesn't exist or truncates an
"w"
existing file.
Opens a file for appending. Data is added to the end of the file. Creates the file if it
"a"
doesn’t exist.
"r+" Opens a file for both reading and writing. The file must exist.
Opens a file for both reading and writing. Creates a new file if it doesn’t exist or
"w+"
truncates an existing file.
"a+" Opens a file for both reading and appending. Creates the file if it doesn’t exist.

5.14. Text and Binary Files

Text Files
 Stores data in a human-readable format.
 Each line ends with a newline character (\n).
 Example: .txt, .csv

Binary Files
 Stores data in binary format, which is not human-readable.
 More efficient for storing large and structured data.
 Example: .dat, .bin

File I/O Operations


The stdio.h library provides functions for file operations. Here are the common file I/O
functions:

Function Description
fopen() Opens a file in a specified mode.
fclose() Closes an opened file.
fgetc() Reads a single character from a file.
fputc() Writes a single character to a file.
fgets() Reads a string from a file.
fputs() Writes a string to a file.
127
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

Here are few sample programs using file handling functions.

Example 1: Writing to a Text File Example 2. Reading from a Text File


#include <stdio.h> #include <stdio.h>

int main() { int main() {


FILE *file = fopen("example.txt", "r");
FILE *file = fopen("example.txt", "w"); char line[100];
if (file == NULL) {
printf("Error opening file!\n"); if (file == NULL) {
return 1; printf("Error opening file!\n");
} return 1;
}
fprintf(file, "Hello, World!\n"); while (fgets(line, sizeof(line), file)) {
fclose(file); printf("%s", line);
return 0; }
fclose(file);
} return 0;
}

Example 3: Writing to a Binary File Example 4: Reading from a Text File


#include <stdio.h> #include <stdio.h>

int main() { int main() {


FILE *file = fopen("example.bin", "wb"); FILE *file = fopen("example.txt", "r");
int numbers[] = {1, 2, 3, 4, 5}; char line[100];

if (file == NULL) { if (file == NULL) {


printf("Error opening file!\n"); printf("Error opening file!\n");
return 1; return 1;
} }
while (fgets(line, sizeof(line), file)) {
fwrite(numbers, sizeof(int), 5, file); printf("%s", line);
fclose(file); }
return 0; fclose(file);
} return 0;
}

File handling is essential for performing operations on data that need to persist beyond
the program's execution. By understanding different modes, types of files, and file I/O functions,
programmers can efficiently manage data in their applications.
128
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C

Exercise

1. What is a file in C programming, and why is it used?


2. Differentiate between text files and binary files.
3. What is the purpose of the fopen() function?
4. Name the file mode used to append data to an existing file.
5. What does the "r+" mode allow you to do in file handling?
6. Write the syntax for opening a file in write mode.
7. What is the function of fread() in file handling?
8. How does fwrite() differ from fprintf()?
9. List two advantages of binary files over text files.
10. Why is fclose() important in file handling?
11. Mention any two commonly used file modes in C.
12. How does the newline character (\n) behave in text files?
13. What does feof() function check for in file operations?
14. Define file pointer in the context of file handling.
15. Why is it important to check if a file is successfully opened?

129
Department of Computer Science and Engineering-BIHER
Chennai,India.

You might also like