Arthi
Arthi
(U24CSTJ02)
School of Computing,
Chennai.
R.Vaishali
School of Computing,
Chennai.
Title : Structured Programming Using C
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
Pages : 129
Price : 100/-
Published by :
Selaiyur,
Chennai 600073,
India
E-mail :[email protected]
Website : www.bharathuniv.ac.in
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 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.
Dr.R.J.Aarthi
Assistant Professor/CSE/BIHER
Contents
1 UNIT-I PROBLEM SOLVING
2.1. Overview 18
2.4. Tokens 24
2.9. Function 56
4 UNIT IV POINTERS
4.1. Introduction 86
The process of computer-based problem solving typically involves the following steps:
Figure 1.1
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
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.
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
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.
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.
Euclidean Algorithm
To find Greatest Common Divisor GCD(A,B), the below algorithm can be used
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.
Among the operations that can be carried out on ordered sets are:
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
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.
Figure 1.2
o From the positional index, till the end of the array the elements at position is replaced
with the consecutive elements
Figure 1.3
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
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
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.
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
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
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
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
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
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
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
17
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C
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.
Importance of 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.
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.
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.
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.
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.
20
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C
The data types supported by C are classified into three major categories:
Figure 2.1
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.
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
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
2. Volatile Example
3. Restrict
23
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C
2.4. Tokens
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
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
Identifiers
Example
int marks;
char studentName[30];
26
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C
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.
A variable name may contain letters, digits and underscore symbol. The following are the
rules to specify a 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
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
}
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.
Operators
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.
&& Logical AND - Returns TRUE if all conditions are 10 < 5 && 12 >
TRUE otherwise returns FALSE 10 is FALSE
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.
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
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.
+= 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
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.
34
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C
sizeof(variableName);
Expressions
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
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
1 [] array reference
structure member
->
access
36
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C
structure member
.
access
~ 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
Expression Evaluation
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
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
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
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")
}
'switch' statement
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
While Loop
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
44
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C
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
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() ;
}
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. }
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.
49
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C
void anotherFunction() {
printf("%d", var); // Prints 5 (global variable is
accessed here)
}
Static Variables
50
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C
Block-Level Scope:
Understanding of scope rules is critical to avoid variable conflicts and to ensure variables
are used in the right context.
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)
51
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C
52
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C
void function1()
{
globalVar += 5;
printf("%d", globalVar);
}
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.
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
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.
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.
Figure 2.4
User-defined functions
57
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C
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
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
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
1. No arguments , No return
2. No arguments, With return
3. With arguments, No return
4. With arguments, With return
62
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C
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
64
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C
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.
data_type array_name[array_size];
Here, numbers is an array that can hold 5 integer elements, with indices ranging from 0 to
4.
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.
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
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
}
return 0 ;
}
The above operations are explained with the algorithm and code as follows.
69
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C
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
{ 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
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
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
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 ;
}
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];
}
}
}
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
Storage in Memory
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];
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
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.
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.
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.
To output the string, the printf() function together with the format specifier %s is used to
tell C compiler about the usage of strings:
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
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.
String literals can be assigned without size. Here, the name of the string str acts as a
pointer because it is an array.
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.
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.
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.
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.
Here are few sample programs that use various string functions.
81
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C
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
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
85
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C
4. UNIT IV POINTERS
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.
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
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.
pointer = &variable;
Example
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.
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
# 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 ;
}
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.
k=j-6;
# 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.
#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
printf(“Area = %f\n”,a);
printf(“Perimenter = %f”,p);
}
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.
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.
#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
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
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;
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
#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
}
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
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.
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
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
for(i=0;i<argc;i++)
printf(“%s\n”, argv[i]);
}
Output
a.out one two three
a.out
one
two
three
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
#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
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’.
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()
{
swap(&a,&b);
Output
Before swapping: a=10 b=20
After swapping: a=20 b=10
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.
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
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
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.
Here units symbolizes int and marks symbolizes float. The declaration of variables now
can be modified as follows,
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.
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.
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 ;
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
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
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,
Structure is a powerful concept that helps to organize the complex data in a meaningful
way in the program.
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.
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
struct structure_name
{
data_type member_name1;
data_type member_name2;
....
....
}variable1, varaible2, ...;
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:
pages – integer
price - float
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
main()
{
struct
{
int weight;
float height;
} student = {60, 160.78};
……
110
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C
……
}
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);
…..
…..
}
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.
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
book1.title == book2.title
book1.price != book2.price
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
Whatever be the elements of a structure, they are always stored in contiguous memory
locations. The following program would illustrate this.
Output
Address of name = 65518
Address of price = 65519
Address of pages = 65523
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;
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
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 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++)
{
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
Output
Structure Pointer
117
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C
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.
118
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C
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);
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
In functions, structure data type can be passed as an argument. The syntax is given as,
Function_name(structure variable_name);
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;
};
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;
}
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("\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
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.
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;
// Initialization
ob2.link = NULL;
ob2.data1 = 30;
123
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C
ob2.data2 = 40;
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.
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;
}
125
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C
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
126
Department of Computer Science and Engineering-BIHER
Chennai,India.
Structured Programming Using C
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.
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
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
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
129
Department of Computer Science and Engineering-BIHER
Chennai,India.