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

Data Structures Using C 22cse13 Module Notes Final

The document provides information about a course on data structures using C programming. It includes the course code, credits, course outcomes, modules, and textbooks. The key points are: - The course code is 22CSE13/23, it is worth 2 credits, and the course outcomes include understanding arrays, functions, pointers, structures, unions, stacks, queues, and linear data structures. - The course contains 5 modules that cover programming essentials, arrays and functions, pointers structures and unions, stacks, and queues. - Three textbooks are recommended for the course on C programming, data structures, and data structures using C.

Uploaded by

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

Data Structures Using C 22cse13 Module Notes Final

The document provides information about a course on data structures using C programming. It includes the course code, credits, course outcomes, modules, and textbooks. The key points are: - The course code is 22CSE13/23, it is worth 2 credits, and the course outcomes include understanding arrays, functions, pointers, structures, unions, stacks, queues, and linear data structures. - The course contains 5 modules that cover programming essentials, arrays and functions, pointers structures and unions, stacks, and queues. - Three textbooks are recommended for the course on C programming, data structures, and data structures using C.

Uploaded by

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

NOTES FOR DATA STRUCTURES USING C

Course Code - 22CSE13

Compiled By,

Dept. of CSE
Dept. of ISE
Dept. of AIML
DATA STRUCTURES USING C
Course Code : 22CSE13/23 Credits: 02
L:T:P:S : 2:0:0:0 CIE Marks : 50
Exam Hours :3 SEE Marks : 50

Course Outcomes: At the end of the course, the student will be able to

CO # COURSE
OUTCOMES
22CSE13.1/23.1 Understand the essentials of programming constructs

22CSE13.2/23.2 Apply the concepts of array and functions

22CSE13.3/23.3 Apply the concepts of pointers, structure and union

22CSE13.4/23.4 Analyze the operations of stack data structure

22CSE13.5/23.5 Analyze the operations of queue data structure

22CSE13.6/23.6 Investigate on the applications of linear data structures

Course Outcomes to Program Outcomes Articulation Matrix:

PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2
22CSE13.1/23.1 3 3 - - - - - - - - - 3 3 3
22CSE13.2/23.2 3 3 - - 3 - - - 2 - - 3 3 3
22CSE13.3/23.3 3 3 - - 3 - - - 2 - - 3 3 3
22CSE13.4/23.4 3 - 2 2 3 - - - 2 - - 3 3 3
22CSE13.5/23.5 3 3 - - 3 - - - - - - 3 3 3
22CSE13.6/23.6 3 3 2 2 - - - - - - - - 3 3
Correlation levels: 1-Slight (Low) 2-Moderate (Medium) 3-Substantial (High)
Module Module Contents Hours Cos
No

Programming Essentials: Structure of a Program, Data Types,


1 Operators and Expressions, Managing Input and Output 6 22CSE13.1/23.1
operations, Decision Making, Branching and Looping
statements.
Arrays and Functions: Array – Definition, Initialization,
2 Declaration, One-dimensional String operations. 7 22CSE13.2/23.2

Functions: Definition, Built-in and User-defined functions.


Pointers, Structure and Union: Pointers – Definition,
3 Initialization, Pointer arithmetic’s, Parameter passing methods 7 22CSE13.3/23.3

- Call by value and Call by reference, Structure and Union.


Stack Data Structure: Definition, Representation and Working
of Stack in Data Structures, Basic operations on stack: Push (), 22CSE13.4/23.4,
4 Pop (), Peek (), isfull (), isempty (), Implementation of stack 5 22CSE13.6/23.6

using Arrays.
Applications of Stack: Recursion, Fibonacci series.
Queue Data Structure: Definition, Representation, Primitive
22CSE13.5/23.5,
5 operations on Linear Queue, Array representation of queues, 5 22CSE13.6/23.6
Case studies on Queue data structure.

Text Books:
1. C Programming - Learn to Code, Sisir Kumar Jena , 2021, CRC Press, Taylor & Francis
Group, ISBN: 978-1-032-03625-0.
2. Data Structures Through – 4th Edition, Yashavant Kanetkar, BPB Publications, March 2022,
C ISBN 978-93-5551-189-
8.
3. Data Structures with C, SEYMOUR LIPSCHUTZ, Special Indian Edition, Thirteenth
reprint 2015, McGraw Hill Education, ISBN: 9780070701984.

Reference Books:
1. Data Structures – A Pseudocode Approach with C, Richard F Gilberg and Behrouz A
Forouzan, Second edition, Fifth Indian Reprint 2015, Cengage Learning ISBN:
9788131503140.
2. Data Structures using C, Aaron M. Tanenbaum, Yedidyah Langsam,
Moshe J Augenstein, Thirteenth Impression 2014, Pearson Education,
ISBN: 9789332549319.
Module 1
Programming Essentials: Structure of a Program, Data Types, Operators and
Expressions, Managing Input and Output operations, Decision Making, Branching
and Looping statements.

INTRODUCTION TO C

1. HISTORY OF C
 C is a general purpose, procedural, structured computer programming language developed by Dennis
Ritchie in the year 1972 at AT&T Bell Labs.
 C language was developed on UNIX and was invented to write UNIX system software.
 C is a successor of B language.
 There are different C standards: K&R C std, ANSI C, ISO C.
Characteristics of C:
 C is easy to learn.
 C is a general-purpose language.
 C is a structured and procedural language.
 It is portable.
 It can extend itself.
Advantages/Features of C Language
C language is very popular language because of the following features:
1. C is structured Programming Language
2. It is considered a high-level language because it allows the programmer to solve aproblem
without worrying about machine details.
3. It has wide variety of operators using which a program can be written easily to solve agiven
problem.
4. C is more efficient which increases the speed of execution and management ofmemory compared
to low level languages.
5. C is machine independent. The program written on one machine will work on anothermachine.
6. C can be executed on many different hardware platforms.
Applications of C:
 Operating system
 Language compilers
 Assemblers
 Text editors
 Databases

2. STRUCTURE OF ‘C’ PROGRAM

 C program consists of different sections. The structure of C program is as shown below.


 Documentation Section: It consists of a set of comment line giving the name of the program, the
author and other details. Compiler ignores these comments. There are two formats:
a) Line comments //Single line comment
b) Block comments /*Multi line comment*/
 Link Section: It provides instruction to the compiler to link functions from system library.
 Definition Section: It defines all symbolic constants.
 Global Declaration Section: The variables which are used in more than one function are called global
variables and are declared in this section.
 main( ) Section: Every ‘C’ program has one main( ) function and it contains two parts:
i. Declaration Part: Here, all the variables used are declared.
ii. Executable Part: Here, it contains at least one executable statement.
The main( ) function is enclosed within flower brackets and the statements ends with semicolon.
 Sub-program Section: It contains all the user defined functions that are called by main( ) function.
Documentation section
Link section
Definition section
Global declaration section
main( ) Section
{
Declaration part
Executable part
}
Sub program section
Function 1
Function 2
-
-
Function n

Example:

//Addition of two numbers


#include<stdio.h>
void main( )
{
int a, b, sum;
printf(“Enter two numbers\n”);
scanf(“%d%d”, &a, &b);
sum = a + b;
printf(“The sum is %d”, sum);
}

3. THE BASIC ‘C’ CHARACTERS

 A C character set defines the valid characters that can be used in a source program. The basic C character
set are:
1. Letters: Uppercase: A,B,C,….,ZLowercase:
a,b,c,…..,z
2. Digits: 0,1,2,…..,9
3. Special characters: ! , . # $ ( ) } { etc
4. White spaces: Blank space, Horizontal tab space (\t), carriage return, new line character (\n), form feed
character.

1. C – TOKENS
 It is also called as lexical unit.
 The smallest individual unit in ‘C’ program is called as C-Token.
 These are the building blocks of ‘C’ program.
 There are 6 types of ‘C’ tokens:
i. Keywords
ii. Identifiers
iii. Constants
iv. Strings
v. Operators
vi. Special symbols

i. Keywords

 Keywords are also called as reserved words.


 They already have pre-defined meaning.
 Keywords should always be written in lowercase.
 The keywords meaning can’t be changed.
 Keywords cannot be used as identifiers.
 There are 32 keywords in ‘C’ program.

auto double int struct break do


else long switch goto sizeof if
case enum register typedef default
char extern return union volatile
const float short unsigned while
continue for signed void static
ii. Identifiers

 It refers to the name of the objects.


 These are the names given to variables, functions, macros etc.
 The rules to write an identifier are as follows:
1. It must contain only alphabets (A to Z, a to z), numbers (0 to 9) and underscore ( _ ).
2. It must start with alphabet or underscore but not numeric character.
3. It should not contain any special symbols apart from underscore.
4. It should not have any space.
5. Keywords cannot be used as identifiers.
6. Identifiers are case sensitive.
7. Maximum length of an identifier is 31 characters.
 Examples:
Valid Identifiers: integer, minimum, sum_total, row1, _cpps
Invalid Identifiers: float It is a keyword.
I am It has space
123_Abc It is starting with number N1
+ n2 It contains special symbol (+)

iii. Constants
Constants are the values that doesn’t changes during the execution of a program.
Integer Constant
Numeric
Constant
Real Constant

Constant
Single Character
Constant
Character
Constant
String Constant

Figure 3: Types of Constants


 Numerical Constant

 Integer Constant: These are the numbers without decimal part.


1. Decimal: It is an integer constant consisting of numbers from 0-9. It can be preceded by + or –
2. Octal: It is an integer constant consisting of numbers from 0-7. It is preceded by o
3. Hexadecimal: It is an integer constant consisting of numbers from 0-9, A-F (A=10, B=11, C=12,
D=13, E=14, F=15). It is preceded by 0x

 Real Constant:

 These are the numbers with decimal part.


 These are also called as floating point constant.
 The floating values can be identified by the suffix ‘F’ or ‘f’
 It can be expressed in exponential form.
 Ex: 21.5, 2.15 x 102 2.15e2

 Character Constant

 Single Character Constant:


 These are the values enclosed within single quotes.
 Each character have an integer value called as ASCII (American Standard Code for Information
Interchange) A: 65, a: 97
 Printable Character: All characters are printable except backslash(\) character or escape
sequence.
 Non-Printable Character: The characters with backslash (\) are non printable. Ex: \n, \t

 String Constant:
 A group of characters together form string.
 Strings are enclosed within double quotes.
 They end with NULL character (\0).
 Ex: “CBIT”

C B I T \0

NOTE:
 Qualified Constant/ Memory Constant: These are created by using “const” qualifier. Const means that
something can only be read but not modified.
Syntax: const datatype variable_name = value;
Ex: const int a = 10;
const float pi = 3.14;

 Symbolic Constants/ Defined Constant: These are created with the help of define preprocessor
directive.
Ex: #define PT 3.142
 During processing the PI in the program will be replaced with 3.142.
 The name of constant is written in uppercase just to differentiate from the variables.

 Enumeration Constant: An enumeration is a list of constant integer values. Names in enumeration


must be distinct. The keyword used is “enum”.
Ex: enum days = {Sun, Mon, Tue, Wed, Thu, Fri, Sat}
Sun 1, Mon 2, ……., Sat 7

iv. Strings

 A group of characters together form string.


 Strings are enclosed within double quotes.
 They end with NULL character (\0).
 Ex: “CPPS”
C P P S \0

5. OPERATORS
An operator is a symbol that tells the compiler to perform specific mathematical and logical functions.The
different operators supported in ‘C’ are:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operators
6. Unary Operators Increment and Decrement
7. Ternary/ Conditional Operator
8. Special Operators
1. Arithmetic Operators: The different arithmetic operators are:

Operator Name Result Syntax Example (b=5, c=2)


+ Addition Sum a=b+c a=7
- Subtraction Difference a=b-c a=3
* Multiplication Product a=b*c a = 10
/ Division Quotient a=b/c a=2
% Modulus Remainder a=b%c a=1

2. Relational Operators: These are used to compare two quantities. The output will be either 0 (False)
or 1 (True). The different relational operators are:
Operator Name Syntax Example (b=5, c=2)
< Lesser than a=b<c a = 0 (False)
> Greater than a=b>c a = 1 (True)
<= Lesser than or Equal to a = b <= c a = 0 (False)
>= Greater than or Equal to a = b >= c a = 1 (True)
== Equal to a = b == c a = 0 (False)
!= Not equal to a = b != c a = 1 (True)

3. Logical Operators: These are used to test more than one condition and make decision. The different
logical operators are: NOT, AND, OR
 Logical NOT (!) The output is true when input is false and vice versa. It accepts only one
input.

Input Output
X !X
0 1
1 0

 Logical AND (&&) The output is true only if both inputs are true. It accepts two or more
inputs.
Input Output
X Y X && Y
0 0 0
0 1 0
1 0 0
1 1 1

 Logical OR (||) The output is true only if any of its input is true. It accepts two or more inputs.

Input Output
X Y X || Y
0 0 0
0 1 1
1 0 1
1 1 1

4. Assignment Operators: These are used to assign the result or values to a variable. The different types
of assignment operators are:

Simple Assignment a = 10
Shorthand Assignment a += 10 a = a + 10
Multiple Assignment a = b = c = 10

5. Bitwise Operators: These works on bits and performs bit by bit operations. The different types of
bitwise operators are:
i. Bitwise NOT (~)
ii. Bitwise AND (&)
iii. Bitwise OR (|)
iv. Bitwise XOR (^) Output is True when odd number of 1’s are present.
v. Bitwise left shift (<<)
vi. Bitwise right shift (>>)

 Bitwise NOT (~)

X ~X
0 1
1 0

 Bitwise AND (&), Bitwise OR (|),Bitwise XOR (^)

X Y X&Y X|Y X^Y


0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

 Bitwise Left Shift (<<) Shift specified number of bits to left side.

X 0 1 0 0 0 1 1 0
X<<2 0 0 0 1 1 0 0 0

 Bitwise Right Shift (>>) Shift specified number of bits to right side.

X 0 1 0 0 0 1 1 0
X>>2 0 0 0 1 0 0 0 1

6. Unary Operators: There are 4 types:

 Unary Plus Operator


 Unary Minus Operator
 Increment (++)
 Decrement (--)

Determines Sign

 Increment (++): It adds one to the operand.

Pre-increment Post-increment
First value of the operand is incremented First value of the operand is used for evaluation
(added) by 1 then, it is used for evaluation. then, it is incremented (added) by 1.

Ex: ++a Ex: a++

 Decrement (--): It subtracts one from the operand.


Pre-decrement Post- decrement
First value of the operand is decremented First value of the operand is used for evaluation
(subtracted) by 1 then, it is used for then, it is decremented (subtracted) by 1.
evaluation.

Ex: - -a Ex: a- -

7. Conditional Operator/ Ternary Operator (?:)

 It takes three arguments.


Expression1 ? Expression2 : Expresseion3
Where,
Expression1 Condition
Expression2 Statement followed if condition is true Expression3
Statement followed if condition is false
 Ex: large = (4 > 2) ? 4: 2 large = 4
8. Special Operator/ Special Symbols

 Comma Operator: It can be used as operator in expression and as separator in declaring


variables.
 Sizeof Operator: It is used to determine the size of variable or value in bytes.
 Address Operator: It is used to find the address of the operators.

6. EXPRESSIONS

1. It is combination of operands (variables, constants) and operators.


2. Precedence: The order in which operators are evaluated is based on the priority value.
3. Associativity: It is the parsing direction used to evaluate an expression. It can be left to right or right
to left.
4. Evaluation of expressions: Expressions are evaluated using an assignment statement.
5. Ex: variable = expression
sum = a + b
6. Following table provides the Precedence and Associativity of operators:

Operator Description Associativity Precedence(Rank)


() Function call Left to right 1
[] Array element reference
+ Unary plus
- Unary minus
++ Increment
-- Decrement
! Logical negation
~ Ones complement
* Pointer to reference
& Address Right to left 2
Sizeof Size of an object
(type) Type cast (conversion)

* Multiplication
/ Division Left to right 3
% Modulus

+ Addition Left to right 4


- Subtraction

<< Left shift Left to right 5


>> Right Shift

< Less than


<= Less than or equal to
> Greater than Left to right 6
>= Greater than or equal to

== Equality Left to right 7


|= Inequality

& Bitwise AND Left to right 8


^ Bitwise XOR Left to right 9
| Bitwise OR Left to right 10
&& Logical AND Left to right 11
|| Logical OR Left to right 12
?: Conditional expression Right to left 13
=
*= /= %=
+= -= &=
^= |= Assignment operators Right to left 14
<<= >>=

, Comma operator Left to right 15

7. DATA TYPES

1. Data type defines the types of data that is stored in a variable.


2. There are 3 types:
i. Primary/ Built-in/ Fundamental data type int, float, double, char, void
ii. Derived data type array, structure, union
iii. User defines data type enum, typedef

 Primary/ Built-in/ Fundamental data type: These are the built in data types available in C. There are5 types.
Namely:
1. Integer (int)
2. Floating point (float)
3. Character (char)
4. Double precision floating point (double)
5. Void (void)
1. Integer type:
 It is used to store whole numbers.
 The keyword int is used to declare variable of integer type.
 Int type takes 2B or 4B of storage depending on machine size.
 The classes of integer are:

Unsigned Signed
Data type Keyword Size Data type Keyword Size
Short Integer short int 1B Signed short integer signed short int 1B
Integer int 2B Signed integer signed int 2B
Long Integer long int 4B Long integer long int 4B

2. Floating point data type:


 It is used to store decimal numbers.
 The keyword float is used to declare variable of floating point data type.
 Float type takes 4B or 8B of storage depending on machine size.
 It can be expressed in fractional or exponential form.
Data type Keyword Size
Floating point float 4B
Double double 8B
Long double long double 10B

3. Double:
 It is used to store double precision floating point numbers.
 The keyword double is used to declare variable of floating point data type.
 Double type takes 8B of storage.
 Double precision is related to accuracy of data.

4. Char:
 It is used to store character type of data.
 The keyword char is used to declare variable of character type.
 Char type takes 1B of storage.
 Two types of character type data, such as Unsigned char and signed char.
 For unsigned char, syntax is
unsign char a;

5. Void:
 It is a special data type that has no value.
 It doesn’t have size.
 It is used for returning the result of function that returns nothing.

List of Escape Sequences in C

Escape Sequence Meaning

\a Alarm or Beep

\b Backspace

\f Form Feed

\n New Line

\r Carriage Return

\t Tab (Horizontal)

\v Vertical Tab

\\ Backslash

\' Single Quote

\" Double Quote


\? Question Mark

\nnn octal number

\xhh hexadecimal number

\0 Null

List of some format specifiers-

S Format
NO. Specifier Type Description

1 %d int/signed int used for I/O signed integer value

2 %c char Used for I/O character value

3 %f float Used for I/O decimal floating-point value

Used for I/O string/group


4 %s string characters

5 %ld long int Used for I/O long signed integer value

6 %u unsigned int Used for I/O unsigned integer value

7 %i unsigned int used for the I/O integer value

double,long
8 %lf double Used for I/O fractional or floating data

9 %n prints prints nothing

8. VARIABLES

1. A variable is a name given to memory location whose value changes during execution.

2. Declaration:
Syntax: datatype variable_list;
Where,
Example: int a;
Where,
datatype Any built in data type
variable_list Identifiers that specifies variable name.
int is the built in data typea is variable of type int.

3. Initialization:
Syntax: datatype variable_name = value;

Where,
Example: int a = 10;
Where,datatype Any built in data type
variable_name Identifier that specifies variable name.value The data which will be stored in variable
name.

int data type


a variable name10 value

OPERATORS :

An operator is a symbol that tells the compiler to perform certain mathematical or logical
manipulations. They form expressions.
C operators can be classified as

1. Arithmetic operators

2. Relational operators

3. Logical operators

4. Assignment operators

5. Increment or Decrement operators

6. Conditional operator

7. Bit wise operators

8. Special operators

1. ARITHMETIC OPERATORS : All basic arithmetic operators are present in C.


operator meaning

+ add

- subtract

* multiplication

/ division

% modulo division(remainder)

An arithmetic operation involving only real operands(or integer operands) is called real arithmetic(or
integer arithmetic). If a combination of arithmetic and real is called mixed mode arithmetic.
2. RELATIONAL OPERATORS : We often compare two quantities and depending on theirrelation take
certain decisions for that comparison we use relational operators.
operator meaning
< is less than

> is greater than

<= is less than or equal to

>= is greater than or equal to

== is equal to

!= is not equal to

It is the form of
ae-1 relational operator ae-2

3. LOGICAL OPERATORS : An expression of this kind which combines two or more relational expressions
is termed as a logical expressions or a compound relational expression. The operators and truth values are

op-1 op-2 op-1 && op-2 op-1 || op-2


non-zero non-zero 1 1

non-zero 0 0 1

0 non-zero 0 1

0 0 0 0

op-1 !op-1

non-zero zero

zero non-zero

5. ASSIGNMENT OPERATORS : They are used to assign the result of an expression to a variable. The
assignment operator is '='.
v op=expv is variable
op binary operatorexp expression
op= short hand assignment operator

short hand assignment operators

use of simple assignment operators use of short hand assignment operatorsa=a+1


a+=1
a=a-1 a-=1

a=a%b a%=b
6. INCREMENT AND DECREMENT OPERATORS :

++ and == are called increment and decrement operators used to add or subtract.Both are unary and
as follows
++m or m++

--m or m--

The difference between ++m and m++ is

if m=5; y=++m then it is equal to m=5;m++;y=m; if m=5;


y=m++ then it is equal to m=5;y=m;m++;
7. CONDITIONAL OPERATOR : A ternary operator pair "?:" is available in C to constructconditional
expressions of the form

exp1 ? exp2 : exp3;

It work as
if exp1 is true then exp2 else exp3

8. BIT WISE OPERATORS : C supports special operators known as bit wise operators formanipulation of
data at bit level. They are not applied to float or double.
operator meaning
& Bitwise AND
| Bitwise OR

^ Bitwise exclusive OR

<< left shift

>> right shift

~ one's complement

9. SPECIAL OPERATORS : These operators which do not fit in any of the above classification are
,(comma), sizeof, Pointer operators(& and *) and member selection operators (. and ->). Thecomma operator
is used to link related expressions together.
sizeof operator is used to know the sizeof operand.
/* programs to exhibit the use of operators */

#include<stdio.h>main()
{
int sum, mul, modu;float sub, divi;
int i,j; float l, m;
printf("Enter two integers ");
scanf("%d%d",&i,&j);
printf("Enter two real numbers");
scanf("%f%f",&l,&m);
sum=i+j;mul=i*j;
modu=i%j;sub=l-m; divi=l/m;
printf("sum is %d", sum);
printf("mul is %d", mul);
printf("Remainder is %d", modu);
printf("subtraction of float is %f", sub);
printf("division of float is %f", divi);
}

/* program to implement relational and logical */#include<stdio.h>


main()
{
int i, j, k;
printf("Enter any three numbers ");
scanf("%d%d%d", &i, &j, &k);
if((i<j)&&(j<k))
printf("k is largest");else if i<j || j>k
{

if i<j && j >k


printf("j is largest");
else
printf("j is not largest of all");
}
}

/* program to implement increment and decrement operators */#include<stdio.h>


main()
{
int i;
printf("Enter a number"); scanf("%d",
&i);
i++;
printf("after incrementing %d ", i);i--;
printf("after decrement %d", i);
}

/* program using ternary operator and assignment */


#include<stdio.h>
main()
{
int i,j,large;
printf("Enter two numbers ");
scanf("%d%d",&i,&j);
large=(i>j)?i:j;
printf("largest of two is %d",large);
}
Example Programs:

Program 1: To find area and perimeter of rectangle

Algo Flo
rith wch
m art

Step 1. [Initialize] Start

Step 2. [Input the length and breadth]


Read l, bStep 3. [Calculate area] area = l
*b
Step 4. [Calculate perimeter] peri= 2(l+b)

Step 5. [Display area and perimeter] Print


area, periStep 6. [Finished] Stop.

Prog Output
ram
#include<stdio.h> Enter length and
{ breadth2
int l, b, area, peri; 4
printf(“Enter length and The area is 8
breadth\n”); scanf(“%d%d”, The perimeter is 12
&l, &b);
area = l * b;
peri = 2 * (l + b);
printf(“The area is %d\n”,
area); printf(“The perimeter is
%d\n”, peri);
}
Program 2: To find Simple Interest

Algorit Flowchart
hm

Step 1. [Initialize] Start

Step 2. [Input the principle, time and rate] Read p,


t, rStep 3. [Calculate si] si = p * t * r / 100
Step 4. [Display si]
Print si Step 5.
[Finished] Stop.

Progra Output
m
#include<stdio.h> Enter principle, rate and time
{ 1000
float p, t, r, si; 2
printf(“Enter principle, time and 4
rate\n”); scanf(“%f%f%f”, The Simple Interest is 80
&p,&t,&r);
si = p * t * r / 100;
printf(“The Simple Interest is %f”, si);
}

Managing Input and Output Operations:

Reading a character, writing a character, formatted input- output statements, and unformatted input-output
statements.

There are two types of Input and Output statements.


1. Formatted
2. Unformatted statements

Formatted statements are printf ( ) and scanf( )printf function:


printf is a formatted output function.

The general format of an output function is

printf(format-string, var1,var2…..varn);
Where format-string gives information on how many variables to expect, what type of arguments they
are, how many columns are to be reserved for displaying them.

The printf ( ) function may sometimes display only a message and not any variable value. In the following
example:

printf(“Answers are given below”);The format-string is:


Answers are given below

In this string the symbol \n commands that the cursor should advance to the beginningof the next line. In
the following example:

printf(“Answer x= %d \n”, x);

%d specifies how the value of x is to be displayed. It indicates the x is to be displayedas a decimal integer.
The variable x is of type int. %d is called the format specifier/character group/ conversion specification and d the
conversion character. In the example:

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

The variable a is of type int and b of type float or double. % d specifies that a is to be displayed as an integer and
%f specifies that, b is to be displayed as a decimal fraction.In this example %d and %f are format
specifier/character group/conversion specifications and d, f is conversion characters.
Examples:
a= 12.3456
1. printf(“%.2f”, a) O/p is 12.34 //after decimal point only consider 2 digits.
2. printf(“%.0f”,a) O/P is 12. // after decimal point nothing will be displayed.
c=543.671
3. printf(“%6.2f”,c) O/P is 543.67 //total 6 digit and after decimal two digit will be displayed.
4. printf(“%-6.1f”,c) O/P is “543.6_” //total 6 digit, after decimal point one digit and at end one extra space will
be displayed.
b=67854
5. printf(“%4d”,b) O/P is 67854 // minimum 4 or more digits will be displayed.
6. printf(“%6d”,b) O/P is “_67854” //total 6 digits will be printed including one extra space at beginning.
7. printf(“%-6d”,b) O/P is “67854-“ //total 6 digits will be printed including one extra space at end.

Scanf functions:-

The function scanf() is used to read data into variables from the standard input,namely a keyboard. The
general format is:
scanf(“control_string”, address_list)

Where format-string/control string gives information to the computer on the type of data to be stored for the
address list.

For example, in the statement:


scanf(“%d%d”, &p,&q);

The two variables in which numbers are used to be stored are p and q. The data to bestored are integers.

Ampersand symbol is used to indicate that the address of the variable name should be found to store a value
in it.
For example:
1. scanf(“%d%f”,&a,&b);
2. scanf(“%3d”,&a);
if the input data to be assigned to a is 1234, then only 123 is stored in the memory location of a.
3. scanf(“%4f”,&b);
If b is 23.123 then 23.1 is stored in the memory(including decimal point)
Unformatted statements:
Unformatted I/O functions are used only for character data type and cannot be used for any other datatype. These
functions are used to read single input from the user at the console and it allows displaying the value at the console.
Why they are called unformatted I/O?
These functions are called unformatted I/O functions because we cannot use format specifiers in these functions and
hence, cannot format these functions according to our needs.
The following unformatted I/O functions will be discussed in this section-
1. getchar()
2. putchar()
3. gets()
4. puts()

getchar():
The getchar() function is used to read only a first single character from the keyboard whether multiple characters is
typed by the user and this function reads one character at one time until and unless the enter key is pressed. This
function is declared in stdio.h(header file)
Syntax:
Variable-name = getchar();

putchar():
The putchar() function is used to display a single character at a time by passing that character directly to it or by
passing a variable that has already stored a character. This function is declared in stdio.h(header file)
Syntax:
putchar(variable_name);

gets():
gets() function reads a group of characters or strings from the keyboard by the user and these characters get stored in
a character array. This function allows us to write space-separated texts or strings. This function is declared in
stdio.h(header file).
Syntax:
char str[length of string in number]; //Declare a char type variable of any length
gets(str);

puts():
In C programming puts() function is used to display a group of characters or strings which is already stored in a
character array. This function is declared in stdio.h(header file).
Syntax:
puts(identifier_name );

Examples:
#include<stdio.h>
void main()
{
char ch;
ch=getchar(); // input is happy
putchar(ch); //output is h
char ab[20];
gets(ab); // input is happy
puts(ab); //output is happy
}

List of some format specifiers-

S
NO. Format Specifier Type Description

1 %d int/signed int used for I/O signed integer value

2 %c char Used for I/O character value

3 %f float Used for I/O decimal floating-point value

4 %s string Used for I/O string/group of characters

5 %ld long int Used for I/O long signed integer value

6 %u unsigned int Used for I/O unsigned integer value

7 %i unsigned int used for the I/O integer value

8 %lf double Used for I/O fractional or floating data

9 %n prints prints nothing

SELECTION STATEMENTS (DECISION MAKING):

IF AND SWITCH STATEMENTS :


We have a number of situations where we may have to change the order of execution ofstatements based
on certain conditions or repeat a group of statements until certain specified conditions are met.
Simple if
The if statement is a two way decision statement and is used in conjunction with an expression. It takes
the following form
If(test expression)
If the test expression is true then the statement block after if is executed otherwise it is notexecuted

/* program for if */#include<stdio.h>


main()
{
int a,b;
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b);
if a>b
printf(“ a is greater”);
if b>a
printf(“b is greater”);

The if –else statement:

If your have another set of statement to be executed if condition is false then if-else is
Used.

/* program for if-else */


#include<stdio.h> main()
{
int a,b;
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b):
if a>b
printf(“ a is greater”)
else
printf(“b is greater”);
}

Nesting of if..else statement :

If more than one if else statement

Flow char

#include <stdio.h>

int main()

int x = 65, y = 35, z = 2;

if (x > y)

if (x > z)

{
printf("x is larger than y and z ");

printf("\n flow for the program is proper ");

return 0;
}

Output:

if else ladder
if(condition1)

statement1; else
if(condition2)
statement 2; else
if(condition n)
statement n;

else
default statement.statement-x;
The nesting of if-else depends upon the conditions with which we have to deal.

THE SWITCH STATEMENT:

If for suppose we have more than one valid choices to choose from then we can useswitch statement in
place of if statements.
switch(expression)
/* program to implement switch */
#include<stdio.h>
main()
{

int marks,index;
char grade[10];
printf(“Enter your marks”);
scanf(“%d”,&marks);
index=marks/10;
switch(index)
{
case 10 :
case 9:
case 8:
case 7:
case 6: grade=”first”;break;
case 5 : grade=”second”;break;
case 4 : grade=”third”;break;
default : grade =”fail”;break;
}
printf(“%s”,grade);

UNCONDITIONAL STATEMENTS:

Continue statement:
 continue keyword forces the next iteration to take place immediately,skipping any
instructions that may follow it.
 The continue statement can only be used inside a loop (for, do-whileand while)
and not inside a switch-case selection.
 When executed, it transfers control to the condition (the expression part) in a while
or do-while loop, and to the increment expression in afor loop.
Unlike the break statement, continue does not force the termination ofa loop, it merely
transfers control to the next iteration.

// using the continue in for structure#include


<stdio.h>
int main(void)
{
int inum;
for(inum = 1; inum <= 10; inum++)
{
// skip remaining code in loop only if iNum == 5
if(inum == 5)
continue;
printf("%d ", iNum);
}
printf("\nUsed continue to skip printing the value 5\n");
return 0;

Goto Statement:

 The goto statement is one of C unconditional jump or branching.


 When program execution encounters a goto statement, execution immediately
jumps, or branches, to the location specified by the gotostatement.
 The statement is unconditional because execution always branches when a goto
statement is came across, the branching does not dependon any condition.
 A goto statement and its target label must be located in the samefunction,
although they can be in different blocks.
 Use goto to transfer execution both into and out of loop.
 However, using goto statement strongly not recommended.
 Always use other C branching statements.
 When program execution branches with a goto statement, no record iskept of where
the execution is coming from.

Example:
#include <stdio.h>
int main () {
/* local variable definition */
int a = 10;
/* do loop execution */
LOOP:do {
if( a == 15) {
/* skip the iteration */
a = a + 1;
goto LOOP;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20 );
return 0;
}

Output:

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a:
18value of a: 19

BREAK STATEMENT:

The break statement in C programming has the following two usages −


• When a break statement is encountered inside a loop, the loop is immediately
terminatedand the program control resumes at the next statement following the
loop.
• It can be used to terminate a case in the switch statement.
If you are using nested loops, the break statement will stop the execution of the
innermostloop and start executing the next line of code after the block.
#include <stdio.h>
int main () {
int a = 10;
while( a < 20 )
{
printf("value of a: %d\n", a);a++;

if( a > 15) {


/* terminate the loop using break statement
*/break;
}
}
return 0;
}
Output:
value of a:
10value of
a: 11value
of a: 12
value of a:
13value of
a: 14value
of a: 15

LOOPING :

Some times we require a set of statements to be executed repeatedly until acondition is met.
We have two types of looping structures. One in which condition is tested beforeentering the statement
block called entry control.
The other in which condition is checked at exit called exit controlled loop.

WHILE STATEMENT :

While(test condition)

{
body of the loop
}

It is an entry controlled loop. The condition is evaluated and if it is true then body ofloop is executed.
After execution of body the condition is once again evaluated and if is true body is executed once again. This
goes on until test condition becomes false.
/* program for while */

#include<stdio.h>main()
{
int count,n;float x,y;
printf(“Enter the values of x and n”);
scanf(“%f%d”,&x,&n);y=1.0;
count=1; while(count<=n)
{
y=y*x;
count++;
}
printf(“x=%f; n=%d; x to power n = %f”,x,n,y);

// simple while loop example


#include <stdio.h>
int main(void)
{
int n = 1,sum=0;
// set the while condition
while(n <= 50)
{
sum=sum+n;
// increment n by 1, repeats
n++;
}
// a newline
printf(“sum upto 1 to 50 is =%d“,sum);
return 0;
}

while – loop example


To sum= 2^2+4^2+….. +50^2

simple while loop example


#include <stdio.h>
int main(void)
{
int n = 2;
float
sum=0.0;
// set the while condition
while(n <= 50)
{
sum=sum+pow(n,2);
// increment n by 1, repeats
n=n+2;
}
printf(“sum upto 2^2 to 50^2 is =%d“,sum);
return 0;
DO WHILE STATEMENT :

 Executes a block of statements as long as a specified condition is true at least once.


 Test the condition at the end of the loop rather than at the
beginning, asdemonstrated by the for and while loops.
 (condition) can be any valid C expression.
 When the program encounter the do-while loop, the following events occur:
 The statement(s) are executed.
 The (condition) is evaluated. If it is TRUE, execution returns to step number
1. If it is FALSE, the loop terminates and the next_statement is executed.
 This means the statement(s) in the do-while will be executed at
least once.

do

body

}while(test condition);

#include <stdio.h>main()
{
int i = 10;
do{
printf("Hello %d\n", i );i = i -1;
}while ( i > 0 );
}
Output:
Hello 10
Hello 9
Hello 8
Hello 7
Hello 6
Hello 5
Hello 4
Hello 3
Hello 2
Hello 1

THE FOR LOOP :

It is also an entry control loop that provides a more concise structure


for(initialization; test control; increment)
{

body of loop

/* program of for loop */

Program to find factorial of a given number

}
1. Write a program to print the below structure using “*”
*
* *
* * *
* * * *
#include <stdio.h>
#include <conio.h>
void main()
{
int i ,j;
for( i=1; i<=4;i++)
{ for (j=1; j<=i; j++)
{
printf(“*\t”);
}
printf(“\n”);
}
getch();
}

2. Write a program to print the below structure using “*”


* * * *
* * *
* *
*
#include<stdio.h>
#include<conio.h>
void main()
{
int i ,j;
for( i=4; i>=1;--i)
{ for (j=1; j<=i; ++j)
{
printf(“*\t”);
}
printf(“\n”);
}
getch();
}
Module 1: Programming Essentials
Q1. Identify various identifiers in the given snippet.

Output: str, i , vowels, constants


Q2. Write the output of the given code snippet.
#include <stdio.h>
void main() {
int x = 3;
int y = 6;
printf("x = %d \n", x++);
printf("y = %d \n", ++y);
printf("x = %d \n", --x);
printf("y = %d \n", y--);
printf("x = %d \n", x);
printf("y = %d \n", y);}

Output:
x=3
y=7
x=3
y=7
x=3
y=6

Q3. Find the output of the below code after performing Bitwise operators.
#include <stdio.h>
int main() {
int a = 12, b = 25;
printf("Output for Bitwise AND= %d \n", a & b); // Bitwise AND
printf("Output for Bitwise OR= %d \n", a | b); // Bitwise OR
printf("Outputfor Bitwise XOR = %d \n", a ^ b); // Bitwise XOR
return 0;}
Output:
Outputfor Bitwise AND= 8
Output for Bitwise OR= 29
Outputfor Bitwise XOR = 21

Q4. Find the output of the below code snippet.


#include <stdio.h>
int main() {
int age;
printf("Enter your age: ");
scanf("%d", &age);
// ternary operator to find if a person can vote or not
(age >= 18) ?printf("You can vote") : printf("You cannot vote");
return 0; }

Output:
Enter your age: 34
You can vote

Q5. Analyse the output of the given code.


#include <stdio.h>
int main() {
// create variables
char operator = '+';
int num1 = 8;
int num2 = 7;
// using variables in ternary operator
int result = (operator == '+') ? (num1 + num2) : (num1 - num2);
printf("%d", result);
return 0; }
Output:
15
Q6. Find the output of the given code.
#include <stdio.h>
int main()
{ /* when operand is a datatype, it returns the amount of memory that is allocated to that
data type. */
printf("%lu\n", sizeof(char));
printf("%lu\n", sizeof(int));
printf("%lu\n", sizeof(float));
printf("%lu", sizeof(double));
return 0; }
Output:
1
4
4
8
Q7. Find the output of the given code.
#include <stdio.h>
int main()
{ // When sizeof() is used with the expression, it returns size of the expression
int a = 0;
double d = 10.21;
printf("%lu", sizeof(a + d));
return 0; }
Output:
8

Q8. WAPto display if a number is negative.


#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);

// true if number is less than 0


if (number < 0) {
printf("You entered %d.\n", number);
}
printf("The if statement is easy.");
return 0; }
Output:
Case 1:
Enter an integer: -3
You entered -3.
The if statement is easy.

Case 2:
Enter an integer: 3
The if statement is easy.
Q9. WAP to check if a number is equal to 10, 50 or 100 using SWITCH statement.
#include<stdio.h>
int main(){
int number=0;
printf("enter a number:");
scanf("%d",&number);
switch(number){
case 10:
printf("number is equal to 10");
break;
case 50:
printf("number is equal to 50");
break;
case 100:
printf("number is equal to 100");
break;
default:
printf("number is not equal to 10, 50 or 100");
}
return 0; }

Output:
enter a number: 10
number is equal to 10

Q10. WAP to demonstrate switch statement to demonstrate multiple cases with unique labels.
#include <stdio.h>

int main() {

char n='C';
switch(n)
{
case 'A':
case 'B':
printf("A and B\n");
break;

case 'C':
case 'D':
printf("C and D\n");
break;

default:printf("Alphabet is greater than D\n");


break;
}
return 0; }

Output:
C and D

Q11. WAP to print sum of even natural numbers up to a certain number.


#include <stdio.h>
void main()
{
int i,n,sum=0;
printf("Input number of terms : ");
scanf("%d",&n);
printf("\nThe even numbers are :");
for(i=1;i<=n;i++)
{
printf("%d ",2*i);
sum+=2*i;
}
printf("\nThe Sum of even Natural Number upto %d terms : %d \n",n,sum);
}

Output:
Input number of terms : 5
The even numbers are :2 4 6 8 10
The Sum of even Natural Number upto 5 terms : 30

Q12. Interpret the output of the below code.


A.
#include <stdio.h>
int main()
{
int x = 4, y, z;
y = --x;
z = x--;
printf("x= %d y = %d z= %d ", x, y, z);
return 0; }
Output:
x= 2 y = 3 z= 3

B.
#include <stdio.h>
int main()
{
int a = 1, b= 3;
b = a++ + a++ + a++ + a++ + a++;
printf("a= %d \nb = %d", a,b);
return 0; }
Output:
a= 6
b = 15

C.
#include <stdio.h>
int main()
{
int x = 8, y = 10;
printf("Before Pre Increment: x= %d \n", x);
printf("At Pre Increment: x= %d \n", --x);
printf("After Pre Decrement: x= %d \n", x);
printf("\n");
printf("Before Post Increment: y= %d \n", y);
printf("At Post Increment: y= %d \n", y--);
printf("After Post Increment: y= %d \n", y);
return 0; }

Output:
Before Pre Increment: x= 8
At Pre Increment: x= 7
After Pre Decrement: x= 7

Before Post Increment: y= 10


At Post Increment: y= 10
After Post Increment: y= 9

D.
#include <stdio.h>
int main()
{
int a = 1, b = 2, c = 3, x = 10, y = 20, p = 30;
int z = (a != b) && ((c && b) || (a && x)) || ((!x) && (!y));
printf("z = %d", z);
return 0;}

Output:
z=1

E.
#include<stdio.h>
int main(){
int i=1,j=1;
for(i=1;i<=3;i++){
for(j=1;j<=3;j++){
if(i==2 && j==2){
continue;//will continue loop of j only
}
printf("%d %d\n",i,j);
}
}//end of for loop
return 0; }

Output:
11
12
13
21
23
31
32
33

Q13. WAP to print Fibonacci series upton numbers.


#include <stdio.h>
int main() {
int i, n;
// initialize first and second terms
int f1 = 0, f2 = 1;
// initialize the next term (3rd term)
int nextTerm = f1 + f2;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: %d %d ", f1, f2);
for (i = 3; i<= n; ++i) {
printf("%d ", nextTerm);
f1 = f2;
f2 = nextTerm;
nextTerm = f1 + f2;
}
return 0;}

Output:
Enter the number of terms: 7
Fibonacci Series: 0 1 1 2 3 5 8

Q14. WAP to print table of a number using goto statement.

#include <stdio.h>
int main()
{
int num,i=1;
printf("Enter the number whose table you want to print?");
scanf("%d",&num);
table:
printf("%d x %d = %d\n",num,i,num*i);
i++;
if(i<=10)
goto table;
}

Output:
Enter the number whose table you want to print?10
10 x 1 = 10
10 x 2 = 20
10 x 3 = 30
10 x 4 = 40
10 x 5 = 50
10 x 6 = 60
10 x 7 = 70
10 x 8 = 80
10 x 9 = 90
10 x 10 = 100

Q15. WAP to print absolute value of a number using goto statement.


#include <stdio.h>
#include <math.h>
int main()
{
// initialize variable whose absolute value is to be printed
int n = -11;
// if the number is already positive, print it directly
if(n>=0)
{
goto positive;
}
// to make the number positive multiply by -1
n = n*(-1);
// declare positive label
positive :
printf("The absolute value is %d", n);
return 0; }
Output:
The absolute value is 11

Q16. WAP to check if a number is palindrome using while loop.


#include<stdio.h>
int main(){
int n,r,sum = 0, temp;
printf("Enter a number: ");
scanf("%d", &n);
temp = n;
while(n>0){
r= n %10;
sum = (sum * 10) +r;
n = n/10;
}
if (temp == sum)
printf("The number is a palindrome.");
else
printf("The number is not a palindrome.");

return 0; }
Output:
Enter a number: 434
The number is a palindrome.

Q 17. WAP to get the following pattern as the output.


A.

#include <stdio.h>
void main() {
for(int i = 1; i<=5; i++)
{
for(int j = 1; j<=5; j++)
{
if(i+j<5)
printf(" ");
else
printf("*");
}
printf("\n");
}
}

B.

#include <stdio.h>

void main() {
for(int i = 1; i<=5; i++)
{
for(int j = 1; j<=i; j++)
{
printf("%d",j);
}

printf("\n");
}
}

C.

#include <stdio.h>

void main() {
for(int i = 1; i<=5; i++)
{
for(int j = 1; j<=i; j++)
{
printf("%d",i);
}

printf("\n");
}
}
Module-2
Arrays and Functions
Arrays and Functions: Array – Definition, Initialization, Declaration, One-dimensional arrays, String
operations.
Functions: Definition, Built-in and User-defined functions.
Array:
Array is a linear data structure that is a collection of similar data types. Arrays are stored in contiguous
memory locations. It is a static data structure with a fixed size. It combines data of similar types.

Declaring Arrays
Syntax:
typearrayName [ arraySize ];
Ex:
• intnum[35]; /* An integer array of 35 elements */

• char name[10]; /* An array of characters for 10 elements */

Initialization an array
However you can also initialize the array during declaration like this:
• intarr[5] = {1, 2, 3, 4 ,5};

OR
• intarr[] = {1, 2, 3, 4, 5};

Example:
int mark[5] = {19, 10, 8, 17, 9};

Types of arrays

 One-dimensional Array
 Two-dimensional Array
 Three-dimensional Array

Two dimensional and three dimensional arrays are also called multi-dimensional arrays.

One-dimensional Array
In C programming language, single dimensional arrays are used to store list of values of same datatype. In other
words, single dimensional arrays are used to store a row of values.
In single dimensional array, data is stored in linear form. Single dimensional arrays are also called as one-
dimensional arrays, Linear Arrays or simply 1-D Arrays.
Declaration of Single Dimensional Array
Syntax for declaring a single dimensional array
datatypearrayName [ size ] ;
Ex:
introllNumbers [60] ;

Examples of Array Program


Ex:1
#include<stdio.h>
void main()
{
inti;
intarr[] = {2, 3, 4}; // Compile time array initialization
for(i = 0 ; i< 3 ; i++)
{
printf("%d\t",arr[i]);
}
}
OUTPUT
234
Ex:2
// Program to find the average of n numbers using arrays
#include <stdio.h>
int main() {
int marks[10], i, n, sum = 0;
double average;
printf("Enter number of elements: ");
scanf("%d", &n);
for(i=0; i< n; ++i) {
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);
// adding integers entered by the user to the sum variable
sum += marks[i];
}
// explicitly convert sum to double
// then calculate average
average = (double) sum / n;
printf("Average = %.2lf", average);
return 0;
}
Output:
Enter number of elements: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39.60
Two dimensional Arrays
C language supports two dimensional arrays also. The simplest form of a multidimensional array is the two-
dimensional array. Both the row's and column's index begins from 0.
Arrays that we have consider up to now are one dimensional arrays, a single line of elements. Often data come
naturally in the form of a table, e.g., spreadsheet, which need a two-dimensional array. Examples:
• Lab book of multiple readings over several days
• Periodic table
• Movie ratings by multiple reviewers.
• Each row is a different reviewer
• Each column is a different movie

Two-dimensional arrays are declared as follows,


data-type array-name[row-size][column-size];
Example
int a[3][4];

Ex: 1
#include<stdio.h>
int main(){
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2D array
for(i=0;i<4;i++){
for(j=0;j<3;j++){
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
}//end of j
}//end of i
return 0;
}

Output:
arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

Ex:2

#include <stdio.h>
void main ()
{
int arr[3][3],i,j;
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
printf("Enter a[%d][%d]: ",i,j);
scanf("%d",&arr[i][j]);
}
}
printf("\n printing the elements ....\n");
for(i=0;i<3;i++)
{
printf("\n");
for (j=0;j<3;j++)
{
printf("%d\t",arr[i][j]);
}
}
}
Output

Enter a[0][0]: 56

Enter a[0][1]: 10

Enter a[0][2]: 30

Enter a[1][0]: 34

Enter a[1][1]: 21

Enter a[1][2]: 34

Enter a[2][0]: 45

Enter a[2][1]: 56

Enter a[2][2]: 78

printing the elements

56 10 30

34 21 34

45 56 78

Ex:3

#include <stdio.h>

int main()

int a[3][3], b[3][3], result[3][3];

// Taking input using nested for loop

printf("Enter elements of 1st matrix\n");

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

for (int j = 0; j < 3; ++j)

scanf("%d", &a[i][j]);

}
// Taking input using nested for loop

printf("Enter elements of 2nd matrix\n");

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

for (int j = 0; j < 3; ++j)

scanf("%d", &b[i][j]);

// adding corresponding elements of two matrices

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

for (int j = 0; j < 3; ++j)

result[i][j] = a[i][j] + b[i][j];

// Displaying the sum

printf("Sum Of Matrix:\n");

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

for (int j = 0; j < 3; ++j)

printf("%d\t", result[i][j]);

printf("\n");

return 0;

Output:

Enter elements of 1st matrix


123

456

789

Enter elements of 2nd matrix

111

111

111

Sum Of Matrix:

234

567

8 9 10

Three-dimensional array:

In three-dimensional array, there will be three dimensions. The array face [5] [10] [15] can hold 750 elements (5
* 10 * 15).

// A sample program for Array Declaration

#include <stdio.h>

int main()

intone_dim [10]; # declaration of 1D array

inttwo_dim [2][2]; #declaration of 2D array

intthree_dim [2][3][4] = {

{ {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} },

{ {13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9} }

}; #declaration of 3D array. Here the elements are also defined.return 0;

Array Operation:
Various operations that can be performed on arrays.
 Traverse − Print all the elements in the array one by one.
 Insertion − Adds an element at the given index.
 Deletion − Deletes an element at the given index.
 Search − Searches an element in the array using the given index or the value.
 Update − Updates an element at the given index.

Applications of Array Data Structure:


Below are some applications of arrays.
 Arrays are used to implement data structures like a stack, queue, etc.
 Arrays are used for matrices and other mathematical implementations.
 Arrays are used in lookup tables in computers.
 Arrays can be used for CPU scheduling.
Advantages of array data structure:
 Arrays store multiple data of similar types with the same name.
 It allows random access to elements.
 As the array is of fixed size and stored in contiguous memory locations there is no memory shortage or
overflow.
 It is helpful to store any type of data with a fixed size.
 Since the elements in the array are stored at contiguous memory locations it is easy to iterate in this data
structure and unit time is required to access an element if the index is known.
Disadvantages of array data structure:
 The size of the array should be known in advance.
 The array is a static data structure with a fixed size so, the size of the array cannot be modified further and
hence no modification can be done during runtime.
 Insertion and deletion operations are costly in arrays as elements are stored in contiguous memory.
 If the size of the declared array is more than the required size then, it can lead to memory wastage.
String:
String is an array of characters.
The difference between a character array and a string is the string is terminated with a special character ‘\0’
This null character indicates the end of the string.
Strings are always enclosed by double quotes. Whereas, character is enclosed by single quotes in C.
Declaration of Strings
Declaring a string is as simple as declaring a one-dimensional array. Below is the basic syntax for declaring a
string.
charstr_name[size];
In the above syntax str_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.

Example for C String:


• char string[5] = {‘I’,’S’,’E’, ‘\0’};

or
• char string[5] = “ISE”;
(or)

• char string [] = “ISE”;

Example 1:
#include <stdio.h>
int main ()
{
charstring[20] = “ISE";
printf("The string is : %s \n", string );
return 0;}
Example 2:
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
String Operations:
String functions Description

strcat ( ) Concatenates str2 at the end of str1

strncat ( ) Appends a portion of string to another

strcpy ( ) Copies str2 into str1

Copies given number of characters of one string to


strncpy ( )
another

strlen ( ) Gives the length of str1

Returns 0 if str1 is same as str2. Returns <0 if strl<


strcmp ( )
str2. Returns >0 if str1 > str2

Strrev() Reverse the string

strlen( ) Function :
strlen( ) function is used to find the length of a character string.
Example: 3
int n;
charst[20] = “Bangalore”;
n = strlen(st);
• This will return the length of the string 9 which is assigned to an integer variable n.
Example:4
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[12] = "Hello";
char str2[12] = "World";
char str3[12]; intlen ; /* copy str1 into str3 */
strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );
/* concatenates str1 and str2 */
strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );
/* total lenghth of str1 after concatenation */
len = strlen(str1);
printf("strlen(str1) : %d\n", len );
return 0;
}
OUTPUT
strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10
Example:5
#include <stdio.h>
#include <string.h>
int main()
{
charstr[40]; // declare the size of character string
printf (" \n Enter a string to be reversed: ");
scanf ("%s", str);

// use strrev() function to reverse a string


printf (" \n After the reverse of a string: %s ", strrev(str));
return 0;
}

Output
Enter a string to be reversed: MALAYALAM
After the reverse of a string: MALAYALAM
Example: 6
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main(){
charstr[20];
inti, len, temp=0;
int flag = 0;
printf("Enter a string:");
scanf("%s", str);
len = strlen(str);
for(i=0;i <len ;i++){
if(str[i] != str[len-i-1]){
temp = 1;
break;
}
}
if (temp==0) {
printf("String is a palindrome");
}
else {
printf("String is not a palindrome");
}
return 0;
}
Output
Enter a String:Madam
String is a Palindrome.
Functions:
In C, we can divide a large program into the basic building blocks known as function.
The function contains the set of programming statements enclosed by {}.
A function can be called multiple times to provide reusability and modularity to the C program.
The function is also known as procedure or subroutine
Need of Functions in C Programming:
We need functions in C programming and even in other programming languages due to the numerous advantages
they provide to the developer. Some of the key benefits of using functions are:

 Enables reusability and reduces redundancy

 Makes a code modular

 Provides abstraction functionality

 The program becomes easy to understand and manage

 Breaks an extensive program into smaller and simpler pieces

Advantage of functions in C:
• The function provides modularity.

• The function offers reusable code

• By using functions, we can avoid rewriting same logic/code again and again in a program.

• We can call C functions any number of times in a program and from any place in a program.

• We can track a large C program easily when it is divided into multiple functions.

• Reusability is the main achievement of C functions.

• However, Function calling is always a overhead in a C program.

There are three aspects of a C function.

o Function declaration A function must be declared globally in a c program to tell the compiler about the
function name, function parameters, and return type.
o Function call Function can be called from anywhere in the program. The parameter list must not differ in
function calling and function declaration. We must pass the same number of functions as it is declared in
the function declaration.
o Function definition It contains the actual statements which are to be executed. It is the most important
aspect to which the control comes when the function is called. Here, we must notice that only one value
can be returned from the function.

Syntax
• Function declaration

return_typefunction_name (argument list);


• Function call

function_name (argument_list)
• Function definition

return_typefunction_name (argument list)


{
function body;
}
 Return Type − A function may return a value. The return_type is the data type of the value the function
returns. Some functions perform the desired operations without returning a value. In this case, the
return_type is the keyword void.
 Function Name − This is the actual name of the function. The function name and the parameter list
together constitute the function signature.
 Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the
parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type,
order, and number of the parameters of a function. Parameters are optional; that is, a function may contain
no parameters.
 Function Body − The function body contains a collection of statements that define what the function
does.

Example:1

#include <stdio.h>

// Function declaration

intmax_Num(inti, int j){

// Function definition

if (i> j)

returni;

else

return j;

// The main function.

int main(void){

int x = 15, y = 20;

// Calling the function to find the greater number among the two

int m = max_Num(x, y);

printf("The bigger number is %d", m);

return 0;

}
Output:

The bigger number is:20

Types of Functions
There are two types of functions in C programming:
• Built in or Library Functions

• User-defined functions

Built in or Library Functions: are the functions which are declared in the C header files.
Library functions are the inbuilt function in C that are grouped and placed at a common place called the library.
Such functions are used to perform some specific operations. For example, printf is a library function used to
print on the console. The library functions are created by the designers of compilers. All C standard library
functions are defined inside the different header files saved with the extension .h.
We need to include these header files in our program to make use of the library functions defined in such header
files.
For example, To use the library functions such as printf/scanf we need to include stdio.h in our program which is
a header file that contains all the library functions regarding standard input/output.
SN Header Description
file

1 stdio.h This is a standard input/output header file. It contains all the library functions regarding
standard input/output.

2 conio.h This is a console input/output header file.

3 string.h It contains all string related library functions like gets(), puts(),etc.

4 stdlib.h This header file contains all the general library functions like malloc(), calloc(), exit(), etc.

5 math.h This header file contains all the math operations related functions like sqrt(), pow(), etc.

6 time.h This header file contains all the time-related functions.

7 ctype.h This header file contains all character handling functions.

Example 2:
int main() {
printf("Hello World!");
return 0;
}
Example 3:
 sqrt() function is available in math.h library and its usage is −
 printf ( ) present in stdio.h library.
 clrscr ( ) present in conio.h library.

#include<stdio.h>
#include<conio.h>
#include<math.h>
main ( ){
intx,y;
clrscr ( );
printf ("enter a positive number");
scanf (" %d", &x)
y = sqrt(x);
printf("squareroot = %d", y);
getch();
}
Output
Enter a positive number 25
Squareroot = 5
Example 3:
Cbrt(x) :cube root of x
Log(x) : natural logarithm of x base e
Ceils(x): round x to smaller integer not less than x
Pow(x,y): x raised to power y

Example 4:
#include<stdio.h>
#include<math.h>
main ( ){
intx,y,z,n,k,p,r,q;
printf ("enter x and n values:");
scanf (" %d%d", &x,&y)
y=cbrt(x);
z=exp(x);
k=log(x);
p=ceil(x);
q=pow(x,r);
printf("cuberoot = %d", y);
printf("exponent value = %d",z);
printf("logarithmic value = %d", k);
printf("ceil value = %d", p);
printf("power = %d", q);
getch();
}
Output
enter x and n values:9 2
cuberoot = 2
exponent value = 8103
logarithmic value = 2
ceil value = 9
power = 81

User-defined functions:
User defined functions are the functions which are created by the C programmer, so that he/she can use it
many times.
Different aspects of function calling:
• A function may or may not accept any argument. It may or may not return any value. Based on these
facts,

There are four different aspects of function calls.


• function without arguments and without return value

• function without arguments and with return value

• function with arguments and without return value

• function with arguments and with return value

Example for Function without argument and return value


#include<stdio.h>
void printName();
void main ()
{
printf("Hello ");
printName();
}
void printName()
{
printf(“NHCE");
}
OUTPUT: Hello
NHCE
Example program for Function without argument and with return value
#include<stdio.h>
int sum();
void main()
{
int result;
printf("\nGoing to calculate the sum of two numbers:");
result = sum();
printf("%d",result);
}
int sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
}
Output
Going to calculate the sum of two numbers:
Enter two numbers
10 24
The sum is 34
Example for Function with argument and without return value:
#include<stdio.h>
void sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int a, int b)
{
printf("\nThe sum is %d",a+b);
}
Output
Going to calculate the sum of two numbers:
Enter two numbers 10 24
The sum is 34
Example for Function with argument and with return value:
#include<stdio.h>
int even_odd(int);
void main()
{
int n,flag=0;
printf("\nGoing to check whether a number is even or odd");
printf("\nEnter the number: ");
scanf("%d",&n);
flag = even_odd(n);
if(flag == 0)
{
printf("\nThe number is odd");
}
else
{
printf("\nThe number is even");
}
}
int even_odd(int n)
{
if(n%2 == 0)
{
return 1;
}
else
{
return 0;
}
}
Output
Going to check whether a number is even or odd
Enter the number: 100
The number is even
Module 2: Arrays and Functions

Q1. WAP to take 5 values from the user and then print it.
#include <stdio.h>

void main() {
int arr[5];

printf("Enter 5 values");

for(int i = 0; i<5; i++)


{
scanf("%d", &arr[i]);
}

printf("Displaying the elements of the array: ");


for(int i = 0; i<5; i++)
{
printf("%d\n", arr[i]);
}
}

Output:
Enter 5 values4
2
8
5
7
Displaying the elements of the array: 4
2
8
5
7

Q2. WAP to print an array in reverse order.

#include <stdio.h>

int main()
{
int arr[6] ;

printf("Enter 6 values");

for(int i = 0; i<=5; i++)


{
scanf("%d", &arr[i]);
}

printf("Displaying the elements of the array in reverse order: ");


for(int i = 5; i>= 0 ; i--)
{
printf("%d ", arr[i]);
}

return 0;
}

Output:
Enter 5 values2
4
6
8
12
23
Displaying the elements of the array in reverse order: 23 12 8 6 4 2

Q3. WAP to find the largest element in an array.

#include <stdio.h>

int main()
{

int arr[10] = {1, 2, 3, 4, 5, 0};

int i, largest;

largest = arr[0];

for(int i = 0; i<10; i++)


{
if(largest <arr[i])
largest = arr[i];
}

printf("Largest elements of the array : %d", largest);


return 0; }

Output:
Largest elements of the array : 5

Q4. WAP to find the maximum and the minimum element in an array.

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

int main() {
int a[1000],i,n,min,max;
printf("Enter size of the array : ");
scanf("%d",&n);

printf("Enter elements in array : ");


for(i=0; i<n; i++)
{
scanf("%d",&a[i]);
}

min=max=a[0];
for(i=1; i<n; i++)
{
if(min>a[i])
min=a[i];
if(max<a[i])
max=a[i];
}
printf("minimum of array is : %d",min);
printf("\nmaximum of array is : %d",max);

return 0;}

Output:
Enter size of the array : 5
Enter elements in array : 12
7
34
9
3
minimum of array is : 3
maximum of array is : 34

Q5. WAP to find the average of n numbers using array.

#include <stdio.h>

int main() {

int marks[10], i, n, sum = 0;


double average;

printf("Enter number of elements: ");


scanf("%d", &n);

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


printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);
sum += marks[i];
}
average =sum / n;

printf("Average = %.2lf", average);

return 0; }

Output:
Enter number of elements: 4
Enter number1: 21
Enter number2: 11
Enter number3: 43
Enter number4: 12
Average = 21.00

Q6. WAP to separate odd and even integers in separate arrays.

#include <stdio.h>

void main()
{
int arr1[10], arr2[10], arr3[10];
int i,j=0,k=0,n;

printf("Input the number of elements to be stored in the array :");


scanf("%d",&n);

printf("Input %d elements in the array :\n",n);


for(i=0;i<n;i++)
{
printf("element - %d : ",i);
scanf("%d",&arr1[i]);
}

for(i=0;i<n;i++)
{
if (arr1[i]%2 == 0)
{
arr2[j] = arr1[i];
j++;
}
else
{
arr3[k] = arr1[i];
k++;
}
}

if(j != 0) {
printf("\nThe Even elements are : \n");
for(i=0;i<j;i++)
{
printf("%d ",arr2[i]);
}
}

else
printf("\nNo Even elements.");

if(k != 0)
{ printf("\nThe Odd elements are :\n");
for(i=0;i<k;i++)
{
printf("%d ", arr3[i]);
}

}
else
printf("\nNo Odd elements.");

Output:
Input 4 elements in the array :
element - 0 : 22
element - 1 : 44
element - 2 : 77
element - 3 : 66

The Even elements are :


22 44 66
The Odd elements are :
77

Q7. Find the output of the given code.


#include<stdio.h>
#include<string.h>
int main(){
char str1[20] = "before ";
char str2[20] = "after";
strcat(str1, str2);
puts(str1);

char src[50];
char dest[50];

strcpy(src,"This is source");
strcpy(dest, "This is destination");
strncpy(dest, src, 10);

printf("Final destination string |%s| ", dest);


return 0;
}

Output:
before after
Final destination string |This is sostination|

Q 8. Find the output of the given code.


#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "abCd", str2[] = "aBCd", str3[] = "abcd", str4[] = "abcd";
int result;

// comparing strings str1 and str2


result = strcmp(str1, str2);
printf("strcmp(str1, str2) = %d\n", result);

// comparing strings str1 and str3


result = strcmp(str1, str3);
printf("strcmp(str1, str3) = %d\n", result);

// comparing strings str3 and str4


result = strcmp(str3, str4);
printf("strcmp(str3, str4) = %d\n", result);

return 0; }

Output:
strcmp(str1, str2) = 32
strcmp(str1, str3) = -32
strcmp(str3, str4) = 0

Q9. WAP to print numbers in words using function without arguments and without return value.
#include <stdio.h>
void printNumbers();
void main() {
printf("\nHello");
printNumbers();
}
void printNumbers(){
printf("\nOne");
printf("\nTwo");
printf("\nThree");
}

Output:
Hello
One
Two
Three

Q10. WAP to perform division using function without arguments and without return value.
#include <stdio.h>
void division();
void main() {
printf("Division of two numbers");
division();
}
void division(){
int a, b;
float c;
printf("\n Enter two numbers");
scanf("%d %d", &a, &b);
if(b != 0){
c= a/b;
printf("Ans = %f", c);
}
else
printf("Enter non zero denominator"); }

Output:
Division of two numbers
Enter two numbers12 0
Enter non zero denominator

Q11. WAP to find sum of n numbers using function without arguments and withreturn value.
#include <stdio.h>
int sum_of_numbers();
void main() {
int ans = sum_of_numbers();
printf("Sum of numbers: %d", ans);
}

int sum_of_numbers(){
int sum = 0; int n;
printf("\nEnter a number ");
scanf("%d", &n);

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


sum += i;
return sum; }

Output:
Enter a number 10
Sum of numbers: 55

Q12. WAP to find sum of n numbers using function with arguments and without return value.

#include <stdio.h>
void sum_of_numbers(int, int);
void main() {
int a, b;
printf("\nEnter first number: ");
scanf("%d", &a);
printf("\nEnter second number: ");
scanf("%d", &b);
sum_of_numbers(a,b); }

void sum_of_numbers(int x, int y){


printf("\nSum of numbers: %d", x + y);
}
Output:
Enter first number: 23

Enter second number: 76

Sum of numbers: 99

Q13. WAP to find sum of n numbers using function with arguments and withreturn value.
#include <stdio.h>
int addition(int, int, int);
void main() {
int a, b, c;
printf("\nEnter first number: ");
scanf("%d", &a);

printf("\nEnter second number: ");


scanf("%d", &b);

printf("\nEnter third number: ");


scanf("%d", &c);

int res = addition(a,b,c);

printf("\nSum of numbers: %d", res);


}

int addition(int x, int y, int z){


return ( x + y + z); }

Output:
Enter first number: 21
Enter second number: 66
Enter third number: 90
Sum of numbers: 177
MODULE -3
Pointers, Structure and Union

SYLLABUS:
Pointers,Structure and Union: Pointers– Definition, Initialization, Pointer arithmetic’s, Parameter
passing methods-Call by value and Call by reference, Structure and Union
Pointers - Concept
Consider the following statement
int Quantity =50;
- Compiler will allocate a memory location for Quantity and places the value in that location. Suppose the
address of that location is 5000, then

 During Execution of the program, the system always associates the name quantity with the address 5000.
 We may have access to the value 50 by using either the name of the variable quantity or the address
5000.
 Since memory addresses are simply numbers, they can be assigned to some variables which can be stored
in memory, like any other variable.
 A memory location or a variable which stores the address of another variable in memory
 Commonly used in C than in many other languages (such as BASIC, Pascal, and certainly Java, which has
no pointers).

Declaring and initializing pointers


Syntax:
data_type * pt_name;
This tells the compiler 3 things about the pt_name:
 The asterisk(*) tells the variable pt_name is a pointer variable.
 pt_name needs a memory location.
 pt_name points to a variable of type data_ type

Example:
int *p; //declares a variable p as a pointer variable
that points to an integer data type.
float *x; //declares x as a pointer to floating point
variable.
Once a pointer variable has been declared, it can be made to point to a variable using an assignment statement :
int quantity = 10;
p = &quantity; // p now contains the address of quantity. This is known as pointer initialization.
Accessing the address of a variable
int Quantity=50 ;
To assign the address 5000 (the location of quantity) to a variable p, we can write:
int *p = &Quantity ;
Such variables that hold memory addresses are called s
Pointer Variables.

The Address-of Operator &


This operator is used to find the address occupied by a variable
Program to illustrate the address of operator
#include <stdio.h>
int main()
{
int var1 = 11;
int var2 = 22;
int var3 = 33;
//print the addresses of these variables
printf(“%x”,&var1);
printf(“%x”,&var2);
printf(“%x”,&var3);
return 0;
}

Output:
0x29feec
0x29fee8
0x29fee4

Accessing variable through a pointer


• A variable’s value can be accessed by its pointer using unary operator *(asterisk) known as indirection
operator.
Consider the following statements:
int quantity, *p, n; // 2 int variables & 1 integer pointer
quantity =50; // assigns value 50 to quantity
p=&quantity; // assigns the address of quantity to p
n=*p; // contains the indirection operator *

* Operator - value at address operator


Example – Accessing variable through a pointer
#include <stdio.h>
int main()
{
int var1 = 11; //two integer variables
int var2 = 22;
int *ptr; //pointer to integer Output :
ptr = &var1; //pointer points to var1 11
printf(“%d”,*ptr); //print contents of pointer (11) 22

ptr = &var2; //pointer points to var2


printf(“%d”,*ptr); //print contents of pointer (22)
return 0;
}

Example - Accessing via pointers.


#include <stdio.h>
int main()
{
int var1, var2; //two integer variables
int *ptr; //pointer to integers
ptr = &var1; //set pointer to address of var1
*ptr = 37; //same as var1=37 ( Dereferencing)
var2 = *ptr; //same as var2=var1
printf(“%d”, var2); //verify var2 is 37
return 0;
}
Reference and dereference operators
 &is the ‘reference’ operator and can be read as "address of"
 * is the ‘dereference’ operator and can be read as “value at address” or "value pointed by"
Example- understanding pointers
#include <iostream>
using namespace std;
int main()
{
int firstvalue = 5, secondvalue = 15;
int * p1, * p2;
p1 = &firstvalue; // p1 = address of firstvalue Output :
p2 = &secondvalue; // p2 = address of secondvalue firstvalue is 10
*p1 = 10; // value pointed by p1 = 10 secondvalue is 20
*p2 = *p1; // value pointed by p2 = value pointed by p1
p1 = p2; // p1 = p2 (value of pointer is copied)
*p1 = 20; // value pointed by p1 = 20
Printf(“firstvalue is %d”, firstvalue);
Printf(“secondvalue is %d”, secondvalue);
return 0;
}

Pointer Arithmetic in C
 We can perform arithmetic operations on the pointers like addition, subtraction, etc.
 However, as we know that pointer contains the address, the result of an arithmetic operation performed
on the pointer will also be a pointer if the other operand is of type integer. In pointer-from-pointer
subtraction, the result will be an integer value. Following arithmetic operations are possible on the pointer
in C language:
 Increment
 Decrement
 Addition
 Subtraction
 Comparison

Incrementing Pointer in C
 If we increment a pointer by 1, the pointer will start pointing to the immediate next location. This is
somewhat different from the general arithmetic since the value of the pointer will get increased by the size
of the data type to which the pointer is pointing.
 We can traverse an array by using the increment operation on a pointer which will keep pointing to every
element of the array, perform some operation on that, and update itself in a loop.
The Rule to increment the pointer is given below:
new_address= current_address + i * size_of(data type)

Where i is the number by which the pointer get increased.


32-bit
For 32-bit int variable, it will be incremented by 2 bytes.
64-bit
For 64-bit int variable, it will be incremented by 4 bytes.
Let's see the example of incrementing pointer variable on 64-bit architecture.

#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p+1;
printf("After increment: Address of p variable is %u \n",p);
// in our case, p will get incremented by 4 bytes.
return 0;
}
OUTPUT:
Address of p variable is 3214864300
After increment: Address of p variable is 3214864304

Decrementing Pointer in C
Like increment, we can decrement a pointer variable. If we decrement a pointer, it will start pointing to
the previous location. The formula of decrementing the pointer is given below:
new_address= current_address - i * size_of(data type)
32-bit
For 32-bit int variable, it will be decremented by 2 bytes.
64-bit
For 64-bit int variable, it will be decremented by 4 bytes.
Let's see the example of decrementing pointer variable on 64-bit OS.

#include <stdio.h>
void main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p-1;
printf("After decrement: Address of p variable is %u \n",p); // P will now point to the immidiate previous location
.
}
OUTPUT:
Address of p variable is 3214864300
After decrement: Address of p variable is 3214864296

C Pointer Addition
We can add a value to the pointer variable. The formula of adding value to pointer is given below:
new_address= current_address + (number * size_of(data type))
32-bit
For 32-bit int variable, it will add 2 * number.
64-bit
For 64-bit int variable, it will add 4 * number.
Let's see the example of adding value to pointer variable on 64-bit architecture.

#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p+3; //adding 3 to pointer variable
printf("After adding 3: Address of p variable is %u \n",p);
return 0;
}
OUTPUT:
Address of p variable is 3214864300
After adding 3: Address of p variable is 3214864312
NOTE:
As you can see, the address of p is 3214864300. But after adding 3 with p variable, it is 3214864312, i.e., 4*3=12
increment. Since we are using 64-bit architecture, it increments 12. But if we were using 32-bit architecture, it
was incrementing to 6 only, i.e., 2*3=6. As integer value occupies 2-byte memory in 32-bit OS.

C Pointer Subtraction
Like pointer addition, we can subtract a value from the pointer variable. Subtracting any number from a
pointer will give an address. The formula of subtracting value from the pointer variable is given below:
new_address= current_address - (number * size_of(data type))
32-bit
For 32-bit int variable, it will subtract 2 * number.
64-bit
For 64-bit int variable, it will subtract 4 * number.
Let's see the example of subtracting value from the pointer variable on 64-bit architecture.
#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p-3; //subtracting 3 from pointer variable
printf("After subtracting 3: Address of p variable is %u \n",p);
return 0;
}
OUTPUT:
Address of p variable is 3214864300
After subtracting 3: Address of p variable is 3214864288

Pointer Comparisons
 Pointers may be compared by using relational operators, such as ==, <, and >. If p1 and p2 point to
variables that are related to each other, such as elements of the same array, then p1 and p2 can be
meaningfully compared.
 The following program modifies the previous example − one by incrementing the variable pointer so long
as the address to which it points is either less than or equal to the address of the last element of the array,
which is &var[MAX - 1] −

Parameter passing techniques


 Pass by value (call by value)
 Pass by reference (call by reference)

Pass by value:
void swap(int x, int y )
{
int t=x;
x=y;
y=t;
printf(“In fn: x= %d and y=%d “,x,y);
}
int main() Output:
{
int a=5,b=7; In fn: x = 7 & y = 5
swap(a, b);
printf(“After swap: a= %d and b= %d“,a,b);
After swap: a = 5 & b =
return 0;
7
}
Structures& Unions
 We’ve seen variables of simple data types, such as float, char, and int.
 We saw derived data type, arrays to store group of related data.
 Variables of such types represent one item of information: a height, an amount, a count, or group of item
with same data type: list[10] and so on.
 But, these basic types does not support the storage of compound data.
Eg. Student {name, address, age, sem, branch}
 C provides facility to define one’s own type (user-defined) that may be a composite of basic types
(int,char,double, etc) and other user-defined types.
 Structures
 Definition:
 collection of one or more variables, possibly of different types, grouped together under a single
name for convenient handling
 A structure type in C is called struct.
 Structures hold data that belong together.
 Examples:
 Student record: student id, name, branch, gender, start year, …
 Bank account: account number, name, address, balance, …
 Address book: name, address, telephone number, …
 In database applications, structures are called records.
 A struct is heterogeneous, that means it can be composed of data of different types.
 In contrast, array is homogeneous since it can contain only data of the same type.
 The general format of a structure definition
struct structure_name
{
data_type member1;
data_type member2;

};
Structure Definition – Examples

• Example:
struct Date
{
int day;
int month;
int year;
};

struct example

• Examples:
i) struct StudentInfo{
int Id;
int age;
char Gender;
float CGA;
};

ii) struct Employee{


char Name[15];
char Address[30];
int Age;
float Basic;
float DA;
float NetSalary;
};

Declaring Structure Variables


• Declaration of a variable of struct type using struct tag name, after structure definition:
<struct-type><identifier_list>;
• Example:
StudentInfoStudent1, Student2;
Student1 and Student2 are variables of StudentInfo type.

Declare them at the time of structure definition:


structstudent
{
introllno;
int age;
charname[10];
floatheight;
}s1, s2, s3; /* Defines 3 variables of type student */

Member or dot operator


 The link between member and a structure variable is established using the member operator ‘.’ which is
also known as ‘dot operator’
<struct-variable>.<member_name>
e.g.: student s1; // s1 is a variable of typeof student structure.
s1. rollno;
s1. age;
s1. name;

Assigning values to members


Different ways to assign values to the members of a structure:
Assigning string:
strcpy(s1.name, “Rama”);
Assignment statement:
s1.rollno = 1335;
s1.age = 18;
s1.height = 5.8;
Reading the values into members:
scanf(“%s %d %d %f”, s1.name, &s1.age, &s1.rollno, &s1.height);

Structure: Example -complete program:


struct Book { // definition
char title[20];
char author[15];
int pages;
float price;
};
int main( ){
struct Book b1;
printf(“Input values”);
scanf(“%s %s %d %f”, b1.title, b1.author, &b1.pages,
&b1.price);
//output
printf(“%s %s %d %f”, b1.title, b1.author, b1.pages,
b1.price);
return 0;
}

Union
Union can be defined as a user-defined data type which is a collection of different variables of different
data types in the same memory location. The union can also be defined as many members, but only one
member can contain a value at a particular point in time.
Union is a user-defined data type, but unlike structures, they share the same memory location.
Let's understand this through an example.
struct abc
{
int a;
char b;
}
The above code is the user-defined structure that consists of two members, i.e., 'a' of type int and 'b' of
type character. When we check the addresses of 'a' and 'b', we found that their addresses are different.
Therefore, we conclude that the members in the structure do not share the same memory location.
 When we define the union, then we found that union is defined in the same way as the structure is defined
but the difference is that union keyword is used for defining the union data type, whereas the struct
keyword is used for defining the structure.
 The union contains the data members, i.e., 'a' and 'b', when we check the addresses of both the variables
then we found that both have the same addresses. It means that the union members share the same
memory location.
union abc
{
int a;
char b;
}var;
int main()
{
var.a = 66;
printf("\n a = %d", var.a);
printf("\n b = %d", var.b);
}
In the above code, union has two members, i.e., 'a' and 'b'. The 'var' is a variable of union abc type. In
the main() method, we assign the 66 to 'a' variable, so var.a will print 66 on the screen. Since both 'a' and 'b'
share the memory location, var.b will print 'B' (ascii code of 66).
Difference between Structure & Union:
Structure Union

The struct keyword is used to define a The union keyword is used to define union.
structure.

When the variables are declared in a structure, When the variable is declared in the union, the
the compiler allocates memory to each compiler allocates memory to the largest size
variables member. The size of a structure is variable member. The size of a union is equal
equal or greater to the sum of the sizes of each to the size of its largest data member size.
data member.

Each variable member occupied a unique Variables members share the memory space of
memory space. the largest size variable.

Changing the value of a member will not Changing the value of one member will also
affect other variables members. affect other variables members.

Each variable member will be assessed at a Only one variable member will be assessed at
time. a time.

We can initialize multiple variables of a In union, only the first data member can be
structure at a time. initialized.

All variable members store some value at any Exactly only one data member stores a value
point in the program. at any particular instance in the program.
The structure allows initializing multiple Union allows initializing only one variable
variable members at once. member at once.

It is used to store different data type values. It is used for storing one at a time from
different data type values.
It allows accessing and retrieving any data It allows accessing and retrieving any one data
member at a time. member at a time.

Advantages of Structure
o Structure stores more than one data type of the same object together.
o It is helpful when you want to store data of different or similar data types such as name, address, phone,
etc., of the same object.
o It makes it very easy to maintain the entire record as we represent complete records using a single name.
o The structure allows passing a whole set of records to any function with the help of a single parameter.
o An array of structures can also be created to store multiple data of similar data types.

Disadvantages of Structure
o If the complexity of the project goes increases, it becomes hard to manage all your data members.
o Making changes to one data structure in a program makes it necessary to change at several other places.
So it becomes difficult to track all changes.
o The structure requires more storage space as it allocates memory to all the data members, and even it is
slower.
o The structure takes more storage space as it gives memory to all the different data members, whereas
union takes only the memory size required by the largest data size parameters, and the same memory is
shared with other data members.

Comparative advantages and disadvantages of union

Below is the list of some advantages and disadvantages of using union:

Advantages of Union
o Union takes less memory space as compared to the structure.
o Only the largest size data member can be directly accessed while using a union.
o It is used when you want to use less (same) memory for different data members.
o It allocates memory size to all its data members to the size of its largest data member.

Disadvantages of Union
o It allows access to only one data member at a time.
o Union allocates one single common memory space to all its data members, which are shared between all
of them.
o Not all the union data members are initialized, and they are used by interchanging values at a time.
Module 3: Pointers, Structures and Union

Q1. WAP to show the basic declaration of pointers.

#include <stdio.h>
void main(void)
{
int m=10,n,o;
int *z=&m ;

printf(" Here is m=10, n and o are two integer variable and *z is an integer");
printf("\n\n z stores the address of m = %p\n", z); // z is a pointer so %p would print the address
printf("\n *z stores the value of m = %i\n", *z);
printf("\n &m is the address of m = %p\n", &m); // &m gives the address of the integer variable m
// so %p is the specifier for that address
printf("\n &n stores the address of n = %p\n", &n);
printf("\n &o stores the address of o = %p\n", &o);
printf("\n &z stores the address of z = %p\n\n", &z); // &z gives the address, where the pointer z is
// stored -> still an address -> %p is the right
// specifier
}

Output:
Here is m=10, n and o are two integer variable and *z is an integer

z stores the address of m = 0x7fff3ca835e4

*z stores the value of m = 10

&m is the address of m = 0x7fff3ca835e4

&n stores the address of n = 0x7fff3ca835e8

&o stores the address of o = 0x7fff3ca835ec

&z stores the address of z = 0x7fff3ca835f0

Q2. WAP to illustrate how to handle pointers in C.

#include <stdio.h>
int main()
{
int* ab;
int m;
m=29;
printf(" Here in the declaration ab = int pointer, int m= 29\n\n");

printf(" Address of m : %p\n",&m);


printf(" Value of m : %d\n\n",m);
ab=&m;
printf(" Now ab is assigned with the address of m.\n");
printf(" Address of pointer ab : %p\n",ab);
printf(" Content of pointer ab : %d\n\n",*ab);
m=34;
printf(" The value of m assigned to 34 now.\n");
printf(" Address of pointer ab : %p\n",ab);
printf(" Content of pointer ab : %d\n\n",*ab);
*ab=7;
printf(" The pointer variable ab is assigned the value 7 now.\n");
printf(" Address of m : %p\n",&m);//as ab contain the address of m
//so *ab changed the value of m and now m become 7
printf(" Value of m : %d\n\n",m);
return 0;
}

Output:
Here in the declaration ab = int pointer, int m= 29

Address of m : 0x7ffcb906b7ac
Value of m : 29

Now ab is assigned with the address of m.


Address of pointer ab : 0x7ffcb906b7ac
Content of pointer ab : 29

The value of m assigned to 34 now.


Address of pointer ab : 0x7ffcb906b7ac
Content of pointer ab : 34

The pointer variable ab is assigned the value 7 now.


Address of m : 0x7ffcb906b7ac
Value of m : 7

Q3. WAP to add two numbers using pointers in C.

#include <stdio.h>
long addTwoNumbers(long *, long *);

int main()
{
long fno, sno, sum;

printf(" Input the first number : ");


scanf("%ld", &fno);
printf(" Input the second number : ");
scanf("%ld", &sno);
sum = addTwoNumbers(&fno, &sno);
printf(" The sum of %ld and %ld is %ld\n\n", fno, sno, sum);
return 0;
}
long addTwoNumbers(long *n1, long *n2)
{
long sum;
sum = *n1 + *n2;
return sum;
}
Output:
Input the first number : 32
Input the second number : 56
The sum of 32 and 56 is 88

Q4. WAP to find the maximum of two numbers using pointers.

#include <stdio.h>
#include <stdlib.h>
void main()
{
int fno,sno,*ptr1=&fno,*ptr2=&sno;

printf(" Input the first number : ");


scanf("%d", ptr1);
printf(" Input the second number : ");
scanf("%d", ptr2);

if(*ptr1>*ptr2)
{
printf("\n%d is the maximum number.\n\n",*ptr1);
}
else
{
printf("\n%d is the maximum number.\n\n",*ptr2);
}
}

Output:
Input the first number : 21
Input the second number : 34

34 is the maximum number.

Q5. WAP to demonstrate increment/ decrement operations of a pointer in C.

#include <stdio.h>
#include <stdlib.h>
int main()
{

int a = 23;
int *p = &a;
printf("p = %u\n", p);

p++;
printf("p after increment: %u\n", p);

p--;
printf("p after decrement: %u\n", p);

return 0;
}

Output:
p = 2338728444
p after increment: 2338728448
p after decrement: 2338728444

Q6.WAP to demonstrate addition/subtraction operations of a pointer in C.

#include<stdio.h>
int main(){
int number=50;
int *p;
p=&number;

printf("Address of p variable is %u \n",p);


p = p + 3;
printf("After adding 3: Address of p variable is %u \n",p);

int *q;

q = &number;

printf("Address of q variable is %u \n",q);


q = q - 4;
printf("After subtracting 4: Address of q variable is %u \n",q);

return 0;
}

Output:
Address of p variable is 1728445412
After adding 3: Address of p variable is 1728445424
Address of q variable is 1728445412
After subtracting 4: Address of q variable is 1728445396

Q7. WAP to find cube of a number using pass by reference pointer in C.


#include <stdio.h>

void cube(int *a)


{
//*(asterix) is used to de-reference the variable
*a=(*a)*(*a)*(*a);
}
int main()
{
int a;
printf("Enter a number:");
scanf("%d",&a);
printf("Numbers Entered is: %d\n",a);
// Calling cube function by passing address
cube(&a);
printf("Cube of entered number is: %d",a);
return 0;
}

Output:
Enter a number:5
Numbers Entered is: 5
Cube of entered number is: 125

Q8. WAP using C Structures to display the name, Citizenship Number and Salary of an employee.
#include <stdio.h>
#include <string.h>

// create struct with person1 variable


struct Person {
char name[50];
int citNo;
float salary;
} person1;

int main() {

int c_no;
// assign value to name of person1

strcpy(person1.name, "Jim Carrie");

// assign values to other person1 variables


printf("Enter citizenship no.: ");
scanf("%d",&c_no);
person1.citNo = c_no;
person1. salary = 25000;

printf("Name: %s\n", person1.name);


printf("Citizenship No.: %d\n", person1.citNo);
printf("Salary: %.2f", person1.salary);

return 0;
}

Output:
Enter citizenship no.: 6550
Name: Jim Carrie
Citizenship No.: 6550
Salary: 25000.00

Q9.Demonstrate unionusing a C program.

#include <stdio.h>
union Job {
float salary;
int workerNo;
} s,j;
int main() {
s.salary = 12.3;

j.workerNo = 100;

printf("Salary = %.1f\n", s.salary);


printf("Number of workers = %d", j.workerNo);
return 0;
}

Output:
Salary = 12.3
Number of workers = 100

Q10. Demonstrate using a C program the difference between Structures and Unions.

#include <stdio.h>
union unionJob
{
//defining a union
char name[32];
float salary;
int workerNo;
} uJob;

struct structJob
{ //defining a struct
char name[32];
float salary;
int workerNo;
} sJob;

int main()
{
printf("size of union = %d bytes", sizeof(uJob));
printf("\nsize of structure = %d bytes", sizeof(sJob));
return 0;
}

Output:
size of union = 32 bytes
size of structure = 40 bytes
MODULE-4
STACK DATA STRUCTURE
Topics

Stack Data Structure: Definition, Representation, Working of Stack in Data Structures, Basic operations on
stack: Push(), Pull(), Peek(), isfull(), isempty(), Implementation of stack using Arrays and Pointers.
Applications of Stack: Recursion, Fibonacci series, Towers of Hanoi problem.

4.1 Stack Definition


“Stack is an ordered collection of elements or items of same type can be inserted and deleted at only one end
called Top of stack”. (OR)
STACK is an ordered-list in which insertions (called push) and deletions (called pop) are made at
one end called the top. Since last element inserted into a stack is first element removed, a stack is also known as
a LIFO list (Last In First Out). Stack can be implemented using the Linked List or Array.
Stack belongs to non-primitive linear data structure.
Consider a stack s=(a0,a1,….,an-1).here a0 is the bottom element , an-1 is the top element and generally,
element ai is on the top of element ai-1,0<i<n
4.2 Representation
Top an-1
an-2
…..
….
a1
a0
Figure 1a: Stack S
If A, B, C, D, E are the elements added into stack in that order then E is the first element to be deleted.
Figure shows insertion and deletion of elements from the stack.

Figure 1b: Insertion and deletion of elements from the stack


Thus, Stack is LIFO Structure i,e Last in First Out as shown in figure 1. Example, we can place or remove a
card or plate from top of the stack only.
Figure 2: Stack of cards and plates

Figure 3: Stack representation


Figure 2 shows the example stacks and figure 3 shows stack representation indicting LIFO operation.
EXAMPLES FOR STACKS:- a stack of coins, a stack of plates , a stack of books , a stack of flooded towels ,
phone call log, tennis balls in a container, undo and redo operations etc.

1.3 Working of Stack in Data Structures


A Stack works on the LIFO process (Last In First Out), i.e., the element that was inserted last will be
removed first. To implement the Stack, it is required to maintain a pointer to the top of the Stack, which is the
last element to be inserted because we can access the elements only on the top of the Stack.
 STACK BASIC OPERATIONS
Stack operations may involve initializing the stack, using it and then de-initializing it. Apart from these basic
stuffs, a stack is used for the following two primary operations −
 push() − pushing (storing / inserting) an element on the stack.
 pop() − removing (accessing/ deleting) an element from the stack.
When data is pushed onto stack, to use a stack efficiently we need to check status of stack as well. For the
same purpose, the following functionality is added to stacks
 peek() − get the top data element of the stack, without removing it.
 isFull() − check if stack is full or overflow.
 isEmpty() − check if stack is empty or underflow.
At all times, we maintain a pointer to the last pushed data on the stack. As this pointer always represents
the top of the stack, hence named top. The top pointer provides top value of the stack without actually removing
it.
PUSH Operation
The process of putting a new data element onto stack is known as PUSH Operation. Push operation involves
series of steps −
 Step 1 − Check if stack is full.
 Step 2 − If stack is full, produce error and exit.
 Step 3 − If stack is not full, increment top to point next empty space.
 Step 4 − Add data element to the stack location, where top is pointing.
 Step 5 − return success.
if linked-list is used to implement stack, then in step 3, we need to allocate space dynamically. Push operation is
shown in figure 5.

Figure 5: Push operation

POP Operation
Accessing the content while removing it from stack, is known as pop operation. In array implementation
of pop() operation, data element is not actually removed, instead top is decremented to a lower position in stack
to point to next value. But in linked-list implementation, pop() actually removes data element and deallocates
memory space. Pop operation is shown in figure6.
A POP operation may involve the following steps −
 Step 1 − Check if stack is empty.
 Step 2 − If stack is empty, produce error and exit.
 Step 3 − If stack is not empty, access the data element at which top is pointing.
 Step 4 − Decrease the value of top by 1.
 Step 5 − return success.
Figure 6: pop operation
IMPLEMENTATION OF STACK OPERATIONS
The easiest way to implement stack ADT is using one-dimensional array.
stack[ MAX_STACK_SIZE],where MAX_STACK_SIZE =maximum number of entries in the stack.
• The first element of the stack is stored in stack [0],stack[1] is second element and stack[i-1] is the ith element.
• ’top’ points to the top element in the stack (top=-1 to denote an empty stack).
• The CreateS() function can be implemented as follows and it creates stack of size 100.

Function push/add() checks to see if the stack is full. If it is, it calls stack_full(), which prints an error
message and terminates execution. When the stack is not full, we increment top and assign item to stack[top].

Function pop/delete() checks to see if the stack is empty using top . If top reaches -1,then it calls
stack_empty(), which prints an error message and terminates execution. When the stack is not empty, we return
the top most element stack[top] and decrement top.
void stack_full()
{ printf(stderr,”stack is full, can’t add element”);
exit(EXIT_FAILURE);
}
void stack_empty ()
{ printf(stderr,”stack is empty, can’t delete element”);
exit(EXIT_FAILURE);
}

1.5 Implementation of stack using Arrays


In stack implementation using an array, we will do all the operations of the stack data structure using an array.
The operations include:

 push(a): Adding a element at the top of the stack in O(1) time.


 pop(): Removing the top element from the stack in O(1) time.
 peak(): Accessing the top element of the stack by returning it in O(1) time.

Adding an Element Onto the Stack: Push Operation

Adding a new element at the top of the stack is known as the push operation. Push operation executes in two
steps:

Step 1: Increment the variable top (the pointer that points to the top of the stack). Now it will point to a new
memory location.

Step 2: Add the new element at the updated top, the new memory location. And increase the size of the stack.

Note: Push operation can cause stack overflow condition if we try to perform push operation on an already full
stack.

Implementation of Push Algorithm in C Language


void push (int value, int n)
{
if (top == n )
printf("\n Overflow");
else
{
top = top +1;
stack[top] = val;
}
}

In the above code, through if-else we are first checking whether the stack array is full or not. If the stack is full,
the program will print overflow. Otherwise, it will increase the top and will add a new element in that position.

Deletion of an Element From a Stack: Pop Operation

Retrieving the value while removing it from the top of the stack, is known as a pop operation. In an array
implementation of pop() operation in the stack data structure, the data element is not removed, instead, the top
pointer is decremented to a lower position in the stack to point to the next value, and simultaneously the size is
decreased.

The pop function will return this removed value.

Note: Underflow condition can occur in pop operation if we try to perform a pop operation on an empty stack.

Implementation of Pop Algorithm in C Language


int pop ()
{
if(top == -1)
{
printf("Underflow");
return 0;
}
else
{
return stack[top-- ];
}
}

In the above code, through if-else we are first checking whether the stack array is empty or not. If the stack
is empty, the program will print underflow. Otherwise, it will decrement the top and will delete the top element
from the stack.

Implementation of Peek Algorithm in C Language

int peek()
{
if (top == -1)
{
printf("Underflow");
return 0;
}
else
{
return stack [top];
}
}

In the above code, firstly we are checking whether the stack is empty or not. If the stack is empty, the program
will print underflow and will return zero. Otherwise, it will return the top element of the stack.

Complete Code of Stack Using Array in C


#include <stdio.h>

// Function declarations
void push();
void pop();
void peek();

// Taking stack array of size 50


int stack[50],i,j,option=0,n,top=-1;
void main ()
{
// Size of stack
printf("Enter the number of elements in the stack ");
scanf("%d",&n);
printf("Stack implementation using array\n");

// Taking user input for the operation to be performed


while(option != 4)
{
printf("Chose one from the below options...\n");
printf("\n1.Push\n2.Pop\n3.Peek\n4.Exit");
printf("\n Enter your option \n");
scanf("%d",&option);
switch(option)
{
case 1:
{
push();
break;
}
case 2:
{
pop();
break;
}
case 3:
{
peek();
break;
}
case 4:
{
printf("Exiting");
break;
}
default:
{
printf("Please Enter valid option");
}
};
}
}

// Push operation function


void push ()
{
int value;
if (top == n )
printf("\n Overflow");
else
{
printf("Enter the value?");
scanf("%d",&val);
top = top +1;
stack[top] = value;
}
}

// Pop operation function


void pop ()
{
if(top == -1)
printf("Underflow");
else
top = top -1;
}

// peek operation function


void peek()
{
for (i=top;i>=0;i--)
{
printf("%d\n",stack[i]);
}
if(top == -1)
{
printf("Stack is empty");
}
}
1.6 Implementation of stack using pointers
stack pointer is a small register that stores the memory address of the last data element added to the stack
or, in some cases, the first available address in the stack.
A stack is a specialized buffer that is used by a program's functions to store data such as parameters,
local variables and other function-related information. The stack pointer -- also referred to as the extended stack
pointer (ESP) -- ensures that the program always adds data to the right location in the stack.
Complete Code of Stack Using Pointers in C
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

#define MAX 50
int size;

// Defining the stack structure


struct stack {
int arr[MAX];
int top;
};

// Initializing the stack(i.e., top=-1)


void init_stk(struct stack *st) {
st->top = -1;
}

// Entering the elements into stack


void push(struct stack *st, int num) {
if (st->top == size - 1) {
printf("\nStack overflow(i.e., stack full).");
return;
}
st->top++;
st->arr[st->top] = num;
}

//Deleting an element from the stack.


int pop(struct stack *st) {
int num;
if (st->top == -1) {
printf("\nStack underflow(i.e., stack empty).");
return NULL;
}
num = st->arr[st->top];
st->top--;
return num;
}

void display(struct stack *st) {


int i;
for (i = st->top; i >= 0; i--)
printf("\n%d", st->arr[i]);
}

int main() {
int element, opt, val;
struct stack ptr;
init_stk(&ptr);
printf("\nEnter Stack Size :");
scanf("%d", &size);
while (1) {
printf("\n\ntSTACK PRIMITIVE OPERATIONS");
printf("\n1.PUSH");
printf("\n2.POP");
printf("\n3.DISPLAY");
printf("\n4.QUIT");
printf("\n");
printf("\nEnter your option : ");
scanf("%d", &opt);
switch (opt) {
case 1:
printf("\nEnter the element into stack:");
scanf("%d", &val);
push(&ptr, val);
break;
case 2:
element = pop(&ptr);
printf("\nThe element popped from stack is : %d", element);
break;
case 3:
printf("\nThe current stack elements are:");
display(&ptr);
break;
case 4:
exit(0);
default:
printf("\nEnter correct option!Try again.");
}
}
return (0);
}
1.6 Applications of Stack
 Recursion
 Fibonacci series
 Towers of Hanoi problem.

Recursion

 Recursion is implemented using stack because activation records are to be stored in LIFO order i.e. last
in first out. An activation record of a function call contains three parts: first is arguments, return address
and local variables of the function.

 Recursion has many, many applications. In this module, we'll see how to use recursion to compute the
factorial function, to determine whether a word is a palindrome, to compute powers of a number, to
draw a type of fractal, and to solve the ancient Towers of Hanoi problem.
Fibonacci series

 In computer science, the Fibonacci search technique is a method of searching a sorted array using a
divide and conquer algorithm that narrows down possible locations with the aid of Fibonacci
numbers.
 Fibonacci search divides the array into two parts that have sizes that are consecutive Fibonacci numbers.
On average, this leads to about 4% more comparisons to be executed, but it has the advantage that one
only needs addition and subtraction to calculate the indices of the accessed array elements, while classical
binary search needs bit-shift division or multiplication, operations that were less common at the time
Fibonacci search was first published. Fibonacci search has an average- and worst-case complexity
of O(log n).

OTHER APPLICATIONS OF STACKS


1. Stack is used by compilers to check for balancing of parentheses, brackets and braces.
2. Stack is used to evaluate a postfix expression.
3. Stack is used to convert an infix expression into postfix/prefix form.
4. In recursion, all intermediate arguments and return values are stored on the processor’s stack.
5. During a function call the return address and arguments are pushed onto a stack and on return they are
popped off.
C recursive function to solve tower of hanoi
#include <stdio.h>

// C recursive function to solve tower of hanoi puzzle


voidtowerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)
{
if (n == 1)
{
printf("\n Move disk 1 from rod %c to rod %c", from_rod, to_rod);
return;
}
towerOfHanoi(n-1, from_rod, aux_rod, to_rod);
printf("\n Move disk %d from rod %c to rod %c", n, from_rod, to_rod);
towerOfHanoi(n-1, aux_rod, to_rod, from_rod);
}
int main()
{
int n = 4; // Number of disks
towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods
return 0;
}

Factorial Program using recursion in C


#include<stdio.h>
long factorial(int n)
{
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}

void main()
{
int number;
long fact;
printf("Enter a number: ");
scanf("%d", &number);
fact = factorial(number);
printf("Factorial of %d is %ld\n", number, fact);
return 0;
}

Output
Enter a number
4
Factorial of 4 is 24

MODULE 5 :- QUEUES

 DEFINITION:
A queue is an ordered list in which insertions (also called enqueue) and deletions (also called dequeue) take place
at different ends.The end at which new elements are added is called the rear, and that from which old
elements are deleted is called the front.

 If the elements are inserted A, B, C, D and E in this order, then A is the first element deleted from the queue.
Since the first element inserted into a queue is the first element removed, queues are also known as First-In-
First-Out (FIFO) lists.

REPRESENTATION :-Below figure 1 shows the logical representation of queues in memory. As we can
see in the above figure, there are five elements in the queue with –2 at the front and 4 at the rear.

Figure 1 : Logical representation of queue

The logical representation of queues showing queue elements stored at contiguous memory location might be true
in case of their array implementation but the same might not be true in case of their linked implementation.
Examples of queue:-
1. Queuing in front of a counter

Figure: Queue of Customers

Suppose there are a number of customers in front of a counter to get service(say, to collect tickets or to
withdraw/deposit money in a teller of a bank), figure 1. The customers are forming a queue and they will be
served in the order they arrived, that is, a customer who comes first will be served first.
2. Another example of queue is the line up of vehicles at the toll booth. The vehicle that comes first to the toll
booth leaves the booth first while the vehicle that comes last leaves at the last; thus, observing FIFO principle.
The concept of queue in data structures follows the same analogy as the queue of people or the queue of vehicles
at toll booth.
3. Phone answering system: The person who calls first gets a response first from the phone answering
system. The person who calls last gets the response last. Therefore, it follows first-in-first-out (FIFO)
strategy of queue.

4.Luggage checking machine: Luggage checking machine checks the luggage first that comes first.
Therefore, it follows FIFO principle of queue.

5.Patients waiting outside the doctor's clinic: The patient who comes first visits the doctor first, and the
patient who comes last visits the doctor last. Therefore, it follows the first-in-first-out (FIFO) strategy of
queue.

ARRAY REPRESENTATION OF QUEUES


 Queues may be represented by one-way list or arrays.

 Queues can be easily represented using linear arrays. As stated earlier, every queue has front and rear
variables that point to the position from where deletions and insertions can be done, respectively.

 Queues will be maintained by a linear array QUEUE and two pointer variables FRONT, REAR

FRONT: The end at which deletion takes place.


REAR: The end at which insertion takes place.

 If FRONT = –1 and REAR = –1, it means there is no element in the queue(queue is empty, underflow
condition). initially, set value of FRONT and REAR to -1

 Whenever an element is deleted from the queue, the value of FRONT is increased by 1; this can be
implemented by the assignment FRONT := FRONT + 1

 When an element is added to the queue, the value of REAR is increased by 1; this can be implemented by
the assignment REAR := REAR + 1

 REAR = MAX – 1, where MAX is the size of the queue, queue is full (overflow condition).
Below are the steps to enqueue (insert) data into a queue

 Check whether the queue is full or not.


 If the queue is full, produce the overflow error and exit.
 If the queue is not full, increment the rear pointer to point to the next empty space.
 Add the data element to the queue location, where the rear is pointing.
 Return success.
Below are the steps to perform dequeue operation

 Check if the queue is empty.


 If the queue is empty, produce the underflow error and exit.
 If the queue is not empty, increment front pointer to point to the next available data element.
 Access the data where front is pointing.
 Return success.

PRIMITIVE OPERATIONS ON LINEAR QUEUE


Implementation of the queue operations as follows.
1.Queue Create
Queue CreateQ(maxQueueSize) ::=
#define MAX_QUEUE_SIZE 100 /* maximum queue size */
typedef struct {
int key;
/* other fields */
} element;
element queue[MAX_QUEUE_SIZE];
int rear = -1;
int front = -1;

2.Boolean IsEmptyQ(queue):= front ==rear

3.Boolean IsFullQ(queue) ::= rear == MAX_QUEUE_SIZE-1

 Since the IsEmptyQ (Check if the queue is empty) and IsFullQ (Checks if the queue is full) operations are
quite simple, we again implement them directly in the addq and deleteq functions. Functions addq and
deleteq are structurally similar to push and pop on stacks.
 While stack uses the variable top in both push and pop, the queue increments rear in addq and front in
deleteq. Typical function calls would be addq(item); and item = delete();.

4.addq(item)
void addq(element item)
{ /* add an item to the queue */
if (rear == MAX_QUEUE_SIZE-1)
queueFull();
queue [++rear] = item;
}

Program: Add to a queue

5. deleteq( )
element deleteq()
{ /* remove element at the front of the queue */
if (front == rear)
return queueEmpty( ); /* return an error key */
return queue[++front];
}

Program: Delete from a queue

6. queueFull( )
//The queueFull function which prints an error message and terminates execution
void queueFull()
{
fprintf(stderr, "Queue is full, cannot add element");
exit(EXIT_FAILURE);
}

CASE STUDIES ON QUEUE DATA STRUCTURE


1. PRINTER SPOOLING

 A very important application of queues is printer spooling. It's crucial to understand from the outset that
printers have much less memory than you might think. Even in this day and age, some only have a few
megabytes of RAM available.
 By using printer spooling, we can send one or more large document files to a printer without having to
wait for the current task to be completed. Consider it as a cache or buffer. It's a location where your papers
can "queue up" and prepare for printing when another printing activity has been finished.
 All print tasks in the queue are managed by a program known as a "spooler". It will send the line of
documents to the printer in the sequence they were received using the First In First Out principle of the
queue.
 If not for spooling, each computer would have to manually wait for the printer to become accessible. Most
people take it for granted because it's handled automatically in the background.
 Spooling can make it simple to delete documents before they are printed because there is a queue in the
order that they were received.
 You can choose to delete a particular job from the queue, for example, if you accidentally printed the
wrong page or needed to format it slightly differently. While there could be several ways to accomplish
this, queues provide the most efficient solution.

2.JOB SCHEDULING
 Queues are frequently used in creation of a job queue by an operating system. Job scheduling is used
to select the job to be executed. CPU scheduling is used to allocate CPU time for a process
or job.
 There are 3 components used: Job Pool, Ready Queue, and Device Queue
 Job-Pool:- When a process enters into a system, they are added into a job pool . This pool
consists of all the processes in the syst em. Job scheduler also called as Long Term
Scheduler, takes the job or process from Job-pool and puts in the ready queue
 Ready-Queue:- This queue consists of processes which are residing in the main memory and
are ready and wait ing to execute. CPU Scheduler or Short Term Scheduler takes the process
from Ready queue and puts in the the CPU fo r execut ion. The process to be put in the CPU
is decided by a Scheduling Algorithm.
 Device Queue:- This queue contains the processes which are wait ing for the complet ion of
I/O request. Each device has its own device queue.
 M o v i n g be t w e e n P o o ls a n d Q u e u e s : - When the new process enters into the system and
ready for execut ion, it is put into ready queue. The operat ing system allocates the CPU to
that ready process. After getting the CPU, the process executes.
 E ve nt s : - During execut ion, one of the events may occur that are;
 Process issues an I/O request and then be placed in an I/O queue.
 Process creates a new subprocess and must wait till the subprocess terminates.
 Due to an interrupt ion, the process could be removed forcefully from the CPU and be put
back in the ready queue.
3.Routers in Networking

 Routers are essential pieces of networking hardware that regulate how data moves within a network. The
input and output interfaces on routers are where packets are received and transmitted.
 A router might not be able to handle newly arriving packets because of its limited memory.
 When the rate at which packets enter the router's memory exceeds the rate at which they leave, there will
be issues. In this case, older packets will be deleted while newer packets will be ignored.
 Therefore, to control how packets are kept or discarded as needed, routers must incorporate some form of
queuing discipline into their resource allocation algorithms.
 Following are a few queueing disciplines routers use to select which packets to keep and which ones to
drop in times of congestion:

First-In-First-Out Queuing (FIFO)

Most routers' default queuing strategy is FIFO. This often requires minimal to no setup on the server. In FIFO,
every packet is handled in the order that it enters the router. When the memory is full, new packets trying to enter
the router are rejected (tail drop).

Prioritization of Queuing (PQ)

Instead of using a single queue, the router divides the memory into several queues according to some metric of
priority in priority queuing. Following that, each queue is handled via FIFO, with each queue being cycled
through one at a time. Depending on their priority, the queues are categorized as High, Medium, or Low. Always,
the medium queue packets are processed after the high queue packets.
// C program to implement QUEUE operations

#include <stdio.h>
#define MAX 5

//Declaration of Queue
typedefstructqueue
{
intfront ;
intrear ;
intele[MAX] ;
}Queue;

//Intialze Queue
voidinit(Queue *q)
{
q->rear = -1;
q->front = 0;
}

//To check Queue is full or not


intisFull(Queue *q)
{
intfull=0;

if( q->rear == MAX -1)


full = 1;

returnfull;
}

//To check Queue is empty or not


intisEmpty(Queue *q)
{
intempty=0;

if( q->front == q->rear+1 )


empty = 1;

returnempty;
}

//Insert item into queue


voidinsertQueue(Queue *q,intitem)
{
if( isFull(q) )
{
printf("\nQueue Overflow");
return;
}

q->ele[++(q->rear)] = item;
printf("\nInserted item : %d",item);
}

//Delete item from queue


intdeleteQueue(Queue *q, int* item)
{
if( isEmpty(q) )
{
printf("\nQueue Underflow");
return-1;
}
*item = q->ele[(q->front)++];
return0;
}

intmain()
{
intitem = 0;
Queue q;

init(&q);

insertQueue(&q,10);
insertQueue(&q,20);
insertQueue(&q,30);
insertQueue(&q,40);
insertQueue(&q,50);
insertQueue(&q,60);

if( deleteQueue( &q, &item ) == 0 )


printf("\nDeleted item : %d",item);
if( deleteQueue( &q, &item ) == 0 )
printf("\nDeleted item : %d",item);
if( deleteQueue( &q, &item ) == 0 )
printf("\nDeleted item : %d",item);
if( deleteQueue( &q, &item ) == 0 )
printf("\nDeleted item : %d",item);
if( deleteQueue( &q, &item ) == 0 )
printf("\nDeleted item : %d",item);
if( deleteQueue( &q, &item ) == 0 )
printf("\nDeleted item : %d",item);

printf("\n");
return0;
}

OUTPUT:

Inserted item : 10
Inserted item : 20
Inserted item : 30
Inserted item : 40
Inserted item : 50

Queue Overflow
Deleted item : 10
Deleted item : 20
Deleted item : 30
Deleted item : 40
Deleted item : 50

Queue Underflow

QUESTION BANK

1) Explain the structure of C program with example.


2) List and explain various data types in c language with syntax and examples.
3) Discuss logical operators and relational operators with 1 example for each.
4) Evaluate the below expression (any expression with any operator combination will be asked and explain each
steps).
5) Explain various way of using scanf() and printf() statements with examples (or standard input output
statements)
6) List various conditional statements and explain with syntax and examples.
7) Compare if-else, nested else statements with examples.
8) Explain for, while and do-while statements with syntax and examples.
9) List the differences between while() and do-while looping statements with one example for each.
10) Discuss switch() statement with syntax and example( Brief on each element of switch block) or predict the
output of the following code
11) Illustrate how array is declared, initialized and elements stored in array with example.
12) Explain advantages, disadvantages of an array. Brief on Ternary operators used in C.
13) Discuss any 3 unconditional statements with syntax and examples.
14) Predict the output of following code (question from 1D array or 2D array).
For Ex:
char Array[3][6] = {"Black", "Blame", "Block"};
strcpy(Array[0], "Hello");
for(i = 0; i < 3; i++)
{
printf("%s\n", Array[i]);
}
15) write a C program to find sum of two matrices or any program may be or may not be asked.
16) List and explain string handling functions with program.
17) Discuss the rules to be followed in using user defined function, give one example program.
18) List types of built in functions and user defined functions. Brief on each and give 1 example.
19) List 4 types of functions used in C, Narrate on any two with examples.
20) Write a c program to find area of a circle using function or UDF().
21) Illustrate how a pointer can be declared and initialized with suitable program
22) Explain pointer arithmetic in detail
23) Demonstrate various techniques for parameter passing
24) Distinguish call by value and call by reference with programs for each
25) Write a c program to read and display the details of an employee
26) Compare and contrast Structure & union in C
27) Give the syntax to define the following
a. Structure
b. Union
28) Write a program to read and display the marks of a student for 6 subjects
29) Define Stack, Discuss the working and representation of a Stack
30) Explain the Basic operations of Stack
31) Imlement stack using Arrays
32) Implement stack using Pointers
33) Write the difference between arrays and Satcks
34) Discuss Tower of Hanoi problem
35) Explain the applications of stacks
36) write brief about recursion
37) what are the advantages and disadvantages of using stacks
38) Explain peek() function in stacks.
39) Write the definition of queue data structure.
40) Illustrate the Array representation of queue.
41) Define the properties of circular queue. How will you check whether the circular queue is
42) i) Full ii) Empty
43) Write the pseudocode for addition of elements into the queue and deletion of elements from the queue.
44) Explain overflow and underflow condition in queue.
45) Explain the realworld applications of queue data structure.
46) Illustrate the result of each operation in the sequence add A,B,C,D,E and delete A,B using array(initially empty).

You might also like