0% found this document useful (0 votes)
1K views

MMT 1 EM 2024 Ip

Uploaded by

duttasimran48
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views

MMT 1 EM 2024 Ip

Uploaded by

duttasimran48
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

1

MMT 1 PROGRAMMING AND DATA STRUCTURES

MMT 1
ASSIGNMENT 2023-2024

www.bookmyassignments.com MMT1
2
MMT 1 PROGRAMMING AND DATA STRUCTURES

www.bookmyassignments.com MMT1
3
MMT 1 PROGRAMMING AND DATA STRUCTURES

www.bookmyassignments.com MMT1
4
MMT 1 PROGRAMMING AND DATA STRUCTURES

www.bookmyassignments.com MMT1
5
MMT 1 PROGRAMMING AND DATA STRUCTURES

www.bookmyassignments.com MMT1
6
MMT 1 PROGRAMMING AND DATA STRUCTURES

Assignment
1. Write the output of the following C codes, with proper
justification for each.
i) main()
{
int a = 2, b = 4, c = 5;
a = b + c;
b = a + c;
c = a - b;
printf("%d,%d,%d", a, b, c);
}
#include <stdio.h>

int main() {
int a = 2, b = 4, c = 5;
a = b + c; // a = 4 + 5 = 9
b = a + c; // b = 9 + 5 = 14
c = a - b; // c = 9 - 14 = -5
printf("%d, %d, %d", a, b, c);
return 0;
}
Initialize three integer variables a, b, and c with values 2, 4, and 5, respectively.
Update the value of a by adding b and c, so a becomes 9.

www.bookmyassignments.com MMT1
7
MMT 1 PROGRAMMING AND DATA STRUCTURES

Update the value of b by adding the new value of a (which is 9) and c, so b becomes 14.
Update the value of c by subtracting b from the new value of a (which is 9 - 14), so c becomes
-5.
Print the values of a, b, and c using printf.
The output of the code will be:
9, 14, -5
Each value is separated by a comma, as specified in the printf format string.

ii) main()
{
printf("%d", ‘C’ + ‘P’ + ‘r’ + ‘o’ + ‘g’ + ‘r’ + ‘a’ + ‘m’);
}
#include <stdio.h>

int main() {
printf("%d", 'C' + 'P' + 'r' + 'o' + 'g' + 'r' + 'a' + 'm');
return 0;
}
'C' corresponds to the ASCII value of the character 'C', which is 67.
'P' corresponds to the ASCII value of the character 'P', which is 80.
'r' corresponds to the ASCII value of the character 'r', which is 114.
'o' corresponds to the ASCII value of the character 'o', which is 111.
'g' corresponds to the ASCII value of the character 'g', which is 103.
'r' corresponds to the ASCII value of the character 'r', which is 114.
'a' corresponds to the ASCII value of the character 'a', which is 97.
'm' corresponds to the ASCII value of the character 'm', which is 109.
www.bookmyassignments.com MMT1
8
MMT 1 PROGRAMMING AND DATA STRUCTURES

Now, let's sum up these ASCII values:

67 + 80 + 114 + 111 + 103 + 114 + 97 + 109 = 795


So, the output of the code will be:
795
The code calculates the sum of the ASCII values of the characters 'C', 'P', 'r', 'o', 'g', 'r', 'a', and
'm' and prints the result, which is 795.

iii) main()
{
int i, j = 1;
for(i = 1; i <= 10; i = i + 2)
{
j = i - j;
while(j <= 2)
printf("%d ", i+j++);
}
}
#include <stdio.h>

int main() {
int i, j = 1;
for (i = 1; i <= 10; i = i + 2) {
j = i - j;
while (j <= 2)

www.bookmyassignments.com MMT1
9
MMT 1 PROGRAMMING AND DATA STRUCTURES

printf("%d ", i + j++);


}
return 0;
}
Initialize two integer variables, i and j. i is initialized to 1, and j is initialized to 1.

Enter a for loop that iterates from 1 to 10 with a step size of 2 in each iteration.

Inside the for loop, update the value of j by subtracting j from the current value of i. In the
first iteration, i is 1, and j becomes 1 - 1, which is 0.

Enter a while loop with the condition j <= 2. This while loop will execute as long as j is less
than or equal to 2.

Inside the while loop, print the value of i + j followed by a space, and then increment j by 1.
The value of i + j is printed on the same line as long as j remains less than or equal to 2.
In the first iteration of the for loop, i is 1, and j is 0. The while loop executes twice, printing
1 and 2 on the same line.

In the second iteration of the for loop, i is 3, and j is updated to 3 - 0, which is 3. The while
loop does not execute because j is no longer less than or equal to 2.

In the third iteration of the for loop, i is 5, and j is updated to 5 - 3, which is 2. The while loop
executes once, printing 7.

The remaining iterations of the for loop follow a similar pattern.


So, the output of the code will be:
1278
www.bookmyassignments.com MMT1
10
MMT 1 PROGRAMMING AND DATA STRUCTURES

iv) main()
{
int a = 10, b = 20, c = 30;
int *p = 2;
a = c/*p;
b = c;
printf("a = %d, b = %d", a, b);
}
#include <stdio.h>

int main() {
int a = 10, b = 20, c = 30;
int *p = 2; // Syntax error - Incorrect pointer assignment
a = c/*p; // Incorrect use of comments
b = c;
printf("a = %d, b = %d", a, b);
return 0;
}
Initialize three integer variables a, b, and c with values 10, 20, and 30, respectively.

Declare an integer pointer p and attempt to initialize it with the value 2. However, this is
incorrect; you cannot initialize a pointer this way.

Attempt to update the value of a using c/*p;. It appears that you intended to perform
multiplication, but due to the use of comments (/* and ;), this line becomes a comment, and
the code effectively does nothing.

www.bookmyassignments.com MMT1
11
MMT 1 PROGRAMMING AND DATA STRUCTURES

Assign the value of c to b, so b becomes 30.

Use printf to display the values of a and b.


v) func(int x)
{
static int a = 0;
a += x;
return(a);
}
main()
{
int p;
for(p = 1; p <= 5; ++p)
printf("%d", fun(p));
}
#include <stdio.h>

// Function declaration with the correct name "func" and return type
int func(int x) {
static int a = 0;
a += x;
return a;
}

www.bookmyassignments.com MMT1
12
MMT 1 PROGRAMMING AND DATA STRUCTURES

int main() {
int p;
for (p = 1; p <= 5; ++p)
printf("%d", func(p)); // Corrected function name from "fun" to "func"
return 0;
}
We add #include <stdio.h> to include the necessary header for the printf function.

We declare the func function with the correct name, return type (int), and parameter (int x).

Inside the func function, we use a static variable a to keep track of the cumulative sum of the
input values x.

In the main function, we initialize an integer variable p and use a for loop to iterate from 1 to
5.

Inside the loop, we call the func function with the current value of p and print the result using
printf.
The func function takes an integer parameter x and adds it to the static variable a, which starts
at 0. The result is then returned.

The main function calls func with values 1, 2, 3, 4, and 5 in the loop and prints the returned
values. Here's the output:
1361015

www.bookmyassignments.com MMT1
13
MMT 1 PROGRAMMING AND DATA STRUCTURES

2. (a) Explain the use of the functions getchar(), putchar(), gets() and puts()
functions, with a suitable program.
getchar() and putchar() Functions:
getchar() reads a single character from standard input (usually the keyboard) and returns the
ASCII value of that character.
putchar() is used to print a single character to standard output (usually the console).

Program using getchar() and putchar():


#include <stdio.h>

int main() {
char ch;

printf("Enter a character: ");


ch = getchar(); // Read a character

printf("You entered: ");


putchar(ch); // Print the character

return 0;
}
In this program, the user is prompted to enter a character. getchar() reads the character, and
putchar() displays it on the screen.

gets() and puts() Functions:

www.bookmyassignments.com MMT1
14
MMT 1 PROGRAMMING AND DATA STRUCTURES

gets() reads a line of text from standard input and stores it in a character array (string). Be
cautious when using gets() as it does not perform any bounds checking, making it susceptible
to buffer overflow vulnerabilities. It is generally recommended to use fgets() for safe input.
puts() is used to print a null-terminated string to standard output (usually the console). It
automatically appends a newline character at the end.

Program using gets() and puts():


#include <stdio.h>

int main() {
char str[100]; // Declare a character array to store the input

printf("Enter a string: ");


gets(str); // Read a line of text

printf("You entered: ");


puts(str); // Print the string with a newline

return 0;
}
In this program, the user is prompted to enter a string of text. gets() reads the input line, and
puts() displays the string along with a newline character.

www.bookmyassignments.com MMT1
15
MMT 1 PROGRAMMING AND DATA STRUCTURES

(b) Arrange the following operators in descending order of their priority. If


any two
operators have the same priority, then specify their associativity.
+ =, %, +, ∗, ∗(unary), ! =, −, ++

++ (Postfix Increment) - Highest priority (right-to-left associativity)


* (Unary Indirection, also known as dereference) - Highest priority (right-to-left
associativity)
% (Modulus) - Left-to-right associativity
* (Multiplication) - Left-to-right associativity
/ (Division) - Left-to-right associativity
+ (Addition) - Left-to-right associativity
- (Subtraction) - Left-to-right associativity
!= (Not Equal) - Left-to-right associativity
= (Assignment) - Right-to-left associativity
In this list:

Operators with higher priority appear earlier in the list.


Operators with the same priority are grouped together and specified with their associativity.
Unary operators like ++ and * have the highest priority and are right-to-left associative.
Binary operators like %, *, /, +, -, !=, and = are left-to-right associative.

www.bookmyassignments.com MMT1
16
MMT 1 PROGRAMMING AND DATA STRUCTURES

(c) Write a loop that examines each character in a character type


array called text,
and determines how many of the characters are letters, how many
are digits, how
many are whitespace characters, and how many are other
characters.
#include <stdio.h>
#include <ctype.h>

int main() {
char text[] = "Hello123, World!";
int letters = 0, digits = 0, whitespace = 0, others = 0;

for (int i = 0; text[i] != '\0'; ++i) {


char currentChar = text[i];

if (isalpha(currentChar)) {
// Character is a letter
++letters;
} else if (isdigit(currentChar)) {
// Character is a digit
++digits;
} else if (isspace(currentChar)) {
// Character is whitespace
www.bookmyassignments.com MMT1
17
MMT 1 PROGRAMMING AND DATA STRUCTURES

++whitespace;
} else {
// Character is neither a letter, digit, nor whitespace
++others;
}
}

printf("Letters: %d\n", letters);


printf("Digits: %d\n", digits);
printf("Whitespace characters: %d\n", whitespace);
printf("Other characters: %d\n", others);

return 0;
}
We initialize the text array with a sample string containing letters, digits,
whitespace, and other characters.

We declare four variables: letters, digits, whitespace, and others to keep track of
the counts.

The for loop iterates through each character in the text array.

www.bookmyassignments.com MMT1
18
MMT 1 PROGRAMMING AND DATA STRUCTURES

Inside the loop, we use functions like isalpha() (checks if a character is a letter),
isdigit() (checks if a character is a digit), and isspace() (checks if a character is
whitespace) from the ctype.h library to categorize each character.

Depending on the category of the character, we increment the corresponding


count variable.

Finally, we print the counts of letters, digits, whitespace characters, and other
characters.

4. (a) How is an external variable defined? How is it initialised? What


happens when an
external variable definition does not include the assignment of an initial
value?
Definition of an External Variable:

An external variable is defined by declaring it outside of any function, typically at the global
scope of a source code file.
It should be declared using a valid data type, and it can have an optional initializer.
Code :
int globalVar; // Declaration of an external variable without an initializer
Initialization of an External Variable:

An external variable can be initialized with an initial value at the time of declaration.
If it is not explicitly initialized, it will be assigned a default value based on its storage class:
For external variables with static storage duration, they are initialized to zero by default.

www.bookmyassignments.com MMT1
19
MMT 1 PROGRAMMING AND DATA STRUCTURES

For external variables with automatic storage duration (i.e., declared within a function), they
are not initialized by default, and their initial values are undefined.
int globalVar = 42; // Declaration and initialization of an external variable

If an external variable definition does not include an assignment of an initial value, the
behavior depends on its storage class:
For external variables with static storage duration (e.g., declared outside any function), they
are automatically initialized to zero. This means that they will have a default initial value of
0 if not explicitly initialized.
For external variables with automatic storage duration (e.g., declared within a function), if
they are not explicitly initialized, their initial values are undefined. They will contain
whatever value happened to be in that memory location at the time of access, which can lead
to unpredictable behavior.
(b) When passing an argument to a function, what is the difference between
passing
by value and passing by reference?
Passing by Value:

In passing by value, a copy of the argument's value is passed to the function.


Any modifications made to the parameter within the function do not affect the original
argument outside of the function.
This method is used when you want to work with a local copy of the data without altering the
original data.
Example in C:
void modifyValue(int x) {
x = x + 1;
}

int main() {
www.bookmyassignments.com MMT1
20
MMT 1 PROGRAMMING AND DATA STRUCTURES

int num = 5;
modifyValue(num); // Passing by value
printf("Original num: %d\n", num); // Output: Original num: 5
return 0;
}
Passing by Reference:

In passing by reference, a reference or pointer to the original argument is passed to the


function.
Any modifications made to the parameter within the function directly affect the original
argument outside of the function.
This method is used when you want the function to operate on the actual data, allowing for
changes to be visible outside the function.
Example in C++ (using references):
void modifyReference(int &x) {
x = x + 1;
}

int main() {
int num = 5;
modifyReference(num); // Passing by reference
cout << "Modified num: " << num << endl; // Output: Modified num: 6
return 0;
}

www.bookmyassignments.com MMT1
21
MMT 1 PROGRAMMING AND DATA STRUCTURES

(c) Explain the use of the string library functions strncpy() and strncat(), with
the
help of an example for each.
strncpy() Function (String Copy with Limited Length):

The strncpy() function is used to copy a specified number of characters from one string to
another. It ensures that only a maximum number of characters are copied, preventing buffer
overflows.

The function prototype for strncpy() is as follows:


char *strncpy(char *dest, const char *src, size_t n);
Parameters:

dest: A pointer to the destination character array where the copied string will be stored.
src: A pointer to the source string from which characters will be copied.
n: The maximum number of characters to be copied.
Example of strncpy():
#include <stdio.h>
#include <string.h>

int main() {
char dest[20];
const char *src = "Hello, World!";
size_t max_length = 10;

strncpy(dest, src, max_length);

www.bookmyassignments.com MMT1
22
MMT 1 PROGRAMMING AND DATA STRUCTURES

dest[max_length] = '\0'; // Null-terminate the copied string

printf("Copied string: %s\n", dest);


return 0;
}
strncat() Function (String Concatenation with Limited Length):

The strncat() function is used to concatenate (append) a specified number of characters from
one string to the end of another string. It ensures that only a maximum number of characters
are appended, preventing buffer overflows.

The function prototype for strncat() is as follows:


char *strncat(char *dest, const char *src, size_t n);
Parameters:

dest: A pointer to the destination character array where the concatenated string will be stored.
src: A pointer to the source string that will be appended to the destination string.
n: The maximum number of characters to be appended.
Example of strncat():
#include <stdio.h>
#include <string.h>

int main() {
char dest[20] = "Hello, ";
const char *src = "World!";
size_t max_length = 5;

www.bookmyassignments.com MMT1
23
MMT 1 PROGRAMMING AND DATA STRUCTURES

strncat(dest, src, max_length);


dest[sizeof(dest) - 1] = '\0'; // Null-terminate the concatenated string

printf("Concatenated string: %s\n", dest);


return 0;
}

5. (a) A C program contains the following statements:


char u, v = ‘A’;
char *pu, *pv = &v;
*pv = v+1;
u = *pv + 1;
pu = &u;
Suppose each character occupies one byte of memory. If the value assigned
to u is
stored in (hexadecimal) address F8C and the value assigned to v is stored in
the
address F8D, then
i) What value is represented by &v?
ii) What value is assigned to pv?
iii) What value is represented by *pv?
iv) What value is assigned to u?
v) What value is represented by &u?

www.bookmyassignments.com MMT1
24
MMT 1 PROGRAMMING AND DATA STRUCTURES

vi) What value is assigned to pu?


char u, v = 'A';
char *pu, *pv = &v;
*pv = v + 1;
u = *pv + 1;
pu = &u;
What value is represented by &v?

The &v represents the memory address where the variable v is stored.
Given that the value assigned to v is stored in address F8D, the value represented by &v is
F8D.
What value is assigned to pv?

pv is assigned the address of the variable v. So, pv contains the memory address of v.
Therefore, pv is assigned the value F8D.
*What value is represented by pv?

*pv represents the value stored at the memory address pointed to by pv.
Since pv points to v, *pv represents the value stored in v, which is 'B' (since v was initially
'A', and *pv increased it by 1).
What value is assigned to u?

u is assigned the value of *pv + 1, which is the value in v (now 'B') plus 1.
So, u is assigned the value 'B' + 1, which is 'C'.
What value is represented by &u?

www.bookmyassignments.com MMT1
25
MMT 1 PROGRAMMING AND DATA STRUCTURES

The &u represents the memory address where the variable u is stored.
Given that the value assigned to u is stored in address F8C, the value represented by &u is
F8C.
What value is assigned to pu?

pu is assigned the address of the variable u. So, pu contains the memory address of u.
Therefore, pu is assigned the value F8C.
To summarize:
i) &v represents F8D.
ii) pv is assigned F8D.
iii) *pv represents 'B'.
iv) u is assigned 'C'.
v) &u represents F8C.
vi) pu is assigned F8C.

(b) How would you differentiate between the terms pointer to an array and
array of
pointers? Give proper examples.
Pointer to an Array:

A pointer to an array is a pointer variable that points to the first element of a contiguous block
of memory where an array is stored. It treats the entire array as a single entity.
Pointer to an array is used to access elements of an array as a whole.
Example:
int arr[3] = {1, 2, 3};
int (*ptr)[3]; // Declaration of a pointer to an array of 3 integers

www.bookmyassignments.com MMT1
26
MMT 1 PROGRAMMING AND DATA STRUCTURES

ptr = &arr; // Pointing to the entire array

printf("%d\n", (*ptr)[0]); // Accessing the first element of the array


Array of Pointers:

An array of pointers is an array where each element is a pointer to a different memory


location, typically pointing to different variables or arrays.
Array of pointers is used to create collections of pointers, often for dynamically allocated
memory or arrays of strings.
Example:
int x = 1, y = 2, z = 3;
int* arr[3]; // Declaration of an array of 3 integer pointers
arr[0] = &x; // Storing the address of x in the first element
arr[1] = &y; // Storing the address of y in the second element
arr[2] = &z; // Storing the address of z in the third element

printf("%d\n", *arr[0]); // Accessing the value pointed to by the first pointer


In this example, arr is an array of 3 integer pointers. Each element of the array (arr[0], arr[1],
arr[2]) stores the address of a different integer variable (x, y, z).

www.bookmyassignments.com MMT1
27
MMT 1 PROGRAMMING AND DATA STRUCTURES

6. (a) What does the following C function compute? Discover.


int some fun(int n)
{
if(n%2 == 0)
return 2;
int d, s = sqrt(n);
2
for(d = 3; d <= s; d = d+2)
if(n%d == 0)
return d;
return n;
}

int some_fun(int n) {
if (n % 2 == 0)
return 2; // If n is even, 2 is returned as the smallest prime factor
int d, s = sqrt(n);
for (d = 3; d <= s; d = d + 2) {
if (n % d == 0)
return d; // If n is divisible by 'd', 'd' is returned as the smallest prime factor
}
return n; // If 'n' is a prime number, 'n' itself is returned as the smallest prime factor
}

www.bookmyassignments.com MMT1
28
MMT 1 PROGRAMMING AND DATA STRUCTURES

It starts by checking if n is even (n % 2 == 0). If it is, the function returns 2 as the smallest
prime factor. This is because even numbers greater than 2 cannot be prime, and 2 is the
smallest prime number.

If n is not even (i.e., it's odd), the function initializes a variable s with the square root of n.
This is done to optimize the loop that follows, as it only needs to check potential divisors up
to the square root of n.

The function enters a loop starting from d = 3 and continues until d reaches or exceeds s.
Inside the loop, it checks if n is divisible by d (i.e., n % d == 0). If it is, it means that d is the
smallest prime factor of n, and d is returned as the result.

If none of the previous conditions are met (i.e., n is neither even nor divisible by any odd
number up to its square root), it means that n itself is a prime number. In this case, the function
returns n as the result.

(b) What do you understand by a nested structure? Explain with an example.


Also,
explain how would you access the members of a structure or a nested
structure
using pointers?
Example of a Nested Structure:
Suppose we want to represent information about a person, including their name and address.
We can create a nested structure to achieve this:
#include <stdio.h>

struct Address {
char street[50];
char city[30];
www.bookmyassignments.com MMT1
29
MMT 1 PROGRAMMING AND DATA STRUCTURES

char state[20];
char zip[10];
};

struct Person {
char name[50];
int age;
struct Address address;
};

int main() {
struct Person person1;

// Accessing members of the nested structure


strcpy(person1.name, "John Doe");
person1.age = 30;
strcpy(person1.address.street, "123 Main St");
strcpy(person1.address.city, "Anytown");
strcpy(person1.address.state, "CA");
strcpy(person1.address.zip, "12345");

// Displaying information
printf("Name: %s\n", person1.name);
printf("Age: %d\n", person1.age);
printf("Address: %s, %s, %s %s\n", person1.address.street, person1.address.city,
person1.address.state, person1.address.zip);

www.bookmyassignments.com MMT1
30
MMT 1 PROGRAMMING AND DATA STRUCTURES

return 0;
}
Accessing Members of a Structure or Nested Structure Using Pointers:

To access members of a structure or a nested structure using pointers, you can use the ->
operator when working with structure pointers. Here's an example:
#include <stdio.h>

struct Point {
int x;
int y;
};

int main() {
struct Point p1;
struct Point *ptr;

// Initialize the structure


p1.x = 10;
p1.y = 20;

// Initialize the pointer to the structure


ptr = &p1;

// Accessing members using pointers

www.bookmyassignments.com MMT1
31
MMT 1 PROGRAMMING AND DATA STRUCTURES

printf("x: %d\n", ptr->x);


printf("y: %d\n", ptr->y);

return 0;
}
In this example, we define a structure Point and create a pointer ptr to a Point structure. We
access the members x and y using the ptr->x and ptr->y syntax. This allows us to modify or
retrieve the values of the structure members through the pointer.

(c) Consider the following structure declaration of a doubly linked list:


struct dlink
{
int nodeid;
dlink *next;
dlink *prev;
} dlink t;
A pointer of the head of the linked list is maintained as a global variable,
whose
definition is
dlink t *head;
The function remove element(dlink t *rp) defined below needs to remove the
node pointed to rp and adjust the head. The first node’s prev and the last
node’s
next are NULL.
remove element(dlink t *rp)

www.bookmyassignments.com MMT1
32
MMT 1 PROGRAMMING AND DATA STRUCTURES

{
rp->prev->next = rp->next;
rp->next->prev = rp->prev;
if(head == rp)
head = rp->next;
}
Explain whether the function remove element() works properly or not.
The remove_element() function is intended to remove a node from a doubly linked list and
adjust the head pointer if necessary. Let's analyze the function and determine if it works
properly.
remove_element(dlink t *rp)
{
rp->prev->next = rp->next;
rp->next->prev = rp->prev;
if (head == rp)
head = rp->next;
}
rp->prev->next = rp->next;: This line updates the next pointer of the node before rp (i.e., rp-
>prev). It makes the previous node's next point to the node after rp, effectively removing rp
from the list.

rp->next->prev = rp->prev;: This line updates the prev pointer of the node after rp (i.e., rp-
>next). It makes the next node's prev point to the node before rp, ensuring the integrity of the
doubly linked list.

www.bookmyassignments.com MMT1
33
MMT 1 PROGRAMMING AND DATA STRUCTURES

if (head == rp) head = rp->next;: This condition checks if the node being removed is the head
of the list (the first node). If it is, it updates the head pointer to point to the node after rp,
effectively setting the next node as the new head.

Now, let's evaluate whether the remove_element() function works properly:

The function correctly updates the prev and next pointers of the nodes before and after rp,
ensuring that rp is removed from the list without causing any memory leaks or list integrity
issues.

The function also correctly updates the head pointer if the node being removed is the head of
the list.

7. (a) Write a C program which reads a line of text from keyboard, and writes
the line to
a file with lower case letters converted to upper case and vice-versa.
#include <stdio.h>
#include <ctype.h>

int main() {
char inputLine[1000];
char outputFile[100];
FILE *file;

// Get the input line from the user


printf("Enter a line of text: ");
fgets(inputLine, sizeof(inputLine), stdin);

www.bookmyassignments.com MMT1
34
MMT 1 PROGRAMMING AND DATA STRUCTURES

// Open a file for writing


printf("Enter the name of the output file: ");
fgets(outputFile, sizeof(outputFile), stdin);

// Remove newline characters from the input


for (int i = 0; inputLine[i] != '\0'; i++) {
if (inputLine[i] == '\n') {
inputLine[i] = '\0';
break;
}
}

// Open the output file for writing


file = fopen(outputFile, "w");
if (file == NULL) {
perror("Error opening the file");
return 1;
}

// Convert and write the line to the file


for (int i = 0; inputLine[i] != '\0'; i++) {
if (islower(inputLine[i])) {
fputc(toupper(inputLine[i]), file); // Convert to uppercase
} else if (isupper(inputLine[i])) {
fputc(tolower(inputLine[i]), file); // Convert to lowercase

www.bookmyassignments.com MMT1
35
MMT 1 PROGRAMMING AND DATA STRUCTURES

} else {
fputc(inputLine[i], file); // Keep non-alphabet characters as they are
}
}

// Close the file


fclose(file);

printf("Line written to file with case conversion.\n");

return 0;
}
The user is prompted to enter a line of text and the name of the output file.

The newline character at the end of the input line is removed to ensure proper processing.

The program opens the specified output file for writing. If the file cannot be opened, it
displays an error message and exits.

It then loops through each character in the input line. If the character is a lowercase letter, it
converts it to uppercase using toupper(). If it's an uppercase letter, it converts it to lowercase
using tolower(). Non-alphabet characters are written to the file as they are.

Finally, the program closes the output file and displays a message indicating that the line has
been written to the file with case conversion.

www.bookmyassignments.com MMT1
36
MMT 1 PROGRAMMING AND DATA STRUCTURES

(b) Define a structure of type hms containing three integer members, called
hour,
minute and second, respectively. Then define a union containing two
members,
each a structure of type hms. Call the union members local and home,
respectively. Declare a pointer variable called time that points to this union

#include <stdio.h>

// Define the structure of type 'hms'


struct hms {
int hour;
int minute;
int second;
};

// Define the union containing two members, each a structure of type 'hms'
union TimeUnion {
struct hms local;
struct hms home;
};

int main() {
// Declare a pointer variable 'time' that points to the union 'TimeUnion'
union TimeUnion *time;

www.bookmyassignments.com MMT1
37
MMT 1 PROGRAMMING AND DATA STRUCTURES

// Initialize 'time' to point to the 'local' member of the union


time = &((union TimeUnion) {.local = {10, 30, 45}});

// Access and print the values through the pointer 'time'


printf("Local Time: %02d:%02d:%02d\n", time->local.hour, time->local.minute, time-
>local.second);

// Modify the values through the pointer 'time'


time->local.hour = 12;
time->local.minute = 15;
time->local.second = 0;

// Access and print the modified values through the pointer 'time'
printf("Modified Local Time: %02d:%02d:%02d\n", time->local.hour, time-
>local.minute, time->local.second);

return 0;
}
We first define the hms structure to represent hours, minutes, and seconds.
Then, we define the TimeUnion union containing two members: local and home, both of
which are structures of type hms.
Next, we declare a pointer variable time of type union TimeUnion*, which points to the union.
We initialize time to point to the local member of the union using a designated initializer.
We access and print the values of the local member through the time pointer.
We modify the values of the local member through the time pointer and then access and print
the modified values.

www.bookmyassignments.com MMT1
38
MMT 1 PROGRAMMING AND DATA STRUCTURES

(c) Write the inorder, preorder and postorder traversals of the following
binary search tree

Inorder Traversal: Visit the left branch, then the current node, and finally, the right branch.
This gives us the nodes in ascending order for a binary search tree.

Preorder Traversal: Visit the current node before its child nodes. The root node is always the
first node visited.

Postorder Traversal: Visit the current node after its child nodes.
A
/\
B H
/| |\
CE IJ
/| |
DFG
Inorder Traversal:

www.bookmyassignments.com MMT1
39
MMT 1 PROGRAMMING AND DATA STRUCTURES

Visit the left subtree of B, which starts with C.


In C's subtree, visit D (C's left child), then C, and then we move to F (C's right child).
Visit the left child of F, which is G, then F, and since F has no right child, we move up.
After finishing with C's subtree, we visit B, then move to E (B's right child), which has no
children.
After B's subtree, we move up to A, then visit A.
After A, we visit A's right subtree, starting with H.
Since I is the left child of H, we visit I first, then H, and finally, J (H's right child).
Preorder Traversal:

Visit A first, as it is the root.


Visit A's left child B, then B's left child C, followed by C's left child D.
Since D has no children, we move up to C and then visit C's right child F, followed by F's left
child G.
After completing the left subtree of B, we visit E, which has no children.
After completing the left subtree of A, we move to A's right child H, then to H's left child I.
Finally, we visit H's right child J.
Postorder Traversal:

Start with the leftmost child, which is D, then move up to its parent C. Since C has a right
child, we visit F and its left child G.
After visiting G, we move up to F, then to C, and finally to B, as C has no right sibling.
We then visit E, which is the right child of B.
After completing the left subtree of A, we visit A's right subtree starting with I (H's left child),
then J (H's right child), and finally H itself.
After completing both subtrees of A, we visit A last.

www.bookmyassignments.com MMT1
40
MMT 1 PROGRAMMING AND DATA STRUCTURES

8. Write a function that evaluates an expression in RPN that is given as a


string.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>

#define MAX_STACK_SIZE 100

// Define a stack structure for operands


struct Stack {
int data[MAX_STACK_SIZE];
int top;
};

// Initialize an empty stack


void initStack(struct Stack *stack) {
stack->top = -1;
}

// Push an operand onto the stack


void push(struct Stack *stack, int operand) {
if (stack->top >= MAX_STACK_SIZE - 1) {
WHATSAPP-7980298614
printf("Stack overflow\n");
exit(1);
}

www.bookmyassignments.com MMT1
41
MMT 1 PROGRAMMING AND DATA STRUCTURES

stack->data[++stack->top] = operand;
}

// Pop an operand from the stack


int pop(struct Stack *stack) {
if (stack->top < 0) {
printf("Stack underflow\n");
exit(1);
}
return stack->data[stack->top--];
}

// Evaluate an expression in RPN


int evaluateRPN(char *expression) {
struct Stack operandStack;
initStack(&operandStack);

int i = 0;
while (expression[i] != '\0') {
if (isdigit(expression[i])) {
// Convert character to integer and push onto the stack
push(&operandStack, expression[i] - '0');
} else if (expression[i] == ' ') {
// Ignore spaces
} else {
// Operator encountered, perform the operation

www.bookmyassignments.com MMT1
42
MMT 1 PROGRAMMING AND DATA STRUCTURES

int operand2 = pop(&operandStack);


int operand1 = pop(&operandStack);
switch (expression[i]) {
case '+':
push(&operandStack, operand1 + operand2);
break;
case '-':
push(&operandStack, operand1 - operand2);
break;
case '*':
push(&operandStack, operand1 * operand2);
break;
case '/':
if (operand2 == 0) {
printf("Division by zero\n");
exit(1);
}
push(&operandStack, operand1 / operand2);
break;
default:
printf("Invalid operator: %c\n", expression[i]);
exit(1);
}
}
WHATSAPP-7980298614
i++;
}

www.bookmyassignments.com MMT1
43
MMT 1 PROGRAMMING AND DATA STRUCTURES

// The result should be on the stack


if (operandStack.top == 0) {
return operandStack.data[0];
} else {
printf("Invalid expression\n");
exit(1);
}
}

int main() {
char expression[] = "3 4 + 2 * 7 /"; // Example RPN expression: (3 + 4) * 2 / 7 = 2
int result = evaluateRPN(expression);
printf("Result: %d\n", result);
return 0;
}
We define a Stack structure to implement a stack for operands.
The initStack, push, and pop functions are used to initialize, push, and pop operands
onto/from the stack.
The evaluateRPN function takes an RPN expression as input and evaluates it using a stack.
It iterates through the input expression character by character.
If a digit is encountered, it is converted to an integer and pushed onto the operand stack.
If an operator is encountered, it pops two operands from the stack, performs the operation,
and pushes the result back onto the stack.
Finally, the result is retrieved from the stack, and error handling is included to handle division
by zero or invalid operators.

WHATSAPP-7980298614
www.bookmyassignments.com MMT1
44
MMT 1 PROGRAMMING AND DATA STRUCTURES

9. (a) Explain the meaning of the terms garbage collection, fragmentation,


relocation and compaction.
Garbage Collection:

Garbage collection is a memory management technique used to automatically reclaim


memory that is no longer in use or referenced by the program.
In programming languages that use garbage collection (such as Java, C#, and some JavaScript
environments), the system periodically identifies and frees up memory occupied by objects
that are no longer reachable, thus preventing memory leaks and reducing the burden on the
programmer to manually manage memory deallocation.
Fragmentation:

Fragmentation refers to the phenomenon where the available memory becomes divided into
smaller, non-contiguous blocks, making it challenging to allocate larger chunks of memory
even when there is sufficient total memory.
There are two types of fragmentation:
Internal Fragmentation: Occurs when memory is allocated in fixed-size blocks, and some
portion of each block is unused due to the size of the allocated data being smaller than the
block size.
External Fragmentation: Occurs when free memory blocks are scattered throughout the
memory space, making it difficult to allocate a contiguous block of memory even though the
total free memory is sufficient.
Relocation:

Relocation is a process where the operating system adjusts the absolute memory addresses
used by a program during its execution.
In modern computer systems with virtual memory, programs are typically loaded into
different memory addresses each time they run. Relocation ensures that the program's
memory references are adjusted to reflect the actual memory addresses where it is loaded.

www.bookmyassignments.com WHATSAPP-7980298614 MMT1


45
MMT 1 PROGRAMMING AND DATA STRUCTURES

Relocation is essential for ensuring that programs can run independently of their absolute
memory locations and do not interfere with each other.
Compaction:

Compaction is a memory management technique used to reduce external fragmentation by


rearranging allocated and free memory blocks to create a larger, contiguous block of free
memory.
Compaction is often used in memory management systems that support dynamic memory
allocation to make better use of available memory and prevent fragmentation.
While compaction can be effective, it can also be a time-consuming process and may not
always be feasible in real-time systems.

(b) What do you understand by file organisation? Explain the methods of file
organisation.
Sequential File Organization:

In a sequential file, records are stored one after another in a linear order. Each record contains
a unique key field by which the records are arranged.
Records can only be accessed in a sequential manner, starting from the beginning of the file
and proceeding sequentially to the desired record.
It is efficient for batch processing but not suitable for random access or frequent updates.
Indexed Sequential File Organization:

Indexed sequential files combine the benefits of both sequential and indexed files.
Data is organized sequentially, but an index structure (like a B-tree or an index table) is used
to store key-value pairs that map keys to file addresses.
The index allows for faster access to specific records, making it suitable for applications
requiring both sequential and random access.

WHATSAPP-7980298614
www.bookmyassignments.com MMT1
46
MMT 1 PROGRAMMING AND DATA STRUCTURES

Random (Direct) File Organization:

In a random file, records are stored independently of each other, and each record can be
accessed directly using a unique identifier or key.
Accessing a specific record does not require reading through other records, making it efficient
for random access.
Common methods for random file organization include hash files and ISAM (Indexed
Sequential Access Method).
Indexed File Organization:

Indexed files use an index table to store key-to-record mappings. Each entry in the index table
points to a specific record.
Records are not necessarily stored in any particular order. Instead, the index allows for
efficient access based on keys.
Indexed files are suitable for applications where random access to records is frequent.
Heap File Organization:

In a heap file, records are inserted into the file as they arrive, without any specific order.
There is no inherent organization or sorting of records within the file.
To retrieve specific records, a full file scan may be required, which can be inefficient for large
files.
Clustered File Organization:

Clustered files organize records based on a particular attribute or key.


Records with the same attribute value are stored together in clusters or blocks.
Clustered files are efficient for range queries and retrieval of related data.
Partitioned File Organization:
WHATSAPP-7980298614
www.bookmyassignments.com MMT1
47
MMT 1 PROGRAMMING AND DATA STRUCTURES

Partitioned files divide data into multiple partitions or segments based on certain criteria, such
as ranges of values.
Each partition can have its own file organization method, optimizing access for different
portions of the data.
This approach is often used in distributed databases.

WHATSAPP-7980298614

www.bookmyassignments.com MMT1
48
MMT 1 PROGRAMMING AND DATA STRUCTURES

www.bookmyassignments.com MMT1
49
MMT 1 PROGRAMMING AND DATA STRUCTURES

www.bookmyassignments.com MMT1

You might also like