Data Structures Using C 22cse13 Module Notes Final
Data Structures Using C 22cse13 Module Notes Final
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
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
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
Example:
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
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
Real Constant:
Character Constant
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.
iv. Strings
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:
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 (>>)
X ~X
0 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
Determines Sign
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- -
6. EXPRESSIONS
* Multiplication
/ Division Left to right 3
% Modulus
7. DATA TYPES
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
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.
\a Alarm or Beep
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Tab (Horizontal)
\v Vertical Tab
\\ Backslash
\0 Null
S Format
NO. Specifier Type Description
5 %ld long int Used for I/O long signed integer value
double,long
8 %lf double Used for I/O fractional or floating data
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.
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
6. Conditional operator
8. Special operators
+ 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 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
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
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--
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
~ 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);
}
Algo Flo
rith wch
m art
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
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);
}
Reading a character, writing a character, formatted input- output statements, and unformatted input-output
statements.
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:
In this string the symbol \n commands that the cursor should advance to the beginningof the next line. In
the following example:
%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:
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.
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
}
S
NO. Format Specifier Type Description
5 %ld long int Used for I/O long signed integer value
If your have another set of statement to be executed if condition is false then if-else is
Used.
Flow char
#include <stdio.h>
int main()
if (x > y)
if (x > z)
{
printf("x is larger than y and z ");
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.
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.
Goto Statement:
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:
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);
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
body of loop
}
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();
}
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
Output:
Enter your age: 34
You can vote
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;
Output:
C and D
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
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
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
Output:
Enter the number of terms: 7
Fibonacci Series: 0 1 1 2 3 5 8
#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
return 0; }
Output:
Enter a number: 434
The number is a palindrome.
#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 */
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] ;
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
56 10 30
34 21 34
45 56 78
Ex:3
#include <stdio.h>
int main()
scanf("%d", &a[i][j]);
}
// Taking input using nested for loop
scanf("%d", &b[i][j]);
printf("Sum Of Matrix:\n");
printf("%d\t", result[i][j]);
printf("\n");
return 0;
Output:
456
789
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).
#include <stdio.h>
int main()
intthree_dim [2][3][4] = {
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.
or
• char string[5] = “ISE”;
(or)
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
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);
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:
Advantage of functions in C:
• The function provides modularity.
• 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.
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
function_name (argument_list)
• Function definition
Example:1
#include <stdio.h>
// Function declaration
// Function definition
if (i> j)
returni;
else
return j;
int main(void){
// Calling the function to find the greater number among the two
return 0;
}
Output:
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.
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.
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,
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");
Output:
Enter 5 values4
2
8
5
7
Displaying the elements of the array: 4
2
8
5
7
#include <stdio.h>
int main()
{
int arr[6] ;
printf("Enter 6 values");
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
#include <stdio.h>
int main()
{
int i, largest;
largest = arr[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);
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
#include <stdio.h>
int main() {
return 0; }
Output:
Enter number of elements: 4
Enter number1: 21
Enter number2: 11
Enter number3: 43
Enter number4: 12
Average = 21.00
#include <stdio.h>
void main()
{
int arr1[10], arr2[10], arr3[10];
int i,j=0,k=0,n;
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
char src[50];
char dest[50];
strcpy(src,"This is source");
strcpy(dest, "This is destination");
strncpy(dest, src, 10);
Output:
before after
Final destination string |This is sostination|
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);
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); }
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);
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).
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.
Output:
0x29feec
0x29fee8
0x29fee4
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)
#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] −
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;
};
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.
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
#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
#include <stdio.h>
int main()
{
int* ab;
int m;
m=29;
printf(" Here in the declaration ab = int pointer, int m= 29\n\n");
Output:
Here in the declaration ab = int pointer, int m= 29
Address of m : 0x7ffcb906b7ac
Value of m : 29
#include <stdio.h>
long addTwoNumbers(long *, long *);
int main()
{
long fno, sno, sum;
#include <stdio.h>
#include <stdlib.h>
void main()
{
int fno,sno,*ptr1=&fno,*ptr2=&sno;
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
#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
#include<stdio.h>
int main(){
int number=50;
int *p;
p=&number;
int *q;
q = &number;
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
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>
int main() {
int c_no;
// assign value to name of person1
return 0;
}
Output:
Enter citizenship no.: 6550
Name: Jim Carrie
Citizenship No.: 6550
Salary: 25000.00
#include <stdio.h>
union Job {
float salary;
int workerNo;
} s,j;
int main() {
s.salary = 12.3;
j.workerNo = 100;
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.
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);
}
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.
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.
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.
Note: Underflow condition can occur in pop operation if we try to perform a pop operation on an empty stack.
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.
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.
// Function declarations
void push();
void pop();
void peek();
#define MAX 50
int size;
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).
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.
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
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.
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
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
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;
}
5. deleteq( )
element deleteq()
{ /* remove element at the front of the queue */
if (front == rear)
return queueEmpty( ); /* return an error key */
return queue[++front];
}
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);
}
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:
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).
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;
}
returnfull;
}
returnempty;
}
q->ele[++(q->rear)] = item;
printf("\nInserted item : %d",item);
}
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);
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