[go: up one dir, main page]

0% found this document useful (0 votes)
9 views19 pages

MCS 201 em 2024 1

The document outlines the MCS-201 solved assignment for the 2023-24 academic year, focusing on programming in C and Python. It includes details about the assignment structure, marking scheme, and submission deadlines, along with specific questions and example code related to C programming concepts and Python database handling. The assignment consists of eight questions divided into two sections, covering topics such as function parameter passing, matrix operations, MySQL connections, and data manipulation using Pandas.

Uploaded by

balrambadcs
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)
9 views19 pages

MCS 201 em 2024 1

The document outlines the MCS-201 solved assignment for the 2023-24 academic year, focusing on programming in C and Python. It includes details about the assignment structure, marking scheme, and submission deadlines, along with specific questions and example code related to C programming concepts and Python database handling. The assignment consists of eight questions divided into two sections, covering topics such as function parameter passing, matrix operations, MySQL connections, and data manipulation using Pandas.

Uploaded by

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

MCS-201

SOLVED ASSIGNMENT
2023-24 IN ENGLISH
Course Code MCS-201
Course Title Programming in C and PYTHON
Assignment Number PGDCA(I)/201/Assignment/2024
Maximum Marks 100
Weightage 30%
30th April, 2024 (for January session) Last Date of Submission 31st October, 2024 (for July
session)
There are eight questions in this assignment (four in each section i.e. Section A and Section
B) which carries 80 marks. Each question carries 10 marks. Rest 20 marks are for viva-
voce. Answer all the questions from both the sections i.e. Section A and Section B. You may
use illustrations and diagrams to enhance the explanations. Include the screen layouts also
along with your assignment responses. Please go through the guidelines regarding
assignments given in the Programme Guide for the format of presentation.
SECTION-A (C-Programming)
Question 1: Briefly discuss the concept of "Call by value" and "Call by reference". Give
example code in C for each. Support your code with suitable comments.
Ans. "Call by value" and "Call by reference" are two different ways parameters can be passed to
a function in programming languages like C.

1. **Call by Value**:
- In call by value, a copy of the actual parameter's value is passed to the function. Changes
made to the parameter inside the function do not affect the actual parameter.
- It's like giving a photocopy of a document to someone; changes made to the photocopy don't
affect the original document.

Example code in C:

Page 1 of 18
Output:

In this example, even though `swapByValue` function swaps the values of `x` and `y`, it does not
affect the original variables `a` and `b` because they are passed by value.

Page 2 of 18
2. **Call by Reference**:
- In call by reference, instead of passing a copy of the value, a reference (i.e., address) of the
actual parameter is passed. Changes made to the parameter inside the function affect the actual
parameter.
- It's like giving the original document to someone; changes made to the document directly
affect the original.

Example code in C:

Output:

Page 3 of 18
In this example, `swapByReference` function swaps the values of `*x` and `*y`, which are
references to the original variables `a` and `b`. Thus, changes made inside the function affect the
original variables.

Question 2: Briefly discuss the relation between pointers and arrays, giving suitable
example. Write a program in C, to print transpose of a 2D matrix entered by a user. Also
give comments.
Ans. In C, arrays and pointers are closely related. An array name can be thought of as a constant
pointer to the first element of the array. This means that you can use pointer arithmetic with
arrays just like you would with pointers.

Here's a brief example to illustrate this relationship:

```c
#include <stdio.h>

int main() {
int arr[5] = {1, 2, 3, 4, 5};

// Pointer to the first element of the array


int *ptr = arr;

// Using pointer arithmetic to access array elements


printf("First element: %d\n", *ptr);
printf("Second element: %d\n", *(ptr + 1));

Page 4 of 18
return 0;
}
```

Output:
```
First element: 1
Second element: 2
```

In this example, `ptr` is a pointer to the first element of the array `arr`. Using pointer arithmetic,
we can access other elements of the array.

Now, let's move to the program to print the transpose of a 2D matrix entered by a user:

```c
#include <stdio.h>

#define ROWS 3
#define COLS 3

// Function to print the transpose of a matrix


void printTranspose(int mat[ROWS][COLS]) {
int transpose[COLS][ROWS]; // Transpose matrix

// Calculating transpose
for (int i = 0; i < ROWS; ++i) {
for (int j = 0; j < COLS; ++j) {
transpose[j][i] = mat[i][j];

Page 5 of 18
}
}

// Printing transpose matrix


printf("Transpose of the matrix:\n");
for (int i = 0; i < COLS; ++i) {
for (int j = 0; j < ROWS; ++j) {
printf("%d\t", transpose[i][j]);
}
printf("\n");
}
}

int main() {
int matrix[ROWS][COLS];

// Getting input for matrix elements from user


printf("Enter elements of %dx%d matrix:\n", ROWS, COLS);
for (int i = 0; i < ROWS; ++i) {
for (int j = 0; j < COLS; ++j) {
scanf("%d", &matrix[i][j]);
}
}

// Printing original matrix


printf("Original matrix:\n");
for (int i = 0; i < ROWS; ++i) {
for (int j = 0; j < COLS; ++j) {

Page 6 of 18
printf("%d\t", matrix[i][j]);
}
printf("\n");
}

// Calling function to print transpose


printTranspose(matrix);

return 0;
}
```

This program prompts the user to enter elements of a 3x3 matrix, prints the original matrix,
calculates and prints its transpose. The `printTranspose` function calculates the transpose of the
matrix and then prints it.

Question 3: Write an algorithm to find the slope of a line segment whose end point
coordinates are (x1, y1) and (x2, y2). The algorithm gives output whether the slope is
positive, negative or zero. Transform your algorithm into C program.

Note: Slope of line segment =

Ans. Here is an algorithm to find the slope of a line segment whose end point coordinates are
(x1, y1) and (x2, y2):

Page 7 of 18
This algorithm first prompts the user to enter the coordinates of the two end points of the line
segment. Then, it calculates the slope using the formula (y2 - y1) / (x2 - x1). Finally, it prints the
slope, along with a message indicating whether it is positive, negative, or zero.

Question 4: Write an algorithm to find the HCF (Highest Common Factor) of the two
numbers entered by a user. Transform your algorithm into a C program, support your
program with suitable comments.
Ans. Here's an algorithm to find the Highest Common Factor (HCF) of two numbers:

Algorithm to Find HCF of Two Numbers:


1. Take input of two numbers, let's call them num1 and num2.
2. Find the minimum of num1 and num2, let's call it min.
3. Initialize a variable called hcf to store the highest common factor.
4. Start a loop from 1 until min:

Page 8 of 18
- If both num1 and num2 are divisible by the current number:
- Update hcf to the current number.
5. The value stored in hcf at the end of the loop will be the HCF of num1 and num2.

Now, let's transform this algorithm into a C program:

```c
#include <stdio.h>

// Function to find the HCF of two numbers


int findHCF(int num1, int num2) {
int min = (num1 < num2) ? num1 : num2; // Find the minimum of num1 and num2

int hcf = 1; // Initialize hcf to 1

// Loop to find HCF


for (int i = 1; i <= min; ++i) {
if (num1 % i == 0 && num2 % i == 0) {
hcf = i; // Update hcf if both numbers are divisible by i
}
}

return hcf; // Return the HCF


}

int main() {
int num1, num2;

Page 9 of 18
// Getting input of two numbers from user
printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter second number: ");
scanf("%d", &num2);

// Calling function to find HCF and printing the result


printf("HCF of %d and %d is: %d\n", num1, num2, findHCF(num1, num2));

return 0;
}
```

This program prompts the user to enter two numbers, then calculates and prints their HCF using
the `findHCF` function. The function iterates through numbers from 1 to the minimum of the two
input numbers, checking if both numbers are divisible by each number. If they are, it updates the
HCF variable. Finally, it returns the HCF found.

SECTION-B (PYTHON-Programming)
Question 1: Discuss the connect() method of MySQL. Connector interface. List the
arguments involved with connect() method. Write Python code to create database
student_DB and to connect to student_DB (make suitable assumptions wherever
necessary).
Ans. In MySQL Connector/Python, the `connect()` method is used to establish a connection to a
MySQL database. It is part of the Connector interface, which provides the methods to connect to
MySQL databases and execute SQL statements.

Arguments involved with the `connect()` method typically include:

1. **host**: The hostname or IP address of the MySQL server.


2. **user**: The username used to authenticate with the MySQL server.

Page 10 of 18
3. **password**: The password used to authenticate with the MySQL server.
4. **database**: The name of the database to connect to.
5. **port**: The port number where the MySQL server is listening (default is 3306).
6. **charset**: The character set to use for the connection (default is 'utf8').
7. **ssl_ca**: The path to the SSL certificate authority file.
8. **ssl_cert**: The path to the SSL certificate file.
9. **ssl_key**: The path to the SSL key file.
10. **ssl_verify_cert**: Whether to verify the server certificate (default is False).

Now, let's write Python code to create a database named "student_DB" and connect to it:

```python
import mysql.connector

# Assuming MySQL server is running on localhost, with default port and authentication
host = 'localhost'
user = 'your_username'
password = 'your_password'
database = 'student_DB'

# Establishing connection to MySQL server


try:
connection = mysql.connector.connect(
host=host,
user=user,
password=password
)

Page 11 of 18
# Creating a cursor object to execute SQL queries
cursor = connection.cursor()

# Creating the student_DB database if it doesn't exist


cursor.execute("CREATE DATABASE IF NOT EXISTS {}".format(database))

print("Database '{}' created successfully.".format(database))

except mysql.connector.Error as error:


print("Error while connecting to MySQL:", error)

finally:
# Closing the connection
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection closed.")
```

This code will create a database named "student_DB" if it doesn't already exist. It assumes that
the MySQL server is running on localhost, and the username and password provided have
sufficient privileges to create databases. Adjust the `host`, `user`, and `password` variables as per
your MySQL server configuration.

Question 2: What are Pandas ? Write steps to import, read and print a CSV file using
Pandas. Also, transform your steps in to suitable code in Python.
Ans. Pandas is a powerful Python library used for data manipulation and analysis. It provides
data structures and functions to efficiently manipulate large datasets. Pandas is widely used for
tasks such as data cleaning, exploration, transformation, and visualization.

Page 12 of 18
Here are the steps to import, read, and print a CSV file using Pandas:

1. **Import Pandas**: First, you need to import the Pandas library in your Python script.

2. **Read CSV File**: Use the `pd.read_csv()` function to read the CSV file into a Pandas
DataFrame. Specify the path to the CSV file as the argument to this function.

3. **Print DataFrame**: You can use the `print()` function or simply write the DataFrame
variable name to print the contents of the DataFrame.

Here's the code in Python:

```python
import pandas as pd

# Step 1: Import Pandas

# Step 2: Read CSV File


# Assume the CSV file is named 'data.csv' and is located in the current directory
data = pd.read_csv('data.csv')

# Step 3: Print DataFrame


print(data)
```

This code assumes that you have a CSV file named 'data.csv' in the same directory as your
Python script. Adjust the path accordingly if your CSV file is located elsewhere.

Page 13 of 18
This code will read the CSV file into a Pandas DataFrame named `data` and print its contents.
You can then perform various operations on this DataFrame using Pandas functions and
methods.

Question 3: Write steps to create a package. Apply these steps to create a package named
volume and create 3 modules in it named cube, cuboid and sphere, having function to
calculate volume of the cube, cuboid and sphere respectively. Import the modules defined
in the package and use the defined functions for calculation of volume respectively.
Ans. To create a Python package and modules for calculating volumes, follow these steps:

### Steps to create a package:

1. **Create a directory for the package**: Choose a directory where you want to create the
package. This directory will contain the package and its modules.

2. **Create a `__init__.py` file**: This file tells Python that the directory should be treated as a
package. This file can be empty or contain initialization code for the package.

3. **Create modules within the package**: Each module will be a separate Python file
containing functions related to a specific task.

4. **Import and use the package**: You can import the package and its modules into your
Python scripts and use the functions defined within them.

### Steps to create the `volume` package with modules:

1. Create a directory named `volume`.


2. Inside the `volume` directory, create the following files:
- `__init__.py`: Leave it empty.
- `cube.py`: Define a function to calculate the volume of a cube.
- `cuboid.py`: Define a function to calculate the volume of a cuboid.

Page 14 of 18
- `sphere.py`: Define a function to calculate the volume of a sphere.

### Example code:

#### 1. `cube.py`:
```python
def cube_volume(side_length):
return side_length ** 3
```

#### 2. `cuboid.py`:
```python
def cuboid_volume(length, width, height):
return length * width * height
```

#### 3. `sphere.py`:
```python
import math

def sphere_volume(radius):
return (4/3) * math.pi * radius ** 3
```

### Using the package and its modules:

You can import the functions from the `volume` package and use them as follows:

Page 15 of 18
```python
from volume import cube, cuboid, sphere

# Calculate volume of a cube


cube_volume = cube.cube_volume(5)
print("Volume of cube:", cube_volume)

# Calculate volume of a cuboid


cuboid_volume = cuboid.cuboid_volume(3, 4, 5)
print("Volume of cuboid:", cuboid_volume)

# Calculate volume of a sphere


sphere_volume = sphere.sphere_volume(4)
print("Volume of sphere:", sphere_volume)
```

This code will import the functions from the `cube`, `cuboid`, and `sphere` modules within the
`volume` package and use them to calculate volumes accordingly.

Question 4: What does map( ) function do ? Write a program in Python to print the cube of
the numbers present in the list, by using map( ) function.
Ans. The `map()` function in Python applies a given function to each item of an iterable (like a
list) and returns an iterator that yields the results. It takes two arguments: the function to apply
and the iterable to apply it to.

Here's a Python program to print the cube of numbers present in a list using the `map()` function:

```python
# Define a function to calculate the cube of a number
def cube(x):

Page 16 of 18
return x ** 3

# List of numbers
numbers = [1, 2, 3, 4, 5]

# Use map() function to apply the cube function to each element of the list
cubes = map(cube, numbers)

# Print the result


print("Cubes of numbers in the list:")
for num, cube_result in zip(numbers, cubes):
print(f"The cube of {num} is {cube_result}")
```

Output:
```
Cubes of numbers in the list:
The cube of 1 is 1
The cube of 2 is 8
The cube of 3 is 27
The cube of 4 is 64
The cube of 5 is 125
```

In this program:
- We define a function `cube(x)` that calculates the cube of a number `x`.
- We have a list `numbers` containing integers.
- We use the `map()` function to apply the `cube()` function to each element of the `numbers` list.

Page 17 of 18
- The result is an iterator containing the cube of each number in the list.
- We iterate over the original list and the result of `map()` simultaneously using `zip()` and print
the cubes of each number.

Page 18 of 18

You might also like