Multiplication of 2D Array
Multiplication of 2D Array
Multiplication of 2D Array
12. using switch case enter 5 mark and find the grade?........................................16
14. what is linked list? explain the create , insert and delete ,
15. what is stack? what are the basic operation associated with stack?
16. write a algorithm for bubble sort and quick sort? Sort a sequence………….32
19.WHAT IS TOKEN?...............................................................................................41
1
20. Why C is called as middle-level
language?...................................42
21. Difference Between Algorithm and Flowchart?......................42
22. Define a binary tree and a binary search tree (BST). Explain the key
difference between these two types of binary trees.
*In the C programming language, there are several basic data types, broadly
categorized as follows:
A. Integer Types:
Used to store whole numbers without any fractional part.
Examples: int , short , long , char
int integerVariable = 42;
char charVariable = 'A';
B. Floating-point Types:
Used to store numbers with a fractional part.
Examples: float , double
float floatVariable = 3.14;
double doubleVariable = 2.71828;
C. Character Type:
Used to store individual characters.
Example: char char character = 'X';
D. Void Type:
Represents the absence of a type. Used in functions that do not return any
value.
Example: void functionWithoutReturnValue() {
// Code here
}
E. Derived Types:
Includes pointers, arrays, structures, and unions.
Pointer Type:
Used to store memory addresses.
Example: int *pointerVariable;
F. Array Type:
Used to store a collection of elements of the same data type.
4
Example: int numbers[5] = {1, 2, 3, 4, 5};
G. Structure Type:
Allows grouping of variables of different types under a single name.
Example: struct Point {
int x;
int y;
};
H. Union Type:
Similar to structures but shares the same memory for all members.
Example: union Shape {
int sides;
float radius;
};
These are the basic data types in C. The appropriate choice of data type depends on
the nature of the data you are working with and the requirements of your program.
2. waht is variable and constant? Explain the rules for naming a variable?
A.Variable:
A variable is a named storage location in the computer's memory where you
can store and manipulate data during the execution of a program.
The value stored in a variable can change during the execution of the
program.
Variables are declared with a specific data type, indicating the type of values
they can hold.
Examples: int age; // Declaration of an integer variable named 'age'
In this example, age is an integer variable that can store whole numbers.
B.Constant:
A constant is a value or an identifier that cannot be altered or modified
during the execution of a program.
Constants are used when you want to define a fixed value that remains
the same throughout the program.
In some programming languages, constants are declared using the
const keyword.
Examples:
const float PI = 3.14159; // Declaration of a constant named 'PI'
In this example, PI is a constant representing the mathematical
constant pi (π). Its value cannot be changed once it is assigned.
5
the other hand, a constant is a fixed value or identifier whose value remains
constant throughout the program, and it cannot be modified once
assigned. Using variables and constants appropriately helps make code
more readable, maintainable, and less error-prone.
*In most programming languages, including C, there are certain rules and
conventions to follow when naming variables. Adhering to these rules helps in
writing clean, readable, and maintainable code. Here are the common rules for
naming variables in C:
1. Valid Characters:
Variable names can consist of letters (both uppercase and lowercase),
digits, and underscores (_ ).
The first character must be a letter or an underscore.
2. Case Sensitivity:
C is a case-sensitive language, so uppercase and lowercase letters are
considered distinct. For example, myVariable and MyVariable are different
identifiers.
3. Length Limitations:
The length of a variable name is not fixed, but most compilers have
practical limits. It's advisable to keep variable names reasonably short
and meaningful.
4. Reserved Keywords:
Variable names cannot be the same as reserved keywords or keywords
in the programming language. Keywords are words with predefined
meanings and purposes in the language (e.g., int , if , else , etc.).
5. Meaningful Names:
Choose variable names that are descriptive and convey the purpose or
content of the variable. This enhances code readability.
Avoid using single-letter names for variables unless they are used as
loop counters (i , j , k ) or in certain contexts where their meaning is
clear.
6. CamelCase or Underscore Notation:
Coding conventions often recommend using either CamelCase or
underscore notation for multi-word variable names.
CamelCase: myVariableName
Underscore Notation: my_variable_name
7. Avoid Starting with Underscore:
Although it's technically allowed, it's common practice to avoid starting
variable names with an underscore, as such names are sometimes
reserved for system use.
6
float averageScore;
char first_name;
double totalAmount;
int 2ndPlace;
float average#Score;
char if;
By following these rules, you can create variable names that are easy to understand,
follow a consistent style, and reduce the likelihood of naming conflicts or errors in
your code.
Arithmetic Operators:
Used for basic mathematical calculations.
Examples: + (addition), - (subtraction), * (multiplication), / (division), %
(modulo, gives the remainder).
Relational Operators:
Used for comparing values and producing a Boolean result (true or false).
Examples: == (equal to), != (not equal to), < (less than), > (greater than), <= (less
than or equal to), >= (greater than or equal to).
Logical Operators:
Used for combining multiple conditions or evaluating the logical relationship
between expressions.
Examples: && (logical AND), || (logical OR), ! (logical NOT).
Assignment Operators:
7
Used to assign values to variables.
Examples: = (assign), += (add and assign), -= (subtract and assign), *= (multiply
and assign), /= (divide and assign), %= (modulo and assign).
Increment and Decrement Operators:
Used to increase or decrease the value of a variable by 1.
Examples: ++ (increment), -- (decrement).
Bitwise Operators:
Used to perform bit-level operations on integers.
Examples: & (bitwise AND), | (bitwise OR), ^ (bitwise XOR), ~ (bitwise NOT), <<
(left shift), >> (right shift).
These are some of the main types of operators in C. Understanding and using these
operators effectively is crucial for writing expressive and efficient code.
#include <stdio.h>
int main() {
} else {
8
return 0;
}
5.write a program to find factorial of a number?
#include <stdio.h>
// Function to calculate the factorial of a number
int calculateFactorial(int number) {
if (number == 0 || number == 1) {
return 1;
} else {
return number * calculateFactorial(number - 1);
}
}
int main() {
// Declare a variable to store the input number
int num;
// Prompt the user to enter a number
printf("Enter a number: ");
scanf("%d", &num);
// Check for negative input
if (num < 0) {
printf("Factorial is not defined for negative numbers.\n");
} else {
// Call the function to calculate factorial and print the result
printf("Factorial of %d is: %d\n", num, calculateFactorial(num));
}
return 0;
}
6. write a program to find Fibonacci series of a number?
#include <stdio.h>
// Function to generate and print Fibonacci series up to n
void generateFibonacci(int n) {
int firstTerm = 0, secondTerm = 1, nextTerm;
printf("Fibonacci series up to %d terms: ", n);
for (int i = 1; i <= n; ++i) {
printf("%d, ", firstTerm);
nextTerm = firstTerm + secondTerm;
firstTerm = secondTerm;
secondTerm = nextTerm;
}
printf("\n");
}
int main() {
9
// Declare a variable to store the number of terms in the Fibonacci series
int terms;
// Prompt the user to enter the number of terms
printf("Enter the number of terms for Fibonacci series: ");
scanf("%d", &terms);
// Check for non-positive input
if (terms <= 0) {
printf("Number of terms should be a positive integer.\n");
} else {
// Call the function to generate Fibonacci series and print the result
generateFibonacci(terms);
}
return 0;
}
7.write a program to check palindrome number or not.
#include <stdio.h>
// Function to check if a number is a palindrome
int isPalindrome(int num) {
int originalNum = num, reversedNum = 0, remainder;
// Reverse the number
while (num > 0) {
remainder = num % 10;
reversedNum = reversedNum * 10 + remainder;
num /= 10;
}
// Check if the reversed number is equal to the original number
if (originalNum == reversedNum) {
return 1; // It's a palindrome
} else {
return 0; // It's not a palindrome
}
}
int main() {
// Declare a variable to store the input number
int num;
// Prompt the user to enter a number
printf("Enter a number: ");
scanf("%d", &num);
// Call the function to check if the number is a palindrome
if (isPalindrome(num)) {
printf("%d is a palindrome.\n", num);
} else {
printf("%d is not a palindrome.\n", num);
}
10
return 0;
}
8. 1
12
123 write a program to create a number triangle.
1234
12345
#include <stdio.h>
int main() {
int rows;
// Prompt the user to enter the number of rows
scanf("%d", &rows);
// Loop to print the pattern
for (int i = 1; i <= rows; ++i) {
// Print numbers from 1 to i in each row
for (int j = 1; j <= i; ++j) {
printf("%d ", j);
}
// Move to the next line after each row
printf("\n");
}
return 0;
}
Let's consider a simple example to explain how an array stores variables in memory.
Suppose we have an array of integers:
Here, numbers is an array that can hold five integers. The diagram below illustrates
how this array is stored in memory:
-------------------------------------------------
| 10 | 20 | 30 | 40 | 50 | ... | ... |
-------------------------------------------------
^ ^ ^ ^ ^ ^
| | | | | |
11
0th 1st 2nd 3rd 4th 5th.
Each box represents a memory location
The array numbers is stored in a contiguous block of memory.
The indices (0th, 1st, 2nd, etc.) represent the position of each element in the
array.
In this example, numbers[0] is 10, numbers[1] is 20, and so on.
The size of the array is fixed, and each element can be accessed using its
index.
When you declare an array, the compiler allocates a block of memory to store all
elements, and each element is stored at a specific memory location based on its
index. The diagram provides a visual representation of how the values are stored in
memory.
Accessing elements in an array is done by using the array name followed by the
index in square brackets, like numbers[2] to access the third element. Arrays are widely
used in programming to handle collections of data efficiently.
10. multiplication of 2D array ?
Multiplying two matrices (2D arrays) involves multiplying each element of the
resulting matrix by performing a dot product of the corresponding row and column
elements of the input matrices. Here's an algorithm to multiply two 2D arrays:
Let's assume we have two matrices A and B, and we want to calculate the product C
= A * B.
a. Set C[i][j] to the sum of the products of the corresponding elements in the ith
row of matrix A and jth column of matrix B.
Coding:
#include <stdio.h>
12
void multiplyMatrices(int A[][3], int B[][2], int result[][2], int m, int n, int p) {
result[i][j] = 0;
int main() {
int result[2][2];
int m = 2, n = 3, p = 2;
printf("%d\t", result[i][j]);
printf("\n");
return 0;
In this example, A is a 2x3 matrix, B is a 3x2 matrix, and the product C will be a 2x2
matrix. The multiplyMatrices function calculates the matrix product according to the
algorithm.
#include <stdio.h>
#include <string.h>
int start = 0;
// Continue comparing characters from both ends until they meet in the middle
// If characters at both ends are not the same, the string is not a palindrome
if (str[start] != str[end]) {
14
return 0; // Not a palindrome
start++;
end--;
int main() {
char input[100];
scanf("%s", input);
if (isPalindrome(input)) {
} else {
return 0;
12. using switch case enter 5 mark and find the grade?.
15
#include <stdio.h>
int main() {
int marks[5];
int totalMarks = 0;
printf("Enter 5 marks:\n");
scanf("%d", &marks[i]);
totalMarks += marks[i];
char grade;
16
switch ((int)average / 10) {
case 9:
case 10:
grade = 'A';
break;
case 8:
grade = 'B';
break;
case 7:
grade = 'C';
break;
case 6:
grade = 'D';
break;
default:
grade = 'F';
break;
return 0;
Structure:
1. Memory Allocation:
In a structure, each member has its own memory space.
The memory required for a structure is the sum of the memory
required for each member.
2. Usage:
Members in a structure are independent of each other.
Structures are typically used when you want to represent a collection of
related but distinct pieces of information.
3. Example:
struct Point {
int x;
int y;
};
p1.x = 5;
p1.y = 10;
1. In this example, struct Point defines a structure with two members, x and y ,
representing the coordinates of a point in 2D space.
Union:
1. Memory Allocation:
In a union, all members share the same memory space.
The memory required for a union is the maximum memory required by
any of its members.
2. Usage:
18
Members in a union are mutually exclusive. Only one member can
contain a value at a time.
Unions are typically used when you want to represent a situation where
only one piece of information is relevant or valid at a given time.
3. Example:
union Number {
int intValue;
float floatValue;
};
num.intValue = 42;
// Now, num.floatValue should not be used as the intValue has been set
14. what is linked list? explain the create , insert and delete , display operation
in double linked list?
Create Operation:
To create a doubly linked list, you typically start with an empty list and add
nodes as needed.
Each node in the list contains data and two pointers, one pointing to the next
node and another pointing to the previous node.
struct Node {
int data;
};
if (newNode == NULL) {
exit(1);
newNode->data = data;
newNode->next = NULL;
newNode->prev = NULL;
return newNode;
Insert Operation:
Insertion in a doubly linked list can occur at the beginning, end, or any
position in between.
For insertion, you need to update the next and prev pointers of the
neighboring nodes.
Example insert operation (insert at the beginning):
if (*head != NULL) {
(*head)->prev = newNode;
newNode->next = *head;
*head = newNode;
if (*head == NULL) {
*head = newNode;
return;
temp = temp->next;
temp->next = newNode;
newNode->prev = temp; }
if (position < 1) {
printf("Invalid position.\n");
return;
if (position == 1) {
insertAtBeginning(head, data);
return;
temp = temp->next;
if (temp == NULL) {
return;
newNode->next = temp->next;
newNode->prev = temp;
if (temp->next != NULL) {
temp->next->prev = newNode;
temp->next = newNode;
Delete Operation:
Deletion in a doubly linked list can occur from the beginning, end, or any
given position.
For deletion, you need to update the next and prev pointers of the
neighboring nodes.
Example delete operation (delete from the beginning):
if (*head == NULL) {
return;
if (*head != NULL) {
(*head)->prev = NULL;
free(temp);
if (*head == NULL) {
return;
temp = temp->next;
if (temp->prev != NULL) {
temp->prev->next = NULL;
} else {
*head = NULL;
free(temp);
23
Example delete operation (delete from a given position):
if (*head == NULL) {
return;
if (position < 1) {
printf("Invalid position.\n");
return;
temp = temp->next;
if (temp == NULL) {
return;
if (temp->prev != NULL) {
temp->prev->next = temp->next;
} else { *}
15. what is stack? what are the basic operation associated with stack? Convert
infix to postfix.
A stack is a linear data structure that follows the Last In, First Out (LIFO) principle. In a
stack, elements are added and removed from the same end, which is often referred to as the
24
"top" of the stack. The most recent element added to the stack is the first one to be removed.
Common real-life examples of stacks include a stack of plates, a call stack in programming,
and the back and forward buttons in a web browser.
1. Push:
The push operation is used to add an element to the top of the stack.
The element is placed on the top, becoming the new top element.
2. Pop:
The pop operation is used to remove the element from the top of the stack.
The top element is removed, and the element below it becomes the new top
element.
3. Peek (or Top):
The peek operation retrieves the element from the top of the stack without
removing it.
It allows you to view the top element without modifying the stack.
4. isEmpty:
The isEmpty operation checks whether the stack is empty.
It returns true if the stack has no elements and false otherwise.
5. isFull:
In some implementations, the isFull operation checks whether the stack is full
(reached its maximum capacity).
It returns true if the stack is full and false otherwise.
6. Size:
The size operation returns the number of elements currently in the stack.
Implementation of Stack:
In programming, a stack can be implemented using arrays or linked lists. Here is a simple
example of a stack implemented using an array in C:
Cording
#include <stdio.h>
#include <stdbool.h>
struct Stack {
int items[MAX_SIZE];
int top;
};
if (isFull(stack)) {
return;
stack->items[++stack->top] = value;
if (isEmpty(stack)) {
return stack->items[stack->top--];
if (isEmpty(stack)) {
return stack->items[stack->top];
return stack->top + 1;
int main() {
initialize(&myStack);
push(&myStack, 10);
push(&myStack, 20);
push(&myStack, 30);
return 0;
In this example, the struct Stack represents a stack using an array. The basic stack
operations are implemented as functions, and the main function demonstrates their
usage.
27
Converting an infix expression to postfix involves using a stack to keep track of
operators and ensuring the correct order of operators in the postfix expression. The
algorithm typically involves scanning the infix expression from left to right and using
a stack to manage operators. Here's a simple C program to convert an infix
expression to postfix:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct Stack {
int top;
unsigned capacity;
char* array;
};
if (!stack) {
stack->top = -1;
stack->capacity = capacity;
if (!stack->array) {
28
return stack;
stack->array[++stack->top] = item;
if (!isEmpty(stack)) {
return stack->array[stack->top--];
switch (operator) {
case '+':
case '-':
return 1;
case '*':
case '/':
29
return 2;
case '^':
return 3;
default:
return -1;
int i, j;
if (isalnum(infix[i])) {
printf("%c", infix[i]);
push(stack, infix[i]);
printf("%c", pop(stack));
printf("Invalid expression\n");
return;
} else {
pop(stack);
30
}
} else {
printf("%c", pop(stack));
push(stack, infix[i]);
while (!isEmpty(stack)) {
printf("%c", pop(stack));
int main() {
char infixExpression[100];
scanf("%s", infixExpression);
infixToPostfix(infixExpression);
return 0;
This program reads an infix expression from the user, converts it to a postfix
expression, and then prints the postfix expression. The algorithm uses a stack to
handle operators and follows the rules of precedence and associativity to produce
the correct postfix expression.
16. write a algorithm for bubble sort and quick sort ? Sort a sequence.
31
Bubble Sort Algorithm:
Bubble Sort is a simple sorting algorithm that repeatedly steps through the list,
compares adjacent elements, and swaps them if they are in the wrong order. The
pass through the list is repeated until the list is sorted.
1. Start from the first element (index 0) and compare it with the next element.
3. Move to the next pair of elements and repeat step 2 until the end of the list is reached.
4. Repeat steps 1-3 for each element in the list until no more swaps are needed (i.e., the list is
sorted).
2. Partition the other elements into two sub-arrays: elements less than the pivot and elements
greater than the pivot.
4. Combine the sorted sub-arrays and the pivot to get the final sorted list.
32
void bubbleSort(int arr[], int n) {
arr[j + 1] = temp;
int main() {
bubbleSort(arr, n);
return 0;
33
}
Quick Sort Implementation in C:
#include <stdio.h>
int i = low - 1;
i++;
arr[i] = arr[j];
arr[j] = temp;
// Swap arr[i+1] and arr[high] (put the pivot in its correct place)
arr[i + 1] = arr[high];
arr[high] = temp;
return i + 1;
34
// Find pivot such that elements smaller than pivot are on the left and greater are on the
right
int main() {
quickSort(arr, 0, n - 1);
return 0;
Sort a sequence
Certainly! Sorting a sequence involves arranging its elements in a specific order, such
as ascending or descending. I'll provide a simple example of sorting an array of
integers in ascending order using the Bubble Sort algorithm in C:
35
#include <stdio.h>
arr[j + 1] = temp;
int main() {
bubbleSort(arr, n);
return 0;
This program uses the Bubble Sort algorithm to sort an array of integers in ascending
order. You can replace the input array with your sequence, and the algorithm will
rearrange the elements in ascending order.
There are various searching algorithms, each with its own approach and efficiency.
Two common searching algorithms are linear search and binary search.
1. Linear Search:
Linear search is a simple searching algorithm that checks each element in the
collection until the target item is found or the entire collection is traversed. It is
suitable for unordered lists.
#include <stdio.h>
37
if (arr[i] == target) {
int main() {
if (result != -1) {
} else {
return 0;
2. Binary Search:
1. Compare the target value with the middle element of the list.
2. If the target matches the middle element, return its index.
3. If the target is less than the middle element, repeat the search in the left half
of the list.
38
4. If the target is greater than the middle element, repeat the search in the right
half of the list.
5. Continue dividing the search interval until the target is found or the interval
becomes empty.
#include <stdio.h>
if (arr[mid] == target) {
} else {
int main() {
39
if (result != -1) {
} else {
return 0; }
18. what is binary . explain the inorder , pre order , post order traversed of a
binary tree?
A binary tree is a hierarchical data structure composed of nodes, where each node
has at most two children, which are referred to as the left child and the right child.
Binary trees are used in various applications, including computer science, data
processing, and artificial intelligence.
In the context of binary trees, there are three main ways to traverse or visit the
nodes:
1.Inorder Traversal:
In inorder traversal, the left subtree is visited first, followed by the root,
and then the right subtree.
For a binary search tree (BST), inorder traversal results in sorted order
of the elements.
EXAMPLE:
Inorder Traversal: 1 2 3 4 5 6 7
2.Preorder Traversal:
In preorder traversal, the root is visited first, followed by the left subtree, and
then the right subtree.
This traversal is often used to create a copy of the tree.
Preorder: Root -> Left -> Right
40
EXAMPLE:
Preorder Traversal: 4 2 1 3 6 5 7
3.Postorder Traversal:
In postorder traversal, the left subtree is visited first, followed by the right
subtree, and then the root.
This traversal is often used to delete nodes in a tree.
Postorder: Left -> Right -> Root
EXAMPLE:
Postorder Traversal: 1 3 2 5 7 6 4
These traversals are recursive in nature and can be implemented using recursive
functions. In each traversal, every node in the tree is visited exactly once. The order in
which nodes are visited depends on the specific traversal method chosen. Each
traversal has its own use cases based on the requirements of the application.
19.WHAT IS TOKEN?
In C, a token is the smallest unit in the source code that has significance. The C
compiler recognizes various types of tokens, and each plays a specific role in the
syntax and semantics of the programming language. The basic types of tokens in C
include:
1. Keywords:
Keywords are reserved words in C that have special meanings.
Examples include int, if , else , while, for , etc.
2. Identifiers:
Identifiers are names given to various program elements such as
variables, functions, arrays, etc. Identifiers must follow certain naming
conventions and rules.
3. Constants:
Constants represent fixed values in the program. There are various
types of constants, including integer constants ( 10 , 42 ), floating-point
constants (3.14, 2.0 ), character constants ('A' , '5' ), and string literals
("Hello" ).
4. String Literals:
String literals represent sequences of characters enclosed in double
quotes, like "Hello, World!" .
5. Operators:
Operators perform operations on variables and values. Examples
include arithmetic operators (+ , - , * , / ), relational operators (< , > , == , != ),
and logical operators (&& , || , ! ).
6. Punctuation Symbols:
41
Punctuation symbols include various symbols used in the C language.
Examples include semicolon ; , comma , , parentheses () , braces {} , and
square brackets [] .
7. Special Symbols:
Special symbols include symbols with specific meanings in C. Examples
include the ampersand & (address-of), asterisk * (dereference or
multiplication), and hash # (used in preprocessor directives).
8. Comments:
Comments are not actual tokens in the sense that they are not
processed by the compiler. They are used to add explanatory notes in
the code. There are two types of comments in C: single-line (// ) and
multi-line (/* ... */ ).
20. Why C is called as middle-level language?
An algorithm and a flowchart are both tools used in computer science and
programming, but they serve different purposes.
Algorithm:
42
It provides a graphical representation of the steps in a process, making it easier to
understand and communicate the logic of an algorithm.
Flowcharts use different shapes to represent different types of steps (e.g., rectangles
for processes, diamonds for decisions).
22. Define a binary tree and a binary search tree (BST). Explain the key
difference between these two types of binary trees. Provide a simple example
to illustrate the distinction.
A binary tree is a hierarchical data structure in which each node has at most two
children, referred to as the left child and the right child. Nodes in a binary tree can
have zero, one, or two children. The topmost node in a binary tree is called the root,
and nodes with no children are called leaves.
A binary search tree (BST) is a special type of binary tree where the values of the
nodes follow a specific ordering property. The key difference between a binary tree
and a binary search tree is that in a binary search tree, for each node, all nodes in its
left subtree have values less than or equal to the node's value, and all nodes in its
right subtree have values greater than the node's value.
1. All nodes in the left subtree of 'n' have values less than or equal to the value
of 'n'.
2. All nodes in the right subtree of 'n' have values greater than the value of 'n'.
Here's a simple example to illustrate the distinction:
Function in Programming:
User-Defined Functions:
Examples:
44
return a + b;
Availability: These functions are available for use without requiring the
programmer to implement their logic.
Examples:
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
Recursive Function:
45
Solving Complex Problems: Recursive functions are often used to simplify
the solution of complex problems by breaking them down into smaller,
more manageable subproblems.
Base Case:
Every recursive function needs a base case, which is the condition that
determines when the function stops calling itself. It prevents the recursion
from continuing indefinitely. The base case provides the result for the
smallest or simplest input.
Recursive Case:
The recursive case is where the function calls itself with a modified or
reduced version of the original problem. This step is crucial for breaking
down the larger problem into smaller, more manageable instances.
csharp
0! = 1 base case
46
Here, the base case is
n! in terms of
1)
Example Code:
#include <stdio.h>
int factorial(int n) {
// Base case
if (n == 0) {
return 1;
// Recursive case
else {
47
}
int main() {
return 0;
In this example, the factorial function calls itself with a smaller input (
0!), at which point the recursion stops, and the results are
calculated backward.
Definition:
Syntax:
data_type array_name[size];
Example:
48
int numbers[5] = {1, 2, 3, 4, 5};
Explanation:
This declares an integer array named numbers with a size of 5. The array is
initialized with the values 1, 2, 3, 4, and 5.
Definition:
Syntax:
data_type array_name[row_size][column_size];
Example:
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Explanation:
This declares a 3x3 integer matrix named matrix and initializes it with values
in a row-major order. The matrix looks like:
123
456
789
Key Differences:
49
Dimension:
Declaration:
1D Array: Declared with a single set of square brackets specifying the size.
2D Array: Declared with two sets of square brackets specifying the row and
column sizes.
Accessing Elements:
Initialization:
Representation:
Example Code:
#include <stdio.h>
int main() {
// 1D Array
// 2D Array
50
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Accessing elements
return 0;
In this method, you specify the size of the array in the function parameter.
#include <stdio.h>
printf("\n");
int main() {
return 0;
In this method, you use a pointer to represent the array, and you pass the
size of the array separately.
#include <stdio.h>
52
// For example, print each element
printf("\n");
int main() {
// Call the function and pass the array and its size
return 0;
Both methods achieve the same result, and the choice between them
depends on your preference and the specific requirements of your
program. In both cases, the array's base address (memory location of the
first element) is passed to the function, allowing the function to access and
modify the array.
Call by Value:
Definition:
In Call by Value, the actual value of the argument is passed to the function.
53
The function works with a copy of the data, and any modifications made to
the parameter inside the function do not affect the original data.
Implementation:
Basic data types (int, float, char) are usually passed by value.
Example:
#include <stdio.h>
void square(int x) {
x = x * x;
int main() {
int num = 5;
square(num);
return 0;
Output:
bash
Inside function: 25
Outside function: 5
Call by Reference:
54
Definition:
The function can directly access and modify the original data stored at that
memory location.
Implementation:
Example:
#include <stdio.h>
*x = (*x) * (*x);
int main() {
int num = 5;
squareByReference(&num);
return 0;
Output:
bash
55
Inside function: 25
Outside function: 2
56
Examples include pointers and functions like malloc, calloc,
realloc, and free.
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
if (arr == NULL) {
return 1;
return 0;
57
}
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
if (arr == NULL) {
return 1;
return 0;
Example:
58
#include <stdio.h>
#include <stdlib.h>
int main() {
if (arr == NULL) {
return 1;
if (arr == NULL) {
return 1;
return 0;
59
Example: (Refer to examples above for usage)
Example:
#include <stdio.h>
int main() {
return 0;
60
}
You can add or subtract an integer value from a pointer, adjusting its
address based on the size of the data type it points to.
Example:
#include <stdio.h>
int main() {
return 0;
Subtraction of Pointers:
Example:
#include <stdio.h>
int main() {
61
int *ptr1 = &arr[2];
return 0;
Pointers can be used to access array elements by using the array indexing
syntax.
Example:
#include <stdio.h>
int main() {
// Output: 10 20 30 40 50
return 0;
Advantages of a Stack:
62
Memory Efficiency:
Ease of Reversal:
Disadvantages of a Stack:
Lack of Flexibility:
Some operations are less efficient than with other data structures,
particularly when dealing with arbitrary insertions and deletions.
Advantages of a Stack:
Simple Implementation:
63
Stack operations are straightforward to implement.
Memory Efficiency:
Ease of Reversal:
Disadvantages of a Stack:
Lack of Flexibility:
Some operations are less efficient than with other data structures,
particularly when dealing with arbitrary insertions and deletions.
64
In data structures, a queue is a linear data structure that follows the First In,
First Out (FIFO) principle. This means that the first element added to the
queue is the first one to be removed. Think of a queue like a line of people
waiting for a service; the person who arrives first is served first.
Principles of a Queue:
Enqueue (Insertion):
Syntax: enqueue(element)
Effect: The queue grows, and the new element becomes the last one.
Dequeue (Deletion):
Syntax: dequeue()
Effect: The front element is taken off, and the queue shrinks.
Syntax: front()
Syntax: rear()
isEmpty:
65
Checking if the queue is empty.
Syntax: isEmpty()
Syntax: isFull()
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 5
struct Queue {
int arr[MAX_SIZE];
};
queue->front = -1;
queue->rear = -1;
66
int isEmpty(struct Queue *queue) {
if (isFull(queue)) {
} else {
if (isEmpty(queue)) {
queue->arr[queue->rear] = element;
67
int dequeue(struct Queue *queue) {
if (isEmpty(queue)) {
} else {
if (queue->front == queue->rear) {
} else {
return dequeuedElement;
if (isEmpty(queue)) {
printf("Queue is empty.\n");
} else {
return queue->arr[queue->front];
68
}
if (isEmpty(queue)) {
printf("Queue is empty.\n");
} else {
return queue->arr[queue->rear];
int main() {
initialize(&myQueue);
enqueue(&myQueue, 10);
enqueue(&myQueue, 20);
enqueue(&myQueue, 30);
dequeue(&myQueue);
dequeue(&myQueue);
69
return 0;
35. What are the different types of Queues available? Explain each with
suitable examples.’
A full binary tree is a binary tree in which each node has either 0 or 2
children. In other words, every node in a full binary tree has either 0
children (a leaf node) or two children. No node in a full binary tree has only
one child.
Node Structure:
Depth Levels:
All leaves (nodes with no children) are at the same level, and all non-leaf
nodes have exactly two children.
Examples:
Examples of full binary trees include complete binary trees, perfect binary
trees, and degenerate (or pathological) trees.
A complete binary tree is a binary tree in which all levels are completely
filled, except possibly for the last level, which is filled from left to right. In
other words, a complete binary tree is one where all nodes are as left as
possible.
Node Structure:
70
All levels are completely filled except possibly for the last level, which is
filled from left to right.
Leftmost Positioning:
Examples:
Heaps (like binary heaps) are often implemented as complete binary trees.
Complete binary trees are commonly used in data structures.
A full binary tree is a binary tree in which each node has either 0 or 2
children. In other words, every node in a full binary tree has either 0
children (a leaf node) or two children. No node in a full binary tree has only
one child.
Node Structure:
Depth Levels:
All leaves (nodes with no children) are at the same level, and all non-leaf
nodes have exactly two children.
Examples:
Examples of full binary trees include complete binary trees, perfect binary
trees, and degenerate (or pathological) trees.
A complete binary tree is a binary tree in which all levels are completely
filled, except possibly for the last level, which is filled from left to right. In
71
other words, a complete binary tree is one where all nodes are as left as
possible.
Node Structure:
All levels are completely filled except possibly for the last level, which is
filled from left to right.
Leftmost Positioning:
Examples:
Heaps (like binary heaps) are often implemented as complete binary trees.
Complete binary trees are commonly used in data structures.
Balance Factor
If the balance factor is -1, it means the right subtree is taller by 1 level.
72
If the balance factor is 0, it means the left and right subtrees have the same
height.
The AVL tree is a self-balancing binary search tree, and maintaining balance
is crucial to ensure efficient search, insert, and delete operations. The
balance factor helps in determining the balance of a node, and the AVL tree
uses rotations to restore balance when it is disturbed due to insertions or
deletions.
In an AVL tree, the balance factor of every node must be in the range
markdown
/\
2 7
73
/ /\
1 5 8
In this AVL tree, the balance factor for each node is:
Balance Factor of 3:
Balance Factor of 7:
74
2
Both Breadth-First Search (BFS) and Depth-First Search (DFS) are traversal
algorithms used to explore and visit nodes in a binary tree. However, they
differ in the order in which they visit nodes and the data structures they use
for implementation.
Order of Visit:
BFS visits nodes level by level, starting from the root and moving to the
next level before going deeper.
Order of Visit:
Data Structure:
Traversal Approach:
Memory Usage:
Order of Visit:
Structure:
Traversal Approach:
75
Visits all nodes at a particular level before moving on to the next level.
Implementation:
Memory Usage:
Requires more memory as it needs to store all nodes at the current level in
the queue.
Applications:
Order of Visit:
DFS visits nodes by going as deep as possible along each branch before
backtracking.
Data Structure:
Uses a stack (or recursion, which implicitly uses the call stack) to keep track
of the nodes to be visited.
Traversal Approach:
Implementation:
Memory Usage:
Generally uses less memory than BFS as it only needs to store the nodes
along the current path.
Applications:
76
Useful for topological sorting, cycle detection, and solving problems with
solutions that require backtracking.
markdown
/\
2 3
/\
4 5
12345
DFS Traversals:
12453
42513
45231
In summary, BFS explores level by level, using a queue, while DFS explores
as deeply as possible, using a stack or recursion. Each has its own strengths
and use cases, and the choice between them depends on the specific
problem and the requirements of the solution.
77
34. What do you mean by Queue in Data structure? Discuss the
principles and operations involved in queue?.....................................65
78