Docsity

Arrays, Pointers, Linked Lists and Binary Trees in C Programming, Summaries of Data Structures and Algorithms

Partial preview of the text

Download Arrays, Pointers, Linked Lists and Binary Trees in C Programming and more Summaries Data Structures and Algorithms in PDF only on Docsity!

DATA TYPES AND OPERATORS

1.1 Data Types

1.1.1 Primitive Data Type

(a) Integer Types:

✓ short int,

✓ int,

✓ long int,

✓ long long int,

unsigned short int

unsigned int

unsigned long int

unsigned long long int

(b) Character Types:

✓ char,unsigned char

(c) Floating Types:

✓ float, double, long double

(d) Other:

✓ void, bool

1.1.2 Non – Primitive Data Type

(a) Derived data type:

✓ Array

✓ Pointer

✓ String

(b) User defined data type:

✓ Structure

✓ union

✓ Enum

✓ typedef

  • C standard does not specify how many bits or bytes to be allocated for every type and different compiler may choose

different ranges.

  • Only restriction is that short and int types are at least 16 bits, long types are at least 32 bits and short is no longer than int

which is no longer that long type.

C Programming

x = 13

Finally, 13 is assigned to x.

1.2.4 Logical Operators

(i) Logical AND (&&)

(ii) Logical OR (||)

(iii) Logical NOT (!)

  • Just like rational operators, the result of every logical operator is either 0 or 1.
  • Logical NOT is a unary operator
  • Logical NOT converts a non-zero operand into 0 and a zero operand in 1.

1.2.5 Short Circuiting in Logical Operators

  • In case of logical AND, the second operand is evaluated only if the first operand is evaluated to be true.

If the first operand is evaluated as false then the second operand is not evaluated.

  • In case of logical OR operation, the second operand is not evaluated if the first operand is evaluated as true.

Example1: void main () {

printf (“Hello”) || printf (“Pankaj”);

O/P: Hello

printf function display everything written within double quotes on the monitor and the result / value returned

by printf () is the number of characters successfully displayed on the screen.

So, printf (“Hello”) prints Hello and return 5.

So, the expression

printf (“Hello”) || printf (“Pankaj”);

becomes

5 || printf (“Pankaj”)

As the first operand for logical OR is evaluated as true, second printf () will never execute.

1.2.6 Increment and Decrement Operators

(i) pre increment ++x

(ii) post increment x++

(iii) pre decrement - - x

(iv) post decrement x - -

  • unary operator.
  • can’t be applied on constant / literals.
  • Pre increment: can be viewed as 2 step operators.

st

step: Increment the value of variable.

nd

step: After increment, use the value of variable.

  • Post increment: can be viewed as 2 step operators

st

step: Use the value.

nd

step: Increase the value of variable by 1.

1.2.7 Bitwise operators

(i) Bitwise AND (&)

(ii) Bitwise OR (|)

(iii) Bitwise XOR (^)

(iv) Bitwise Left Shift (<<)

(v) Bitwise Right Shift (>>)

(vi) Bitwise Not ( )

  • All these operators work on binary representation of numbers.
  • Typically, faster than arithmetic operators and other operators.

// output 2

// output 7

// output 5

#include

int main () {

int x = 3, y = 6;

printf (“%d\n”,x & y);

printf (“%d\n”,x|y);

printf (“%d\n”, x^y)

return 0;

binary representation of 3: 00000000...

binary representation of 6: 00000000...

3 ^ 6: 00000000...

XOR of two bits is 1 if both bits are different.

XOR of two bits is 0 if both bits are same.

  •  x has output as – (x + 1)
  • printf (“%d\n”, ~2) has output - 3 i.e., - (2 + 1)
  • Comma has lowest precedence among all operators in C language.
  • sizeof() is used

(i) To find the number of elements present in an array.

(ii) To dynamically allocate block of memory.

1.2.8 Ternary operator (? :)

  • It requires 3 operands i.e., Left, Middle, Right

Left? Middle : Right

  • If left expression evaluates as true, then the value returned is middle argument otherwise the returned value is

Right expression

int a;

a = 7 > 2? 3  2 + 5 : 6! = 7

 Left expression: 7 > 2 is true

 So, the value returned would be the middle argument.

i.e., 3  2 + 5 = 11

so, a will get 11.

CONTROL FLOW STATEMENTS

2.1 Switch Statement

  • “Case Value” can be of character type and int type.
  • There can be one or many number of cases.
  • Statements associated with a matching case executes until a break statement is reached.
  • The position of default case does not matter. It can be placed anywhere.
  • Default case is optional.
  • Duplicate case labels are not allowed.
  • Statements written before all the cases are ignored by the compiler.
  • The break statement is optional.
  • Case label cannot be a variable.

2.2 Iterative statements (Loop)

An iterative statement, or loop, repeatedly executes a group of statements, known as body of loop, until the controlling

expression is false.

2.2.1 For Loop

  • The for statement evaluates 3 expressions and executes the loop body until second controlling expression

executes to false.

  • It is recommended to use for loop when the number of iterations is known in advance.
  • Syntax of for loop is:

for (expression – 1(optional); expression – 2(optional); expression – 3(optional))

statement – 1

statement – 2

statement – n

  • for loop executes the loop body 0 or more times.
  • for statements works as follows:

(a) expression – 1 is evaluated once before the first iteration of the loop.

(b) expression – 2 is a expression that determines whether to terminate the loop. expression – 2 is evaluated before every

iteration.

If the expression is true (non - zero), the loop body executed.

If the expression is false (zero), execution of the for statement is terminated.

(c) expression – 3 is evaluated after each iteration.

(d) The for statement executes until expression-2 is false (0), or until a jump statement terminates execution of the loop.

  • All 3 expression can be omitted

(a) If we omit expression-2, the condition is considered as true for an example:

for (i = 0; ; i++) represent an infinite loop

statement.

2.3 While Statement

  • The while statement evaluates a controlling expression before every execution of the loop body.
  • If the controlling expression is true (non-zero), the loop body is executed. If the controlling expression is false (zero),

then the while statement terminates.

  • Syntax:

while (expression) while (expression)

statement- 1

statement- 2

OR

statement

statement-n

2.4 Do-while Loops

  • Both for and while loop checks the loop termination condition before every iteration but do while loop check the

condition after executing the loop body.

  • do while loop body executes at least 1 time, no matter whether the loop termination condition is false or true.
  • Syntax is:

do

do {

statement- 1

OR statement- 2

statement

while (expression);

statement-n

} while (expression);

2.5 Break Statement

  • The break statement provides an early exit from for, while and do while.
  • A break statement causes the innermost loop or switch to be exited immediately.
  • In implementation, when we know the maximum number of repetition but some condition is there, where we require to

terminate the repetition process, then use break statement.

Example:

void main ()

int i = 1;

while (i < = 15)

STORAGE CLASS & FUNCTION

3.1 Memory Organization of C Program

3.1.1 Code Segment

  • It is also known as text segment.
  • It contains executable instructions and this segment is a read only segment.
  • Usually, this section is sharable.

3.1.2 Uninitialized data segment

  • This section contains all static and global variables that are not initialized by the programmer and hence initialized to

zero (default value).

3.1.3 Initialized data segment

  • This section contains all static and global variables that are initialized by the programmer.

3.1.4 Stack

  • In this local variables are stored and some other information is also saved.
  • A set of values stored for a function is called as stack frame which atleast contain return address.

3.1.5 Heap

  • This area is responsible for dynamic memory allocation. The heap area is managed by malloc(), calloc(), ralloc() and free()

which may be use brk() and sbrk() system calls.

3.1.6 Static Memory

  • Compile time allocation
  • Static variable
  • Global Variable

3.2 Storage Classes

Storage

Class

Scope Life Time Default Storage area

auto Local

Within

function

Garbage

Value

RAM

static Local

Till end of

main

program

0 RAM

extern Global

Till end of

main

program

0 RAM

Register Local

Within

function

Garbage Register

  • Stack Overflow: Abnormal Termination
  • If conflict between global and local variable occurs, then local variable gets preference.
  • Declaration of a register variable is only a recommendation/request not a command.
  • Cannot apply ‘&’ operator with register variable.
  • No physical memory is allocated using ‘extern’ keyword.
  • Extern declaration is mandatory when an external variable is referred before it is defined or if it is defined in

some other source file from the file where it is being used.

  • Declaration of an external variable tells about the properties like its type, while definition leads to storage allocation.

3.3 Recursion

Definition: When the body of a function call the function itself directly or indirectly.

  • Certain arguments for which the function does not call itself are called as base argument, base values.
  • In general, for recursion to be non-cyclic whenever a function calls itself the formal arguments must get closer to the base

argument.

Example 1:

Consider the factorial code:

int factorial (int n)

if (n = = 0)

return 1;

else

return n * factorial (n - 1);

If we call factorial (3), it will call factorial of 2 and so on …the argument will get closer to 0 i.e., the base argument.

  • Recursion code is shorter than iterative code.
  • Overhead is present.
  • Some standard problems are best suited to be solved by using recursion for example- Tower of Hanoi, Factorial, merge

Sort.

3.4 Static and dynamic scoping

3.4.1 Static Scoping

Static scoping is also called as lexical scoping. In this scoping, the binding of a variable can be determined by the program text.

In this type of scoping compiler first looks in the current block (local), then in global variables i.e., local and then ancestors’

strategy is followed.

C Programming

and dynamic scoping, let’s try to find the output.

The order of function calls is:

main () ⎯

c

alling

⎯⎯ →f() ⎯

c

alling

⎯⎯ →g()

g() is printing i, which is not present inside current block. So, because of dynamic scoping compiler will go to the function that

calls g() i.e., compiler will search f() for variable i. Hence 20 is printed.

ARRAYS AND POINTERS

4.1 Array

  • An array is defined as the collection of similar type of data items stored at contiguous memory locations.
  • Arrays are the derived data type in C programming language which can store the primitive type of data such as int, char,

double etc.

  • It has the capability to store the collection of derived data types such as pointer, structure etc.
  • Each element of an array is of same data type and carries the same size example int = 4 byte.
  • Elements of the array are stored at contiguous memory locations, meaning, the first element is stored at the smallest

memory location.

  • Elements of the array can be randomly accessed since we can calculate the address of each element of array with the given

base address and size of the data element.

4.1.1 Advantages of C Array

  1. Code Optimization: Less code to access the data.

  2. Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.

  3. Ease of sorting: To sort the elements of the array, we need a few lines of code only.

  4. Random Access: We can access any element randomly using the array.

4.1.2 Disadvantages of Array

  • Fixed Size : 1) Whatever size, we define at the time of declaration of the array, we can’t exceed the limit.
  1. It does not grow the size dynamically like linked list.

Declaration of C Array

Syntax:

Example:

Initialization of C array:

We can initialize each element of the array by using the index. Suppose array int marks [5]. Then

4.1.4 Two-Dimensional Array

  • The two-dimensional array can be defined as an array of arrays.
  • The 2D array is organized as matrices which can be represented as the collection of row and columns.

4.1.5 Declaration of two-dimensional array in C syntax

Example:

Example: Program of Two-Dimensional Array

include

int main()

int i = 0, j = 0;

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

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

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

printf(“arrayHello[%d][%d]=%d\n”,i,j,arrayHello[i][j])

return 0;

Initialization of 2D Array

int array Hello [4] [3] = {{1,2,3}, {3,4,5}, {4, 5, 6}};

Output: arrayHello[0][0] = 1

arrayHello[0][1] = 2

arrayHello[0][2] = 3

arrayHello[1][0] = 2

arrayHello[1][1] = 3

arrayHello[1][2] = 4

arrayHello[2][0] = 3

arrayHello[2][1] = 4

arrayHello[2][2] = 5

arrayHello[3][0] = 4

data_type array_name [rows] [columns]

int hello [4] [3]

No of rows

Array name

(user define)

Data

Type

No of columns

Array name

(user define)

Data

Type

1

st

Row 2

nd

Row 3

rd

Row

arrayHello[3][1] = 5

arrayHello[3][2] = 6

4.1.6 Passing array to a function

Example:

include

void Helloarray (int marks [ ])

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

printf(“%d”, marks[i]);

int main()

int marks[5] = {45, 67, 34, 78, 90};

Helloarray(marks);

return 0;

Note: void Helloarray(int marks[ ])

Without return type function

4.1.7 Passing Array to a Functions as a pointer

Now, we will see how to pass an array to a function as a pointer.

include

void helloarray(char * marks)

printf(“Elements of array are:”);

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

printf(“%c”, marks[i])

int main()

char marks[5] = {‘A’, ‘B’, ‘C’, ‘D’, ‘E’};

helloarray(marks);

return 0;

Note:

Whenever you pass an array, it is always call by reference. In previous 2 programs, we passed an address & formal

argument in both the cases is a pointer internally.

data type

User

defined

function

User define

Array name

  1. int A[ ] [3] [2]; = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,};
  2. int A[2] [ ] [2]; = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,};
  3. int A[2] [3] [ ]; = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,};

valid

invalid

invalid

Note:

  • while declaring an array, it is mandatory to provide the size of each dimension. (3), (6), (10), (11), (12) are not providing

sizes of dimensions.

  • While initializing an array, you have flexibility to omit only first dimension i.e., you are allowed to other dimension (1),

(8),(14) are following this rule while (15), (16) are not following this rule.

4.1.9 Pointers

  • In C, there is a strong relationship between arrays and pointers. An operation that can be achieved by arrays subscripting

also be done with pointes.

  • Consider the declaration

int a[5] = {10, 20, 30, 40, 50};

int* Pa;

Pa = &a[0];

  • Pointers are special variable that can hold address of other variables

Syntax:

*int Pa:

data type * Identifier

Pa is a pointer to integer variable

i.e., Pa can hold address of integer variable

Pa contains address of a[0]

  • Two operators are important to understand for understanding pointers: &, *

i. &: address of operator

ii. *: value at operator

  • Pa is equivalent address 1020
  • Pa is equivalent to value at (Memory location 1020)

i,e *Pa is same as 10

  • Pa is pointing to same element of array, then by definition Pa +1 points to next element, Pa + i points to elements after i

elements before Pa.

i.e, In our example Pa points to a[0]

So, Pa+1 will point [1]

Pa+2 will point to a[2]

i,e

Pa+i is address of a[i]

 Pa + i  & a[i]

 *(Pa+i)  *& a[i]  a [i]

  • Array name always represent address of the very first element

i.e., Pa = &a[0];

and

Pa = a ;

both are same.

  • a[i]  *(a+i)  *(i + a)  i [a]

All are same and can be used interchangeably in program except in declaration.

  • In declaration, we can not write

int 3[a]; instead of int a[3]

  • Array name represent a constant address.

int a[10];

i. a++, ++a, – – a , a – – are all invalid as we cannot apply increment/decrement operator on constants:

ii. Array name cannot be Lvalue of on assignment statement.

i.e.

array_name = any expression/address/value is invalid

  • On the other hand, pointer being a variable, the following operations are valid.

int a[5]

int = *Pa;

Pa = a : valid

all arevalid

Pa+ + ;

Pa – – :

    • Pa :
  • – Pa :
  • Multi-level pointer

int x

int *P

int **q

x = 10

p = &x

q = &p

: x can store value

: p can store address of integer variable

: q can store address of pointer variable

: valid

: valid

: valid

p  1020 i, e address of x

*P  value at (memory location 1020)

*p  10

q  1096 i,e address of variable p

*q  value at (memory location 1096)

 1020 which is again an address

q  value at (memory address 1020)

**q  10

  1. Dangling pointer: The pointer pointing to a deallocated memory block is known as dangling pointer.

This situation raises an error known as dangling pointer problem. Dangling pointer occurs when a pointer pointing to a

variable goes out of scope or when a variables memory gets deallocated.

Consider the code.

int *f( ) {