Multiplication of 2D Array

Download as pdf or txt
Download as pdf or txt
You are on page 1of 78

1. define keyword and identifier in c ? what is datatype ?

explain the different


data types with examples?..........................................................................................3
2. waht is variable and constant? Explain the rules for naming a variable?
A.Variable: …………………………………………………………………………………….…….5

3.explain different types of operators used in c , with example?...........................7

4.write a program to find the larger number among 3 number?...........................8


5.write a program to find factorial of a number?.....................................................9
6. write a program to find Fibonacci series of a number?.......................................9
7.write a program to check palindrome number or not………………………………10
8. 1
12
123 write a program to create a number triangle………………….11
1234
12345
9.what is array? explain with suitable diagram to store variable in memory..…11
10. multiplication of 2D array
?............................................................................................12

11. write a program to find string is palindrome or not?......................................14

12. using switch case enter 5 mark and find the grade?........................................16

13. difference between structure and union with example?................................18

14. what is linked list? explain the create , insert and delete ,

display operation in double linked list?.................................................................19

15. what is stack? what are the basic operation associated with stack?

Convert infix to postfix……………………………………………………………….……25

16. write a algorithm for bubble sort and quick sort? Sort a sequence………….32

17. what is searching? explain detail with suitable example?...............................37

18. what is binary . explain the inorder , pre order ,

post order traversed of a binary tree?.....................................................................40

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.

Provide a simple example to illustrate the distinction……………………….……….43

23.what is the need of operator precedence?..........................................44

24. What do you mean by a function in the programming language?


Differentiate between user-defined and pre-defined functions……….44

25. What do you mean by recursive function? Explain need and


working principle of recursive function……………………………………….46

26. Differentiate between 1D array vs 2D array.

(Definition, syntax & example must be included)………………………….48

27. What do you mean by passing array to function?

Explain the methods to declare a function that receives an


array as an argument……………………………………………………….51

28. Differentiate between call by value vs call by reference…………….54

29.Differentiate between static memory allocation

vs Dynamic memory allocation………………………………………….56

30. What do you mean by dynamic memory allocation? Explain………57


different types of functions available for DMA with suitable examples?

31. What is pointer? Explain different types of pointer arithmetic


operations in c with suitable examples?...................................................60

32. Differentiate between push() and pop() in stack………………………63

33. How to implement a stack? Write advantages and dis


advantages of stack…………………………………………………………64
2
0.What is c programming language?

The C programming language is a general-purpose, procedural programming


language created by Dennis Ritchie in the early 1970s at Bell Labs. C is one of the
most influential programming languages and has been widely used for developing
software, including operating systems, compilers, and application software.

Key features and characteristics of the C language include:

1. Procedural Programming: C follows a procedural programming paradigm,


which means it focuses on functions and procedures that manipulate data.
2. Low-Level Programming: C provides low-level access to memory, allowing
for efficient manipulation of hardware and system resources. This makes it
suitable for systems programming and developing operating systems.
3. Portability: C code can be compiled to run on different platforms with
minimal modification. This portability has contributed to the widespread use
of C in cross-platform development.
4. Efficiency: C is known for its efficiency and performance. It allows for direct
manipulation of memory and provides features like pointers, which give
developers fine control over system resources.
5. Structured Programming: C supports structured programming principles,
allowing for the organization of code into functions, modules, and blocks. This
enhances code readability and maintainability.
6. Standard Libraries: C comes with standard libraries that provide a set of
functions for common tasks, such as input/output operations, string
manipulation, and mathematical operations.
7. Influence on Other Languages: Many modern programming languages, such
as C++, C#, and Objective-C, have been influenced by or directly derived from
C.
1. define keyword and identifier in c ? what is datatype ? explain the different
data types with examples?
I. Keyword:
 Keywords in C are reserved words that have predefined meanings in
the language.
 These words cannot be used as identifiers (variable names, function
names, etc.) because they are reserved for specific purposes in the
language.
 Examples of keywords in C include int , float , if , else , while , for , return ,
and so on.
II. Identifier:
 Identifiers are names given to various program elements such as
variables, functions, arrays, etc., in C.
3
 Rules for naming identifiers in C:
 An identifier must begin with a letter (uppercase or lowercase) or
an underscore _ .
 After the first character, it can contain letters, digits, or
underscores.
 C is case-sensitive, so myVariable and MyVariable are considered
different identifiers.
 The length of an identifier is not fixed; however, most compilers
have limits on the length.
*In programming, a data type is a classification that specifies which type of value
a variable can hold. It defines the operations that can be performed on the data,
the meaning of the data, and the way the values of that type can be stored.
Different programming languages support various data types, and each type has
its own set of rules for operations.

*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'

age = 25; // Assignment of a value to the 'age' variable

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.

In summary, a variable is a storage location that can hold varying data


values, and its content can be changed during the program's execution. On

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.

Examples of valid variable names: int age;

6
float averageScore;

char first_name;

double totalAmount;

Examples of invalid variable names: // Invalid: Starts with a digit

int 2ndPlace;

// Invalid: Contains invalid character #

float average#Score;

// Invalid: Reserved keyword

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.

3.explain different types of operators used in c , with example?


ANS: Operators in C are symbols that represent computations or operations on
variables and values. They allow you to perform various tasks, such as arithmetic
calculations, logical comparisons, and bit manipulations. Here are the main types of
operators in C:

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.

4.write a program to find the larger number among 3 number?

#include <stdio.h>

int main() {

// Declare three variables to store input numbers

int num1, num2, num3;

// Prompt the user to enter three numbers

printf("Enter three numbers: ");

scanf("%d %d %d", &num1, &num2, &num3);

// Check and find the largest number

if (num1 >= num2 && num1 >= num3) {

printf("The largest number is: %d\n", num1);

} else if (num2 >= num1 && num2 >= num3) {

printf("The largest number is: %d\n", num2);

} else {

printf("The largest number is: %d\n", num3);

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;
}

9.what is array? explain with suitable diagram to store variable in memory.


An array is a data structure that allows you to store multiple values of the same
data type under a single name. Each value in an array is called an element, and
each element is identified by its index or position within the array. Arrays provide
a convenient way to work with collections of data in programming.

Let's consider a simple example to explain how an array stores variables in memory.
Suppose we have an array of integers:

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

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.

Algorithm: Matrix Multiplication

Input: Two matrices A and B of sizes m x n and n x p, respectively.

Output: The product matrix C of size m x p.

1. Initialize a result matrix C of size m x p with all elements set to 0.

2. For each element C[i][j] in the result matrix:

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.

3.Return the resulting matrix C.

Coding:

#include <stdio.h>

12
void multiplyMatrices(int A[][3], int B[][2], int result[][2], int m, int n, int p) {

// Initialize the result matrix with zeros

for (int i = 0; i < m; ++i) {

for (int j = 0; j < p; ++j) {

result[i][j] = 0;

// Perform matrix multiplication

for (int i = 0; i < m; ++i) {

for (int j = 0; j < p; ++j) {

for (int k = 0; k < n; ++k) {

result[i][j] += A[i][k] * B[k][j];

int main() {

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

int B[3][2] = {{7, 8}, {9, 10}, {11, 12}};

int result[2][2];

int m = 2, n = 3, p = 2;

multiplyMatrices(A, B, result, m, n, p);

// Print the result matrix

printf("Resultant Matrix (C = A * B):\n");


13
for (int i = 0; i < m; ++i) {

for (int j = 0; j < p; ++j) {

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.

11. write a program to find string is palindrome or not?

#include <stdio.h>

#include <string.h>

// Function to check if a string is a palindrome

int isPalindrome(char str[]) {

int length = strlen(str);

// Initialize pointers to the beginning and end of the string

int start = 0;

int end = length - 1;

// Continue comparing characters from both ends until they meet in the middle

while (start < end) {

// 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

// Move the pointers towards the center

start++;

end--;

// If the loop completes without returning, the string is a palindrome

return 1; // It's a palindrome

int main() {

// Declare an array to store the input string

char input[100];

// Prompt the user to enter a string

printf("Enter a string: ");

scanf("%s", input);

// Call the function to check if the string is a palindrome

if (isPalindrome(input)) {

printf("%s is a palindrome.\n", input);

} else {

printf("%s is not a palindrome.\n", input);

return 0;

12. using switch case enter 5 mark and find the grade?.
15
#include <stdio.h>

int main() {

// Declare variables to store 5 marks

int marks[5];

int totalMarks = 0;

// Prompt the user to enter 5 marks

printf("Enter 5 marks:\n");

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

printf("Mark %d: ", i + 1);

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

// Add the entered mark to the total

totalMarks += marks[i];

// Calculate the average

float average = (float)totalMarks / 5;

// Determine the grade based on the average using a switch statement

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;

// Print the average and corresponding grade

printf("Average: %.2f\n", average);

printf("Grade: %c\n", grade);

return 0;

13. difference between structure and union with example?


17
In C, both structures and unions are used to group different data types under a
single name. However, they have some key differences in terms of memory allocation
and usage.

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:

// Define a structure representing a point in 2D space

struct Point {

int x;

int y;

};

// Declare a variable of the Point structure

struct Point p1;

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:

// Define a union representing a variable that can be an integer or a float

union Number {

int intValue;

float floatValue;

};

// Declare a variable of the Number union

union Number num;

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;

struct Node* next;

struct Node* prev;

};

Example create operation:


19
struct Node* createNode(int data) {

struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

if (newNode == NULL) {

// Handle memory allocation failure

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):

void insertAtBeginning(struct Node** head, int data) {

struct Node* newNode = createNode(data);

if (*head != NULL) {

(*head)->prev = newNode;

newNode->next = *head;

*head = newNode;

Example insert operation (insert at the end):


20
void insertAtEnd(struct Node** head, int data) {

struct Node* newNode = createNode(data);

struct Node* temp = *head;

if (*head == NULL) {

*head = newNode;

return;

while (temp->next != NULL) {

temp = temp->next;

temp->next = newNode;

newNode->prev = temp; }

Example insert operation (insert at a given position):

void insertAtPosition(struct Node** head, int data, int position) {

if (position < 1) {

printf("Invalid position.\n");

return;

if (position == 1) {

insertAtBeginning(head, data);

return;

struct Node* newNode = createNode(data);

struct Node* temp = *head;


21
for (int i = 1; i < position - 1 && temp != NULL; ++i) {

temp = temp->next;

if (temp == NULL) {

printf("Position exceeds the length of the list.\n");

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):

void deleteFromBeginning(struct Node** head) {

if (*head == NULL) {

printf("List is empty. Nothing to delete.\n");

return;

struct Node* temp = *head;


22
*head = temp->next;

if (*head != NULL) {

(*head)->prev = NULL;

free(temp);

Example delete operation (delete from the end):

void deleteFromEnd(struct Node** head) {

if (*head == NULL) {

printf("List is empty. Nothing to delete.\n");

return;

struct Node* temp = *head;

while (temp->next != NULL) {

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):

void deleteFromPosition(struct Node** head, int position) {

if (*head == NULL) {

printf("List is empty. Nothing to delete.\n");

return;

if (position < 1) {

printf("Invalid position.\n");

return;

struct Node* temp = *head;

for (int i = 1; i < position && temp != NULL; ++i) {

temp = temp->next;

if (temp == NULL) {

printf("Position exceeds the length of the list.\n");

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.

Basic operations associated with a stack:

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>

#define MAX_SIZE 100

struct Stack {

int items[MAX_SIZE];

int top;

};

void initialize(struct Stack* stack) {


25
stack->top = -1;

bool isEmpty(struct Stack* stack) {

return stack->top == -1;

bool isFull(struct Stack* stack) {

return stack->top == MAX_SIZE - 1;

void push(struct Stack* stack, int value) {

if (isFull(stack)) {

printf("Stack overflow. Cannot push %d\n", value);

return;

stack->items[++stack->top] = value;

int pop(struct Stack* stack) {

if (isEmpty(stack)) {

printf("Stack underflow. Cannot pop from an empty stack.\n");

return -1; // Assuming -1 represents an error or an invalid value

return stack->items[stack->top--];

int peek(struct Stack* stack) {

if (isEmpty(stack)) {

printf("Stack is empty. Cannot peek.\n");


26
return -1; // Assuming -1 represents an error or an invalid value

return stack->items[stack->top];

int size(struct Stack* stack) {

return stack->top + 1;

int main() {

struct Stack myStack;

initialize(&myStack);

push(&myStack, 10);

push(&myStack, 20);

push(&myStack, 30);

printf("Top element: %d\n", peek(&myStack));

printf("Stack size: %d\n", size(&myStack));

printf("Pop: %d\n", pop(&myStack));

printf("Pop: %d\n", pop(&myStack));

printf("Is stack empty? %s\n", isEmpty(&myStack) ? "Yes" : "No");

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.

Convert infix to postfix.

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>

// Structure to represent a stack

struct Stack {

int top;

unsigned capacity;

char* array;

};

// Function to create a new stack

struct Stack* createStack(unsigned capacity) {

struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));

if (!stack) {

exit(1); // Memory allocation failure

stack->top = -1;

stack->capacity = capacity;

stack->array = (char*)malloc(stack->capacity * sizeof(char));

if (!stack->array) {

exit(1); // Memory allocation failure

28
return stack;

// Function to check if the stack is empty

bool isEmpty(struct Stack* stack) {

return stack->top == -1;

// Function to push an element onto the stack

void push(struct Stack* stack, char item) {

stack->array[++stack->top] = item;

// Function to pop an element from the stack

char pop(struct Stack* stack) {

if (!isEmpty(stack)) {

return stack->array[stack->top--];

return '\0'; // Return null character for an empty stack

// Function to get the precedence of an operator

int getPrecedence(char operator) {

switch (operator) {

case '+':

case '-':

return 1;

case '*':

case '/':
29
return 2;

case '^':

return 3;

default:

return -1;

// Function to convert infix expression to postfix

void infixToPostfix(char* infix) {

struct Stack* stack = createStack(strlen(infix));

int i, j;

for (i = 0, j = -1; infix[i]; ++i) {

if (isalnum(infix[i])) {

printf("%c", infix[i]);

} else if (infix[i] == '(') {

push(stack, infix[i]);

} else if (infix[i] == ')') {

while (!isEmpty(stack) && stack->array[stack->top] != '(') {

printf("%c", pop(stack));

if (!isEmpty(stack) && stack->array[stack->top] != '(') {

printf("Invalid expression\n");

return;

} else {

pop(stack);
30
}

} else {

while (!isEmpty(stack) && getPrecedence(infix[i]) <= getPrecedence(stack-


>array[stack->top])) {

printf("%c", pop(stack));

push(stack, infix[i]);

while (!isEmpty(stack)) {

printf("%c", pop(stack));

int main() {

char infixExpression[100];

printf("Enter an infix expression: ");

scanf("%s", infixExpression);

printf("Postfix expression: ");

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.

Algorithm: Bubble Sort

Input: A list of elements

Output: The sorted list

1. Start from the first element (index 0) and compare it with the next element.

2. If the first element is greater than the next, swap them.

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).

Quick Sort Algorithm:

Quick Sort is a divide-and-conquer algorithm that works by selecting a 'pivot'


element from the array and partitioning the other elements into two sub-arrays
according to whether they are less than or greater than the pivot. The sub-arrays are
then sorted recursively.

Algorithm: Quick Sort

Input: A list of elements

Output: The sorted list

1. Choose a pivot element from the list.

2. Partition the other elements into two sub-arrays: elements less than the pivot and elements
greater than the pivot.

3. Recursively apply the Quick Sort algorithm to the two sub-arrays.

4. Combine the sorted sub-arrays and the pivot to get the final sorted list.

Bubble Sort Implementation in C:


#include <stdio.h>

32
void bubbleSort(int arr[], int n) {

for (int i = 0; i < n - 1; i++) {

for (int j = 0; j < n - i - 1; j++) {

if (arr[j] > arr[j + 1]) {

// Swap elements if they are in the wrong order

int temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

int main() {

int arr[] = {64, 34, 25, 12, 22, 11, 90};

int n = sizeof(arr) / sizeof(arr[0]);

printf("Original Array: ");

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

printf("%d ", arr[i]);

bubbleSort(arr, n);

printf("\nSorted Array: ");

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

printf("%d ", arr[i]);

return 0;
33
}
Quick Sort Implementation in C:
#include <stdio.h>

// Function to partition the array and return the pivot index

int partition(int arr[], int low, int high) {

int pivot = arr[high];

int i = low - 1;

for (int j = low; j <= high - 1; j++) {

if (arr[j] < pivot) {

i++;

// Swap arr[i] and arr[j]

int temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

// Swap arr[i+1] and arr[high] (put the pivot in its correct place)

int temp = arr[i + 1];

arr[i + 1] = arr[high];

arr[high] = temp;

return i + 1;

// Function to implement Quick Sort

void quickSort(int arr[], int low, int high) {

if (low < high) {

34
// Find pivot such that elements smaller than pivot are on the left and greater are on the
right

int pivotIndex = partition(arr, low, high);

// Recursively sort the sub-arrays

quickSort(arr, low, pivotIndex - 1);

quickSort(arr, pivotIndex + 1, high);

int main() {

int arr[] = {64, 34, 25, 12, 22, 11, 90};

int n = sizeof(arr) / sizeof(arr[0]);

printf("Original Array: ");

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

printf("%d ", arr[i]);

quickSort(arr, 0, n - 1);

printf("\nSorted Array: ");

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

printf("%d ", arr[i]);

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>

void bubbleSort(int arr[], int n) {

for (int i = 0; i < n - 1; i++) {

for (int j = 0; j < n - i - 1; j++) {

if (arr[j] > arr[j + 1]) {

// Swap elements if they are in the wrong order

int temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

int main() {

int arr[] = {64, 34, 25, 12, 22, 11, 90};

int n = sizeof(arr) / sizeof(arr[0]);

printf("Original Array: ");

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

printf("%d ", arr[i]);

bubbleSort(arr, n);

printf("\nSorted Array (Ascending Order): ");

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

printf("%d ", arr[i]);


36
}

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.

17. what is searching? explain detail with suitable example?

Searching is the process of finding a specific item or value within a collection of


items, often referred to as a dataset or data structure. The goal of searching is to
determine whether the target item is present in the collection and, if so, to locate its
position or some additional information about it.

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.

Algorithm: Linear Search

1. Start from the first element of the list.


2. Compare the target value with each element in the list until a match is found.
3. If a match is found, return the index of the element; otherwise, continue
searching.
4. If the end of the list is reached without finding the target, indicate that the
item is not present.

Example: Linear Search in C

#include <stdio.h>

int linearSearch(int arr[], int n, int target) {

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

37
if (arr[i] == target) {

return i; // Element found, return its index

return -1; // Element not found

int main() {

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

int n = sizeof(arr) / sizeof(arr[0]);

int target = 30;

int result = linearSearch(arr, n, target);

if (result != -1) {

printf("Element %d found at index %d.\n", target, result);

} else {

printf("Element %d not found in the array.\n", target);

return 0;

2. Binary Search:

Binary search is an efficient searching algorithm for ordered lists. It works by


repeatedly dividing the search interval in half.

Algorithm: 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.

Example: Binary Search in C

#include <stdio.h>

int binarySearch(int arr[], int low, int high, int target) {

while (low <= high) {

int mid = low + (high - low) / 2;

if (arr[mid] == target) {

return mid; // Element found, return its index

} else if (arr[mid] < target) {

low = mid + 1; // Search in the right half

} else {

high = mid - 1; // Search in the left half

return -1; // Element not found

int main() {

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

int n = sizeof(arr) / sizeof(arr[0]);

int target = 30;

int result = binarySearch(arr, 0, n - 1, target);

39
if (result != -1) {

printf("Element %d found at index %d.\n", target, result);

} else {

printf("Element %d not found in the array.\n", target);

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.

Inorder: Left -> Root -> Right

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?

The term "middle-level language" is not commonly used to describe the C


programming language. C is typically referred to as a "high-level" programming
language. In general classifications:

High-level languages: These languages, including C, are designed for ease of


programming, providing abstractions and simplifications. They are closer to human
language and abstract away low-level hardware details.

Low-level languages: These languages, such as assembly and machine languages,


are closer to the hardware, offering more direct control over the
computer's resources.
21. Difference Between Algorithm and Flowchart?

An algorithm and a flowchart are both tools used in computer science and
programming, but they serve different purposes.
Algorithm:

An algorithm is a step-by-step procedure or set of rules designed to solve a specific


problem or perform a particular task.

It is a logical and systematic approach to problem-solving that describes a sequence


of actions or operations.

Algorithms are language-independent and can be implemented in various


programming languages.
Flowchart:

A flowchart is a visual representation of an algorithm using symbols, shapes, and


arrows to depict the flow of control and data within a system.

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.

In other words, for every node 'n' in a binary search tree:

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:

Binary Tree: Binary Search Tree:

In the binary tree, the structure is arbitrary,


and there is no specific ordering of values. In
the binary search tree, however, the ordering property is maintained, where
each node's value is greater than all values in its left subtree and less than
all values in its right subtree.

23.what is the need of operator precedence?

Operator precedence rules help avoid ambiguity in expressions with


multiple operators. They define the order in which operators are evaluated,
ensuring a clear and unambiguous interpretation of expressions. For
example, in the expression 3 + 5 * 2, operator precedence dictates that
43
multiplication has higher precedence than addition, preventing ambiguity
in the result.

Define Execution Order

Operator precedence establishes the execution order of operators in an


expression. This ensures that mathematical and logical operations are
performed in a predictable and consistent manner. By defining a standard
order of evaluation, operator precedence contributes to code clarity and
readability, reducing the need for excessive parentheses to specify the
order of operations.

24. What do you mean by a function in the programming language?


Differentiate between user-defined and pre-defined functions.

Function in Programming:

In programming, a function is a self-contained block of code that performs


a specific task or set of tasks. It is designed to be reusable and modular,
allowing developers to organize code efficiently and promote code reuse.
Functions typically take input parameters, perform operations, and return a
result.

Differentiation between User-Defined and Predefined Functions:

User-Defined Functions:

Definition: Functions created by the programmer are called user-defined


functions.

Creation: Programmers define these functions according to the


requirements of their specific program.

Customization: User-defined functions are highly customizable and can be


tailored to meet the specific needs of the program.

Examples:

// Example of a user-defined function in C

int add(int a, int b) {

44
return a + b;

Predefined Functions (Built-in Functions):

Definition: Functions that are already provided by theprogramming


language or a library are called predefined functions.

Availability: These functions are available for use without requiring the
programmer to implement their logic.

Standardization: Predefined functions are standardized and follow a specific


set of rules defined by the language or library.

Examples:

// Example of a predefined function in C (from the standard library)

#include <stdio.h>

int main() {

printf("Hello, World!\n");

return 0;

25. What do you mean by recursive function? Explain need and


working principle of recursive function.

Recursive Function:

A recursive function is a function that calls itself during its execution. In


other words, it's a programming technique where a function solves a
problem by solving smaller instances of the same problem. Recursive
functions have two main components: a base case and a recursive case.

Need for Recursive Functions:

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.

Code Modularity: Recursive functions promote modularity and code reuse.


The same function can be called with different inputs, making the code
more elegant and maintainable.

Mathematical Modeling: Recursive functions are suitable for problems that


can be naturally modeled in a recursive way, such as computing factorials,
Fibonacci numbers, or solving certain mathematical sequences.

Working Principle of Recursive Functions:

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.

Example: Factorial Function:

Consider the factorial function, denoted as

n!, which is the product of all positive integers up to

n. The recursive definition of the factorial function is as follows:

csharp

n! = n * (n-1)! for n > 0

0! = 1 base case
46
Here, the base case is

0!, and the recursive case is the definition of

n! in terms of

1)

(n−1)!. The recursion continues until it reaches the base case.

Example Code:

#include <stdio.h>

int factorial(int n) {

// Base case

if (n == 0) {

return 1;

// Recursive case

else {

return n * factorial(n - 1);

47
}

int main() {

int result = factorial(5);

printf("Factorial of 5: %d\n", result);

return 0;

In this example, the factorial function calls itself with a smaller input (

n−1) until it reaches the base case (

0!), at which point the recursion stops, and the results are
calculated backward.

26. Differentiate between 1D array vs 2D array. (Definition, syntax &


example must be included).

1D Array (One-Dimensional Array):

Definition:

A 1D array is a collection of elements of the same data type arranged in a


linear sequence. It is also known as a vector or a list.

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.

2D Array (Two-Dimensional Array):

Definition:

A 2D array is a collection of elements of the same data type organized in a


grid with rows and columns. It is like a table of elements.

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:

1D Array: Contains a single line or sequence of elements.

2D Array: Organized in rows and columns, forming a two-dimensional grid.

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:

1D Array: Accessed using a single index.

2D Array: Accessed using two indices (row and column).

Initialization:

1D Array: Initialized with a single set of curly braces.

2D Array: Initialized with nested curly braces to represent rows and


columns.

Representation:

1D Array: Represented as a single line of elements.

2D Array: Represented as a grid with rows and columns.

Example Code:

#include <stdio.h>

int main() {

// 1D Array

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

// 2D Array

50
int matrix[3][3] = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

// Accessing elements

printf("1D Array: %d\n", numbers[2]); // Accessing the third element

printf("2D Array: %d\n", matrix[1][2]); // Accessing the element in the


second row, third column

return 0;

This code demonstrates the declaration, initialization, and access of


elements in both 1D and 2D arrays in the C programming language.

27. What do you mean by passing array to function? Explain the


methods to declare a function that receives an array as an argument?

Passing an array to a function in C involves sending the array or a reference


to the array to a function, allowing the function to work with the array's
elements or modify its contents. There are two common methods to
declare a function that receives an array as an argument: using a fixed-size
array or using a pointer to an array. Below are explanations for both
methods:

Method 1: Using a Fixed-Size Array

In this method, you specify the size of the array in the function parameter.

#include <stdio.h>

// Function declaration with a fixed-size array

void processArray(int arr[], int size) {


51
for (int i = 0; i < size; i++) {

// Process each element of the array

// For example, print each element

printf("%d ", arr[i]);

printf("\n");

int main() {

// Array declaration and initialization

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

// Call the function and pass the array

processArray(myArray, sizeof(myArray) / sizeof(myArray[0]));

return 0;

Method 2: Using a Pointer to an Array

In this method, you use a pointer to represent the array, and you pass the
size of the array separately.

#include <stdio.h>

// Function declaration with a pointer to an array

void processArray(int *arr, int size) {

for (int i = 0; i < size; i++) {

// Process each element of the array

52
// For example, print each element

printf("%d ", arr[i]);

printf("\n");

int main() {

// Array declaration and initialization

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

// Call the function and pass the array and its size

processArray(myArray, sizeof(myArray) / sizeof(myArray[0]));

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.

28. Differentiate between call by value vs call by reference.

In programming languages like C, function arguments can be passed in two


main ways: Call by Value and Call by Reference. Let's differentiate between
these two concepts:

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.

A new copy of the variable is created in the function's local scope.

Example:

#include <stdio.h>

void square(int x) {

x = x * x;

printf("Inside function: %d\n", x);

int main() {

int num = 5;

square(num);

printf("Outside function: %d\n", num);

return 0;

Output:

bash

Inside function: 25

Outside function: 5

Call by Reference:

54
Definition:

In Call by Reference, the memory address (reference) of the actual


argument is passed to the function.

The function can directly access and modify the original data stored at that
memory location.

Implementation:

Implemented using pointers or references.

Suitable for passing large data structures (arrays, structures) to avoid


copying the entire data.

Example:

#include <stdio.h>

void squareByReference(int *x) {

*x = (*x) * (*x);

printf("Inside function: %d\n", *x);

int main() {

int num = 5;

squareByReference(&num);

printf("Outside function: %d\n", num);

return 0;

Output:

bash

55
Inside function: 25

Outside function: 2

29.Differentiate between static memory allocation vs Dynamic


memory allocation.

Static Memory Allocation:

Memory is allocated at compile time.

Size is determined before program execution.

Fixed memory locations and sizes for variables.

Managed by the compiler.

Allocated on the stack or in the data segment.

Variables have a fixed lifetime throughout the program.

Less flexible; size is fixed at compile time.

Examples include arrays, static variables, and global variables.

Dynamic Memory Allocation:

Memory is allocated at runtime.

Size can be determined during program execution.

Variables and data structures can change in size.

Managed by the programmer.

Allocated on the heap.

Programmer is responsible for allocation and deallocation.

Memory can be allocated and deallocated at any point.

More flexible; allows efficient memory usage based on needs.

56
Examples include pointers and functions like malloc, calloc,
realloc, and free.

30. What do you mean by dynamic memory allocation? Explain


different types of functions available for DMA with suitable examples?

Dynamic Memory Allocation (DMA) in C allows you to allocate memory


during program execution. This is different from static memory allocation,
where memory is allocated at compile-time. In C, dynamic memory
allocation is achieved using functions from the stdlib.h header. The main
functions for DMA in C are malloc(), calloc(), realloc(), and free().

Here are explanations and examples for each:

malloc (Memory Allocation):

Purpose: Allocates a specified number of bytes of memory.

Syntax: void* malloc(size_t size);

Example:

#include <stdio.h>

#include <stdlib.h>

int main() {

int arr = (int)malloc(5 * sizeof(int));

if (arr == NULL) {

printf("Memory allocation failed!\n");

return 1;

// Use 'arr' as an array of 5 integers

free(arr); // Don't forget to free the allocated memory

return 0;
57
}

calloc (Contiguous Allocation):

Purpose: Allocates a specified number of blocks of memory, each of a


specified size. Initializes the allocated memory to zero.

Syntax: void* calloc(size_t num, size_t size);

Example:

#include <stdio.h>

#include <stdlib.h>

int main() {

int arr = (int)calloc(5, sizeof(int));

if (arr == NULL) {

printf("Memory allocation failed!\n");

return 1;

// 'arr' now points to an array of 5 integers, all initialized to zero

free(arr); // Don't forget to free the allocated memory

return 0;

realloc (Reallocating Memory):

Purpose: Changes the size of an already allocated block of memory.

Syntax: void* realloc(void* ptr, size_t size);

Example:

58
#include <stdio.h>

#include <stdlib.h>

int main() {

int arr = (int)malloc(5 * sizeof(int));

if (arr == NULL) {

printf("Memory allocation failed!\n");

return 1;

// Use 'arr' as an array of 5 integers

arr = (int*)realloc(arr, 10 * sizeof(int));

if (arr == NULL) {

printf("Memory reallocation failed!\n");

return 1;

// 'arr' now points to an array of 10 integers

free(arr); // Don't forget to free the allocated memory

return 0;

free (Freeing Memory):

Purpose: Deallocates memory that was previously allocated using malloc,


calloc, or realloc.

Syntax: void free(void* ptr);

59
Example: (Refer to examples above for usage)

31. What is pointer? Explain different types of pointer arithmetic


operations in c with suitable examples?

In C, a pointer is a variable that holds the memory address of another


variable. It essentially "points" to the location of a data item in memory.
Pointers provide a way to work directly with memory addresses, which can
be useful for tasks like dynamic memory allocation, efficient array
manipulation, and interfacing with hardware.

Pointer arithmetic involves performing arithmetic operations on pointers,


which is possible due to the fixed size of data types in C. Here are some
common pointer arithmetic operations:

Increment and Decrement:

You can increment or decrement a pointer to move to the next or previous


memory location, based on the size of the data type it points to.

Example:

#include <stdio.h>

int main() {

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

int *ptr = arr;

printf("%d\n", *ptr); // Output: 10

ptr++; // Move to the next element

printf("%d\n", *ptr); // Output: 20

ptr--; // Move back to the previous element

printf("%d\n", *ptr); // Output: 10

return 0;
60
}

Addition and Subtraction:

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() {

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

int *ptr = arr;

printf("%d\n", *ptr); // Output: 10

ptr = ptr + 2; // Move two elements ahead

printf("%d\n", *ptr); // Output: 30

ptr = ptr - 1; // Move one element back

printf("%d\n", *ptr); // Output: 20

return 0;

Subtraction of Pointers:

Subtracting one pointer from another gives the number of elements


between them.

Example:

#include <stdio.h>

int main() {

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

61
int *ptr1 = &arr[2];

int *ptr2 = &arr[0];\

printf("Difference: %ld\n", ptr1 - ptr2); // Output: 2

return 0;

Array Indexing with Pointers:

Pointers can be used to access array elements by using the array indexing
syntax.

Example:

#include <stdio.h>

int main() {

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

int *ptr = arr;

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

printf("%d ", ptr[i]);

// Output: 10 20 30 40 50

return 0;

32. Differentiate between push() and pop() in stack.

Advantages of a Stack:

Simple Implementation:Stack operations are straightforward to implement.

62
Memory Efficiency:

Memory is managed efficiently, especially when compared to dynamic


structures like linked lists.

Ease of Reversal:

Useful for reversing sequences, as elements are accessed in reverse order


(Last In, First Out).

Function Call Management:

Used for managing function calls in recursion, allowing for easy


backtracking.

Disadvantages of a Stack:

Fixed Size (Array Implementation):

If implemented using arrays, the size is typically fixed, leading to potential


overflow.

Limited Random Access:

Random access to elements is not efficient in a stack. You need to pop


elements sequentially to reach a specific position.

Dynamic Memory Management Overhead:

In certain scenarios, dynamically allocating memory for a stack may


introduce overhead compared to other data structures.

Lack of Flexibility:

Some operations are less efficient than with other data structures,
particularly when dealing with arbitrary insertions and deletions.

33. How to implement a stack? Write advantages and dis


advantages of stack.

Advantages of a Stack:

Simple Implementation:
63
Stack operations are straightforward to implement.

Memory Efficiency:

Memory is managed efficiently, especially when compared to dynamic


structures like linked lists.

Ease of Reversal:

Useful for reversing sequences, as elements are accessed in reverse order


(Last In, First Out).

Function Call Management:

Used for managing function calls in recursion, allowing for easy


backtracking.

Disadvantages of a Stack:

Fixed Size (Array Implementation):

If implemented using arrays, the size is typically fixed, leading to potential


overflow.

Limited Random Access:

Random access to elements is not efficient in a stack. You need to pop


elements sequentially to reach a specific position.

Dynamic Memory Management Overhead:

In certain scenarios, dynamically allocating memory for a stack may


introduce overhead compared to other data structures.

Lack of Flexibility:

Some operations are less efficient than with other data structures,
particularly when dealing with arbitrary insertions and deletions.

34. What do you mean by Queue in Data structure? Discuss the


principles and operations involved in queue?

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):

Adding an element to the back (rear) of the queue.

Syntax: enqueue(element)

Effect: The queue grows, and the new element becomes the last one.

Dequeue (Deletion):

Removing the element from the front (front) of the queue.

Syntax: dequeue()

Effect: The front element is taken off, and the queue shrinks.

Front (Peek at the front):

Retrieving the element at the front without removing it.

Syntax: front()

Effect: No change to the queue.

Rear (Peek at the rear):

Retrieving the element at the rear without removing it.

Syntax: rear()

Effect: No change to the queue.

isEmpty:

65
Checking if the queue is empty.

Syntax: isEmpty()

Effect: No change to the queue.

isFull (for fixed-size implementation):

Checking if the queue is full (applies to fixed-size implementations).

Syntax: isFull()

Effect: No change to the queue.

Operations involved in a Queue:

Here is a simple example of a queue implemented using an array in C:

#include <stdio.h>

#include <stdlib.h>

#define MAX_SIZE 5

struct Queue {

int arr[MAX_SIZE];

int front, rear;

};

// Function to initialize an empty queue

void initialize(struct Queue *queue) {

queue->front = -1;

queue->rear = -1;

// Function to check if the queue is empty

66
int isEmpty(struct Queue *queue) {

return queue->front == -1;

// Function to check if the queue is full

int isFull(struct Queue *queue) {

return (queue->rear + 1) % MAX_SIZE == queue->front;

// Function to enqueue an element

void enqueue(struct Queue *queue, int element) {

if (isFull(queue)) {

printf("Queue Overflow: Cannot enqueue %d, the queue is full.\n",


element);

} else {

if (isEmpty(queue)) {

queue->front = 0; // If the queue is empty, set front to 0

queue->rear = (queue->rear + 1) % MAX_SIZE;

queue->arr[queue->rear] = element;

printf("Enqueued %d into the queue.\n", element);

// Function to dequeue an element

67
int dequeue(struct Queue *queue) {

if (isEmpty(queue)) {

printf("Queue Underflow: Cannot dequeue from an empty queue.\n");

return -1; // Placeholder for an invalid value

} else {

int dequeuedElement = queue->arr[queue->front];

if (queue->front == queue->rear) {

initialize(queue); // If the last element is dequeued, reset the queue

} else {

queue->front = (queue->front + 1) % MAX_SIZE;

printf("Dequeued %d from the queue.\n", dequeuedElement);

return dequeuedElement;

// Function to peek at the front element

int front(struct Queue *queue) {

if (isEmpty(queue)) {

printf("Queue is empty.\n");

return -1; // Placeholder for an invalid value

} else {

return queue->arr[queue->front];

68
}

// Function to peek at the rear element

int rear(struct Queue *queue) {

if (isEmpty(queue)) {

printf("Queue is empty.\n");

return -1; // Placeholder for an invalid value

} else {

return queue->arr[queue->rear];

int main() {

struct Queue myQueue;

initialize(&myQueue);

enqueue(&myQueue, 10);

enqueue(&myQueue, 20);

enqueue(&myQueue, 30);

printf("Front of the queue: %d\n", front(&myQueue));

printf("Rear of the queue: %d\n", rear(&myQueue));

dequeue(&myQueue);

dequeue(&myQueue);

printf("Is the queue empty? %s\n", isEmpty(&myQueue) ? "Yes" : "No");

69
return 0;

35. What are the different types of Queues available? Explain each with
suitable examples.’

Full Binary Tree:

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.

Characteristics of a Full Binary Tree:

Node Structure:

Each node has either 0 or 2 children.

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.

Complete Binary Tree:

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.

Characteristics of a Complete Binary Tree:

Node Structure:

70
All levels are completely filled except possibly for the last level, which is
filled from left to right.

Leftmost Positioning:

Nodes in the last level are positioned as left as possible.

Examples:

Heaps (like binary heaps) are often implemented as complete binary trees.
Complete binary trees are commonly used in data structures.

36. Define a full binary tree and complete binary tree.

Full Binary Tree:

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.

Characteristics of a Full Binary Tree:

Node Structure:

Each node has either 0 or 2 children.

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.

Complete Binary Tree:

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.

Characteristics of a Complete Binary Tree:

Node Structure:

All levels are completely filled except possibly for the last level, which is
filled from left to right.

Leftmost Positioning:

Nodes in the last level are positioned as left as possible.

Examples:

Heaps (like binary heaps) are often implemented as complete binary trees.
Complete binary trees are commonly used in data structures.

37. What do you mean by balance factor of a node in AVL tree.

In an AVL tree, the balance factor of a node is a numerical indicator that


represents the difference in heights between the left and right subtrees of
that node. The balance factor is calculated as follows:

Balance Factor

Height of Left Subtree

Height of Right Subtree

Balance Factor=Height of Left Subtree−Height of Right Subtree

In other words, the balance factor of a node is the absolute difference


between the height of its left subtree and the height of its right subtree.
The balance factor can have three possible values: -1, 0, or 1.

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.

If the balance factor is 1, it means the left subtree is taller by 1 level.

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

[−1,0,1] for the tree to be considered AVL-balanced. If at any node the


balance factor is outside this range, the tree is rebalanced through
rotations.

Here's an example to illustrate the concept:

markdown

/\

2 7

73
/ /\

1 5 8

In this AVL tree, the balance factor for each node is:

Balance Factor of 3:

Height of Left Subtree

Height of Right Subtree

Height of Left Subtree−Height of Right Subtree=1−2=−1

Balance Factor of 7:

Height of Left Subtree

Height of Right Subtree

74
2

Height of Left Subtree−Height of Right Subtree=2−1=1

38. Different between BFS and DFS for binary tree.

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.

Breadth-First Search (BFS):

Order of Visit:

BFS visits nodes level by level, starting from the root and moving to the
next level before going deeper.

Data Breadth-First Search (BFS):

Order of Visit:

Data Structure:

Traversal Approach:

Memory Usage:

Order of Visit:

Structure:

Uses a queue data structure to keep track of the nodes to be visited.

Traversal Approach:
75
Visits all nodes at a particular level before moving on to the next level.

Implementation:

Iterative implementation is straightforward using a queue.

Memory Usage:

Requires more memory as it needs to store all nodes at the current level in
the queue.

Applications:

Useful for finding the shortest path in an unweighted graph or tree.

Depth-First Search (DFS):

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:

Explores as far as possible along each branch before backtracking.

Implementation:

Recursive implementation is quite natural. Stack can also be used for an


iterative approach.

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.

Example Binary Tree:

markdown

/\

2 3

/\

4 5

BFS Traversal (Level Order):

12345

DFS Traversals:

Preorder (Root, Left, Right):

12453

Inorder (Left, Root, Right):

42513

Postorder (Left, Right, Root):

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

35. What are the different types of Queues available?

Explain each with suitable examples.’……………………………….…….70

36. Define a full binary tree and complete binary tree…………….…71

37. What do you mean by balance factor of a node in AVL tree…..72

38. Different between BFS and DFS for binary tree…………….……..75

78

You might also like