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

Data Structure PDF

Uploaded by

avi.singhec20
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Data Structure PDF

Uploaded by

avi.singhec20
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 99

Data Structures

using C
DR GAURAV KUMAR
ASST. PROF, CEA, GLA UNIVERSITY
C Programing
Quick Revision
Text Book- 1. Let Us C by Yashavant Kanetkar
2. The C Programming Language by Dennis Ritchie
Reference

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


C "Hello, World!" Program

#include <stdio.h>

int main()

printf("Hello, World!"); // printf() displays the string inside quotation

return 0;

}
Output- Hello, World!

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Compilation Process in C

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Compilation Process in C

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


How "Hello, World!" program works?

#include is a preprocessor command that tells the compiler to


#include <stdio.h> include the contents of stdio.h (standard input and output) file in
the program
int main() execution of a C program starts from the main() function

printf("Hello, World!"); printf() is a library function to send formatted output to the screen.

return 0; return 0; statement is the "Exit status" of the program. In simple terms, the
program ends with this statement
}

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


C Programming

C programming is a
a general-purpose

procedural

a middle-level computer programming language

developed in 1972 by Dennis M. Ritchie at the Bell

Telephone Laboratories to develop the UNIX operating

system.

In procedural language, variables and function prototypes must be declared before being used.

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Why to Learn C Programming?

MUST for students and working


professionals to become great Software
Engineer

Key advantages of learning C Programming

01 02 03
Easy to learn Structured language Handle low-level activities

04 05
Produces efficient programs Compiled on a variety of computer platforms

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Usage of C Programming
C was initially used for system development work, particularly
the programs that make up the operating system.

C was adopted as a system development language because


it produces code that runs nearly as fast as the code written
in assembly language.

01 02 03 04
Operating Systems Language Compilers Assemblers Text Editors

05 06 07 08 09
Print Spoolers Network Drivers Databases Language Interpreters Modern Programs

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


printf() and scanf() in C
The printf() and scanf() functions are used for input and

output in C language.

Both functions are inbuilt library functions, declared in

stdio.h (header file).

The syntax of printf() function is given below:

printf("format string",argument_list); OR printf("Simple Statement string");

The format string can be %d (integer), %c (character), %s (string), %f (float) etc.

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


printf() and scanf() in C
scanf() function

The scanf() function is used for input.

It reads the input data from the console.

The syntax of scanf() function is given below:

scanf("format string", &argument_list);

printf("enter a number:");
Example
scanf("%d", &number);

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Program to Add Two Integers
#include <stdio.h>

int main() {

int number1, number2, sum; //declared the variables

printf("Enter two integers: ");

scanf("%d %d", &number1, &number2);

// calculating sum

sum = number1 + number2;

printf("Sum of %d + %d = %d", number1, number2, sum);

return 0;

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Variable Declaration
A variable is nothing but a name given to a storage area that our

programs can manipulate.

Each variable in C has a specific type, which determines the size and

layout of the variable's memory. (int, char, float, double, long)

The name of a variable can be composed of letters, digits, and the

underscore character.

It must begin with either a letter or an underscore.

Upper and lowercase letters are distinct because C is case-sensitive.

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Syntax & Example of Variable Declaration

type variable_list;
int i, j, k;
Declaration char c, ch;
float f, salary;

i=3, j=5, k=10; Declaration with Initialization


Initilization
ch='a';
int d = 3, f = 5;
salary= 1000.0;

Vaiable Deafult value is Garbage value

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Assessment
Which one is the Correct Variable Declartion

a. int a2b;
b. int Abc;
c. int _abc;
d. int 2ab;
Answer is -

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Lvalues and Rvalues in C

There are two kinds of expressions in C

lvalue − Expressions that refer to a memory location are called

"lvalue" expressions.

rvalue − The term rvalue refers to a data value that is stored at

some address in memory.

a = 10;
lvalue rvalue
~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University
Control Structure
Decision Making

If Statement
The if statement in C is used to
perform the operations based on
some specific condition.

The operations specified in if block


are executed if and only if the given
condition is true.

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


If Syntax if(expression)
{
//code to be executed
}

int a = 10; /* local variable definition */

if( a < 20 ) // check the boolean condition using if statement


{

Or printf("a is less than 20\n" ); // if condition is true then print it


}
if(number%2==0)
{
printf("%d is even number",number);
}
~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University
Multiple If Statements
if(number%2==0)
{
printf("%d is even number",number);
}

If(number %3==0)
{
printf("number is not even number or number is divisible by
3 );
}

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


If Else Statement
if...else statement
An if statement can be followed by an optional else statement, which
executes when the Boolean expression is false.

if(number%2==0)
{
printf("%d is even number",number);
}
else
{
printf("number is not even number);
}

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Nested If Statements
int a = 100;
int b = 200;

if( a == 100 ) /* check the boolean condition */


{
/* if condition is true then check the following */
if( b == 200 )
{
/* if condition is true then print the following */
printf("Value of a is 100 and b is 200\n" );
}
}

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


nested if statements or
If else-if ladder Statement
You can use one if or else if statement
inside another if or else if statement(s).

if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;
nested if statements or
If else-if ladder Statement
int main()
{
if (condition) int i = 20;
statement; if (i == 10)
else if (condition) printf("i is 10");

statement; else if (i == 15)

. printf("i is 15");

. else if (i == 20)

else printf("i is 20");


else
statement;
printf("i is not present");
}
~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University
The ? : Operator
(Conditional Operator)

int main()
Syntax
{
int i = 20;
Exp1 ? Exp2 : Exp3;

The value of a ? expression is determined like this −


if (i == 10)
printf("i is 10");
Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes
else the value of the entire? expression.
printf("i is 20");
If Exp1 is false, then Exp3 is evaluated and its value becomes the

} value of the expression.

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


The ? : Operator
(Conditional Operator)

int main()
{
int i = 20;

if (i == 10)
printf("i is 10");
i==10 ? printf ("i is 10") : printf ("i is 20");
else
printf("i is 20");

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Switch Statement
if (i == 10)
printf("i is 10"); Switch
if (i == 20)
printf("i is 20");
if (i == 30)
printf("i is 30");
if (i == 40)
printf("i is 40");
if (i == 50)
printf("i is 50");
if (i == 50)
printf("i is 50");
Switch Statement
Switch case statements are a substitute for
long if statements that compare a variable
to several integral values

The switch statement is a multiway branch


statement.

It provides an easy way to dispatch


execution to different parts of code based
on the value of the expression.

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Switch Statement
Syntax int x = 2;
switch (x)
switch (n) {
{ case 1: printf("Choice is 1");
case 1: // code to be executed if n = 1; break;
break; case 2: printf("Choice is 2");
case 2: // code to be executed if n = 2; break;
break; case 3: printf("Choice is 3");
default: break;
// code to be executed if n doesn't match any cases
default: printf("Choice other than 1, 2 and 3");
}

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Real Life Application of
Switch Statement

Develop Menu-Driven program

Problem Statement:

Write a menu-driven program to calculate the following:

1. Area of circle

2. Area of square

3. Area of sphere

4. Area of Rectangle

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Example of Real Life Application of
Switch Statement
int choice, num; case 2: {
printf("Press 1 to calculate area of circle\n"); printf("Enter side of square:\n");
printf("Press 2 to calculate area of square\n"); num = input();
printf("Press 3 to calculate area of sphere\n"); result = num * num;
printf("Enter your choice:\n"); printf("Area of square=");
scanf("%d", &choice); output(result);
break;
switch (choice) { }
case 1: { case 3: {
printf("Enter radius:\n"); printf("Enter radius:\n");
num = input(); num = input();
result = 3.14 * num * num; result = 4 * (3.14 * num * num);
printf("Area of sphere="); printf("Area of sphere=");
output(result); output(result);
break; break;
} }

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Quiz on Switch Statement
int x = 2;
switch (x)
{
case 1: printf("Choice is 1");

case 2: printf("Choice is 2");


Output??
case 3: printf("Choice is 3");

default: printf("Choice other than 1, 2 and 3");

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Switch Statement
int x = 2;
switch (x)
{
case 1: printf("Choice is 1"); Output
case 2: printf("Choice is 2"); Choice is 2

case 3: printf("Choice is 3"); Choice is 3

Choice other than 1, 2 and 3


default: printf("Choice other than 1, 2 and 3");

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Quiz on Switch Statement
int x = 2;
switch (x)
{
case 1: printf("Choice is 1");

Output??
case 3: printf("Choice is 3");

default: printf("Choice other than 1, 2 and 3");

case 2: printf("Choice is 2");


}

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Quiz on Switch Statement
int x = 2;
switch (x)
Output
{
a. Choice is 2
case 1: printf("Choice is 1");
Choice is 3
Choice other than 1, 2 and 3
case 3: printf("Choice is 3");

b. Choice is 2
default: printf("Choice other than 1, 2 and 3");

c. Error
case 2: printf("Choice is 2");
}

Answer- b ~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Switch Statement
int x = 5;
switch (x)
{
case 1: printf("Choice is 1");

Output??
case 3: printf("Choice is 3");

default: printf("Choice other than 1, 2 and 3");

case 2: printf("Choice is 2");


}

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Quiz on Switch Statement
int x = 5; Output
switch (x)
{ a. Choice other than 1, 2 and 3
case 1: printf("Choice is 1");
b. Choice other than 1, 2 and 3
case 3: printf("Choice is 3"); Choice is 2

default: printf("Choice other than 1, 2 and 3"); c. Error

case 2: printf("Choice is 2");


}

Answer- b
~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University
Switch Expression
Char ch = 'b';
Valid expressions for switch
switch (ch) switch(1+2+23)
{ switch(1*2+3%4)
case a: printf("Choice is a");

case b: printf("Choice is b");


Invalid switch expressions

default: printf("Choice other than a and b"); switch(ab+cd)


switch(a+b+c)
}

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


C - Loops
You may encounter situations, when a block of code needs to be
executed several number of times.

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


C - Loops Type & Description

01 while loop

02 for loop

03 do...while loop

04 nested loops

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


01 while loop
A while loop in C programming repeatedly executes a target statement as
long as a given condition is true.

Syntax

while(condition)
{
statement(s);
}

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


01 while loop

value of a: 10
int a = 10;
value of a: 11
value of a: 12
/* while loop execution */ Output value of a: 13
while( a < 20 )
value of a: 14
{ value of a: 15
printf("value of a: %d\n", a); value of a: 16
a++; value of a: 17
} value of a: 18
value of a: 19

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Quiz Example of while loop
int a=10;
while( a < 20 )
{
printf("This is the Data Structure Class\n",);
} a. Syntax Error

Output?? b. Logical Error


c. This is the Data Structre Class
d. Infinite Loop

Answer- infinite Loop ~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University
Example of while loop

int a=10;
while( a < 20 )
{
printf("This is Data Structure Class\n",);
a++; // a=a+1;
}
Before adding a++, the output will be infinite loop
After adding a++, it will execute for 10 times only.

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


02 for loop
A for loop is a repetition control structure that allows you to efficiently write a loop that needs
to execute a specific number of times

Syntax
for ( initialization; condition; increment )
{
statement(s);
}

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Example of loop
int a;

/* for loop execution */

for( a = 10; a < 20; a = a + 1 )


{
printf("We are learning For Loop");
}

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Example of loop
for( ; ; )
{
printf("We are learning For Loop");
} a. Error

b. We are learning For Loop


Output??? c. Infinite Times Printing
We are learning For Loop
d. Do not know
Answer- C ~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University
03 do....while loop
Unlike for and while loops, which test the loop condition at the top of the loop, the
do...while loop in C programming checks its condition at the bottom of the loop.

A do...while loop is similar to a while loop, except the fact that it is guaranteed to
execute at least one time.

Syntax
do
{
statement(s);
} while( condition );

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


03 do....while loop

int a = 10; value of a: 10


/* do loop execution */ value of a: 11

do value of a: 12
value of a: 13
{ Output
value of a: 14
printf("value of a: %d\n", a); value of a: 15
a = a + 1; value of a: 16

}while( a < 20 ); value of a: 17


value of a: 18
value of a: 19

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


04 nested loops in C
C programming allows to use one loop inside another loop.

Syntax
for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s);
}
~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University
04 nested loops in C
Nested While Nested do...while

while(condition) do
{ {
while(condition) statement(s);
{ do

statement(s); {
statement(s);
}
}while( condition );
statement(s);
}while( condition );
}

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Loop Control Statements
Loop control statements change execution from its normal sequence.

a. break statement (Syntax: break;)


When a break statement is encountered inside a loop, the loop is immediately
terminated and
the program control resumes at the next statement following the loop.
int a = 10;
while( a < 20 ) //while loop execution
{ value of a: 10
printf("value of a: %d\n", a); value of a: 11
a++;
Output
value of a: 12
if( a > 15)
{
value of a: 13
/* terminate the loop using break statement */ value of a: 14
break; value of a: 15
}
}
~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University
Loop Control Statements
Loop control statements change execution from its normal sequence.

b. continue statement (Syntax: continue;)


Instead of forcing termination, it forces the next iteration of the loop to take
place, skipping any code in between.

int a = 10; value of a: 10


while( a < 20 ) //while loop execution value of a: 11
{ value of a: 12
if( a == 15)
value of a: 13
{ Output
a=a+1; value of a: 14
continue; // skip the current loop value of a: 16
}
value of a: 17
printf("value of a: %d\n", a);
value of a: 18
a++;
} value of a: 19
~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University
Loop Control Statements
c. goto statement
A goto statement provides an unconditional jump from the 'goto' to a labeled
statement in the same function.
Syntax
Int a=10;
goto label;
LOOP:do
.. value of a: 10
{
value of a: 11
. if( a == 15) // skip the iteration
value of a: 12
{
label: statement; Output value of a: 13
a = a + 1;
value of a: 14
goto LOOP;
value of a: 16
}
value of a: 17
printf("value of a: %d\n", a);
value of a: 18
a++;
value of a: 19
}while( a < 20 );

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Functions
A function is a group of statements that together perform a task.

Every C program has at least one function, which is main(), and program starts execution
from main.

Syntax of Defining a Function Example


return_type function_name( parameter list ) int sum(int num1, int num2)

{ {

body of the function int result; //local variable

} result= num1 + num2;


return result;
}

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Functions
A function is a group of statements that together perform a task.

Every C program has at least one function, which is main(), and program starts execution
from main.

Example
Task- Maximum of two numbers
Task- Addition of two numbers
int a, b, max;
int a, b, sum;
a=5, b=10;
a=5, b=10;
if(a>b)
sum= a + b;
printf("Max is %d", a);
printf("Sum is: %d", sum);
else
printf("Max is %d", b);

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Functions sum()
Task- Addition of two numbers {
int a, b, sum; int a, b, sum;
a=5, b=10; a=5, b=10;
sum= a + b; sum= a + b;
printf("Sum is: %d", sum); printf("Sum is: %d", sum);
}
max()
Task- Maximum of two numbers {
int a, b, max; int a, b, max;
a=5, b=10; a=5, b=10;
if(a>b) if(a>b)
printf("Max is %d", a); printf("Max is %d", a);
else else
printf("Max is %d", b); printf("Max is %d", b);
}
~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University
Functions Definition
return_type function_name( parameter list )
{
optional
body of the function
}

Example Example
int sum(int num1, int num2) display()
{ {
int result; //local variable printf(" I am in display function");
result= num1 + num2; }
return result;
}

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Functions Declaration
return_type function_name( parameter list ); or Argument List

optional

A function declaration tells the compiler about a function name and how
to call the function.

Example int sum(int num1, int num2);

Parameter names are not important in function declaration only their


type is required, so the following is also a valid declaration

Example int sum(int, int); Valid Declaration

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Calling a Function
To call a function, you simply need to pass the required parameters along
with the function name, and if the function returns a value, then you can
store the returned value.

When a program calls a function, the program control is transferred to


the called function.

A called function performs a defined task and when its return statement is
executed or when its function-ending closing brace is reached, it returns
the program control back to the main program.

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Calling a Function
#include <stdio.h>
int sum(int num1, int num2); //function declaration
int main ()
{
int add, a = 100, b = 200; //Local Variables of main function
add = sum(a, b); //Calling a Sum function
printf( "Sum of two number is : %d\n", add);
return 0;
}
int sum(int num1, int num2) //Called function
{
int result; //Local Variable of Sum function
result= num1+num2;
return result; Scope of the variable is restricted to the
} function only where it has defined
~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University
Local and Global Variables
There are three places where variables can be declared in C
programming language

Inside a function or a block which is called local variables.

Outside of all functions which is called global variables.

In the definition of function parameters which are called formal


parameters.

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Local Variables
Variables that are declared inside a function or block are called
local variables.

They can be used only by statements that are inside that function or
block of code.

Local variables are not known to functions outside their own.

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Global Variables
Global variables are defined outside a function, usually on top of the
program.

Global variables hold their values throughout the lifetime of your


program and they can be accessed inside any of the functions
defined for the program.

int g;

int main () {

/* local variable declaration */


int a, b;
~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University
Type of Calling a Function

Call by value

Call by Reference

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Function Arguments

Formal Argument
A variable and its type as they appear in the
prototype of the function or method

Actual Argument
The variable appears in the function call in the calling
environment

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Function Arguments
int add, a = 100, b = 200;
add = sum(a, b); // Actual argument
printf( "Sum of two number is : %d\n", add);

int sum(int num1, int num2) //Formal Argument


{
int result; //Local Variable of Sum function
result= num1+num2;
return result;
}

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Call by value
Value of actual argument is passed into the formal argument

any changes made to the formal argument doesnt effect the actual
Example argument

void swap(int x, int y)


int a = 100, b = 200;
{
printf("Before swap, value of a : %d\n", a );
int temp;
printf("Before swap, value of b : %d\n", b );
temp = x; /* save the value of x */
swap(a, b); // calling a function to swap the values
x = y; /* put y into x */
printf("After swap, value of a : %d\n", a );
y = temp; /* put temp into y */
printf("After swap, value of b : %d\n", b );
}
~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University
Call by value
int a = 100, b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
swap(a, b); // calling a function to swap the values
printf("After swap, value of a : %d\n", a );
Before swap, value of a : 100
printf("After swap, value of b : %d\n", b );
Output Before swap, value of b : 200
void swap(int x, int y)
After swap, value of a : 100
{
int temp;
After swap, value of b : 200
temp = x;
x = y;
y = temp;
}

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Call by Reference

The call by reference method of passing arguments to a function


copies the address of an argument into the formal parameter.

Inside the function, the address is used to access the actual


argument used in the call.

It means the changes made to the parameter affect the passed


argument.

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Pointer
A pointer is a variable whose value is the address of
another variable, i.e., direct address of the memory
location

int a = 100;
printf( "Number is : %d", a);
printf( "Address of Number is : %d", &a)
/*& is referencing operator*/
printf( "Value of a is : %d", *(&a);

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Pointer
Syntax type *var-name;

int a=100;
int *p; //pointer to an integer
p=&a;

* is indirection operator or dereferencing operator

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Call by Reference
void swap(int *x, int *y);// Fucntion Declaration

int a = 100, b = 200;


printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
swap(&a, &b); // calling a function to swap the values
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );

void swap(int *x, int *y)


{ Before swap, value of a : 100
int temp; Before swap, value of b : 200
Output
temp = *x; /* save the value at address x */ After swap, value of a : 100
*x = *y; /* put y into x */ After swap, value of b : 200
*y = temp; /* put temp into y */
}
~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University
Array
An array is used to store a collection of data of same type

All arrays consist of contiguous memory locations.

Syntax type arrayName [ arraySize ];

This is called a single-dimensional array.

The arraySize must be an integer constant greater than zero


and type can be any valid C data type.

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Array Initialization
double balance[10];
balance[0] = 50.0;
balance[1] = 20.0;
.
.
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};

double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Accessing Array Elements

double salary = balance[3];

The above statement will take the 4th element from the array
and assign the value to salary variable.

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Extended Pointers
int a, *b, **c;
a=10;
b=&a;
c=&b;

printf("The value of a is : %d", a );

printf("The value of a is : %d", *b );

printf("The value of a is : %d", **c );

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


NULL Pointers
It is always a good practice to assign a NULL value to a
pointer variable in case you do not have an exact
address to be assigned.

This is done at the time of variable declaration.

A pointer that is assigned NULL is called a null pointer.

int *ptr = NULL; Output


printf("The value of ptr is : %x\n", ptr ); The value of ptr is 0

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Operations on Pointers
There are four arithmetic operators that can be used on pointers: ++, --, +, and -

Incrementing a Pointer ptr++ Decrementing a Pointer ptr--


let us consider that ptr is an integer pointer which points to the address 1000.

After the above operation, the ptr will point to the location 1004 (Size of an
integer is 4 bytes)

If ptr points to a character whose address is 1000, then the above operation
will point to location 1001 because the next character will be available at 1001.

ptr+n= ptr + sizeof(ptr)*n


Operations on Pointers

Two Pointers can not be


added/subtracted/multiplied and divided

Note: Two Pointers of same type can be subtracted


ptr1-ptr2 = literal subtraction/size of (ptr)

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Pointer Comparisons

Pointers may be compared by using relational operators, such


as ==, <, and > (relational operator) or ==, != (equality
operator)

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.

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Example of Pointer Comparisons

int n[ 5 ] = {3, 6, 8, 12, 15}


int *ptr1, *ptr2;
ptr1=&n[2];
ptr2=&n[4]; Output?
printf("%d"; ptr1<=ptr2); 1
printf("%d"; ptr1>=ptr2);
0

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Storing Array Elements using Pointer
or Pointer to an Array

Pointer to an array is also known as array pointer. We are using the pointer to
access the components of the array.

int var[5], i; int var[5], i, *p;


p=&var[0]; or p=var;
for (i = 0; i < 5; i++) for (i = 0; i < 5; i++)
{ {
scanf("%d", &var[i]); scanf("%d", p+i);
} }
Storing Array Elements using Pointer
or Pointer to an Array
Returning a Pointer

int* fun() int* p;


{ p = fun();
int A = 10; printf("%u\n", p);
return (&A); printf("%d\n", *p);
}

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Passing and Returning Pointer
The previous programme will show segementation error

int* fun() int* p;


{ p = fun();
static int A = 10; printf("%u\n", p);
return (&A); printf("%d\n", *p);
}
Static Variables have a property of preserving their value even after they are out of their scope.

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Structures
Structure is another user defined data type available in C that
allows to combine data items of different kinds.

Structures are used to represent a record. Suppose you want to


keep track of your books in a library. You might want to track the
following attributes about each book −

Title
Author
Subject
Book ID

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Structures
struct [structure tag]
{

member definition;
member definition;
...
member definition;
} [one or more structure variables];

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Accessing Structure Members
To access any member of a structure, we use the member access operator (.).

struct Books {
char title[50];
char author[50]; struct Books Book1;

char subject[100]; struct Books Book2;

int book_id;
};

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Accessing Structure Members
struct Books {
Book1.title= "C Programming";
char title[50];
Book1.author="Nuha Ali";
char author[50];
char subject[100];
Book1.subject= "C Programming Tutorial";
int book_id; Book1.book_id = 6495407;
};

printf( "Book 1 title : %s\n", Book1.title);


printf( "Book 1 author : %s\n", Book1.author);

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Structures as Function Arguments
struct Books { /* function declaration */
char title[50]; void printBook( struct Books book );
char author[50];
char subject[100];
int book_id;
void printBook( struct Books book)
}; {
printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 author : %s\n", Book1.author);
}
Pointers to Structures
struct Books {
struct Books *struct_pointer; char title[50];
char author[50];
struct_pointer = &Book1; char subject[100];
int book_id;
};

To access the members of a structure using a pointer to that structure,


you must use the → operator as follows
struct_pointer->title;

printf( "Book title : %s\n", book->title);

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Pointers to Structures
struct Books {
struct Books *struct_pointer; char title[50];
char author[50];
struct_pointer = &Book1; char subject[100];
int book_id;
};

To access the members of a structure using a pointer to that structure,


you must use the → operator as follows
struct_pointer->title;

printf( "Book title : %s\n", book->title);


Dynamic Memory Management
The C programming language provides several functions for
memory allocation and management. These functions can be
found in the <stdlib.h> header file.

Dynamic Memory Allocation can be defined as a procedure in which the


size of a data structure (like Array) is changed during the runtime.

malloc()
calloc()
free()
realloc()
~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University
C malloc() method
The “malloc” or “memory allocation” method in C is used to dynamically allocate a
single large block of memory with the specified size.

It returns a pointer of type void which can be cast into a pointer of any form.

It doesn’t Iniatialize memory at execution time so that it has initializes each block with
the default garbage value initially.

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

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


Since the size of int is 4 bytes, this statement will allocate 400 bytes of
memory. And, the pointer ptr holds the address of the first byte in the
allocated memory.

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


C malloc() method
int *ptr, n, i;
printf("Enter number of elements:");
scanf("%d",&n);
printf("Entered number of elements: %d\n", n);

ptr = (int*)malloc(n * sizeof(int)); // Dynamically allocate memory

// Check if the memory has been successfully allocated by malloc or not


if (ptr == NULL)
{
printf("Memory not allocated.\n");
exit(0);
}

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


C calloc() method
“calloc” or “contiguous allocation” method in C is used to
dynamically allocate the specified number of blocks of memory of
the specified type. it is very much similar to malloc() but has two
different points and these are:

It initializes each block with a default value ‘0’.

It has two parameters or arguments as compare to malloc().

ptr = (cast-type*)calloc(n, element-size);


here, n is the no. of elements and element-size is the size of each
element.

Example: ptr = (int*) calloc(25, sizeof(int));


~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University
C free() method
“free” method in C is used to dynamically de-allocate the memory.

The memory allocated using functions malloc() and calloc() is not


de-allocated on their own.

Hence the free() method is used, whenever the dynamic memory


allocation takes place.

It helps to reduce wastage of memory by freeing it.

Syntax: free(ptr);

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


C realloc() method

“realloc” method in C is used to dynamically change the memory


allocation of a previously allocated memory.

Syntax:

ptr = realloc(ptr, newSize);

where ptr is reallocated with new size 'newSize'.

~Dr Gaurav Kumar, Asst. Prof, CEA, GLA University


Keep Learning!

Feel happy to discuss your queries on


[email protected] 8586968801

Office: 310, C11, AB-1

You might also like