Term-End Examination
June, 2023
MCS–201: PROGRAMMING IN C AND PYTHON
Ans. 1(a) Ref: See Chpater-1, Page No. 4-5, “Syntax and Semantic Errors”
Also Add: Difference Between Syntax Errors and Semantic Errors
Aspect Syntax Error Semantic Error
Errors that occur due to incorrect use Errors that occur due to incorrect logic or
Definition
of language rules. meaning in the code.
Detected by the compiler during Detected at runtime or through logical
Detection
compilation. analysis.
Missing semicolon, incorrect Incorrect algorithm, using a variable
Cause keyword usage, unmatched without initialization, incorrect type
parentheses, etc. usage, etc.
The program may compile but will not
Effect The program will not compile.
produce the expected output.
Fixing the syntax according to Fixing the logic to produce the correct
Correction
language rules. result.
Example of a Syntax Error in C
#include <stdio.h>
int main() {
printf("Hello, World!") // Missing semicolon (;) at the end of the statement
return 0;
}
Error: The compiler will throw an error because a semicolon (;) is missing at the end of the
printf statement.
Example of a Semantic Error in C
#include <stdio.h>
int main() {
int a = 5, b = 0;
int result = a / b; // Division by zero (logical error)
printf("Result: %d", result);
return 0;
}
Error: The program will compile successfully but will cause a runtime error (division by
zero), leading to an undefined behavior or crash.
Ans. 1(b) C Program to Print the Size of Basic Data Types
#include <stdio.h> // Include standard input-output header file
int main() {
// Print the size of int data type
printf("Size of int: %lu bytes\n", sizeof(int));
// Print the size of char data type
printf("Size of char: %lu byte\n", sizeof(char));
// Print the size of float data type
printf("Size of float: %lu bytes\n", sizeof(float));
// Print the size of double data type
printf("Size of double: %lu bytes\n", sizeof(double));
return 0; // Return 0 to indicate successful execution
}
Explanation:
1. The program includes the stdio.h library for input-output functions.
2. The sizeof operator is used to determine the memory size (in bytes) of basic data
types.
3. The %lu format specifier is used for sizeof() because it returns a value of type size_t,
which is an unsigned long integer.
4. The output is displayed in a user-friendly format with appropriate labels.
Sample Output (May vary based on system architecture)
Size of int: 4 bytes
Size of char: 1 byte
Size of float: 4 bytes
Size of double: 8 bytes
Ans. 1(c) Ref: See Chapter-2, Page No. 17, “Conditional Operator (?:)(ternary operator)
Also Add:
Understanding the Given Code
#include <stdio.h>
int main()
{
int a = 10, b = 15, x;
x = (a < b) ? ++a : ++b;
printf("x = %d a = %d b = %d\n", x, a, b);
return 0;
}
Step-by-Step Execution
1. Variable Initialization:
a = 10, b = 15
2. Ternary Operation:
x = (a < b) ? ++a : ++b;
o Condition a < b (i.e., 10 < 15) is true.
o Since the condition is true, ++a (pre-increment) executes, making a = 11.
o The value of a (now 11) is assigned to x.
3. Final Values of Variables:
a = 11, b = 15, x = 11
4. Output of printf:
x = 11 a = 11 b = 15
Ans. 1(d) Ref: See Chapter-6, Page No. 52, “DECLARATION OF STRUCTURES” and
Page No. 53-54, “UNIONS”
Ans. 1(e) Ref: See Chapter-9, Page No. 76, “IronPython”
Also Add: Structure of a Python Program
A Python program typically consists of the following components:
Comments: These are non-executable statements used to provide explanations or
documentation within the code.
Imports: These statements are used to bring in external modules or libraries into the
program.
Global Variables and Constants: These are defined at the beginning of the program
and can be accessed throughout the program.
Functions and Classes: These are the building blocks of a Python program, allowing
for modular and object-oriented programming.
Main Body: This is where the main execution of the program takes place, often
containing conditional statements, loops, and function calls.
Here's a block diagram illustrating the structure of a Python program:
Ans. 1(f) Ref: See Chapter-10, Page No. 86-87, “Dictionaries”, “Sets”
Ans. 1(g) Ref: See Chapter-13, Page No. 115, “POLYMORPHISM” and Page No. 116, Q.
No. 2
Ans. 1(h) Ref: See Chapter-15, Page No. 126, Q. No. 3
Ans. 2(a) The connect() method of the [Link] interface in Python is used to
establish a connection to a MySQL database. It returns a connection object that allows
interaction with the database.
Arguments of the connect() Method
The connect() method takes several arguments, the most common ones being:
host: The hostname or IP address of the MySQL server (e.g., "localhost").
user: The MySQL username (e.g., "root").
password: The password for the MySQL user.
database: The name of the database to connect to (optional when creating a new
database).
port: The port number for MySQL (default is 3306).
auth_plugin: The authentication plugin to use (e.g., "mysql_native_password").
Python Code to Create and Connect to Emp_DB
import [Link]
# Establish connection to MySQL server
conn = [Link](
host="localhost", # Change as per your server
user="root", # Replace with your MySQL username
password="password" # Replace with your MySQL password
)
# Create a cursor object
cursor = [Link]()
# Create database Emp_DB
[Link]("CREATE DATABASE IF NOT EXISTS Emp_DB")
# Close the initial connection
[Link]()
# Connect to the newly created database Emp_DB
conn = [Link](
host="localhost",
user="root",
password="password",
database="Emp_DB"
)
# Print confirmation
if conn.is_connected():
print("Successfully connected to Emp_DB")
# Close connection
[Link]()
Ans. 2(b) Ref: See Chapter-9, Page No. 76-77, Q. No. 3
Also Add:
Creating a Module: Arithmetic_op.py
Let's create a Python module named Arithmetic_op.py that contains functions to perform
basic arithmetic operations.
Arithmetic_op.py
# Arithmetic_op.py
def add(a, b):
"""Returns the sum of two numbers"""
return a + b
def subtract(a, b):
"""Returns the difference of two numbers"""
return a - b
def multiply(a, b):
"""Returns the product of two numbers"""
return a * b
def divide(a, b):
"""Returns the quotient of two numbers. Handles division by zero."""
if b == 0:
return "Error: Division by zero is not allowed."
return a / b
Using the Module in Another Python Script
Now, let's create another script ([Link]) to import and use this module.
[Link]
# Importing the Arithmetic_op module
import Arithmetic_op
# Input values
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
# Performing operations using the module
sum_result = Arithmetic_op.add(num1, num2)
difference = Arithmetic_op.subtract(num1, num2)
product = Arithmetic_op.multiply(num1, num2)
quotient = Arithmetic_op.divide(num1, num2)
# Printing the results
print(f"Addition: {num1} + {num2} = {sum_result}")
print(f"Subtraction: {num1} - {num2} = {difference}")
print(f"Multiplication: {num1} × {num2} = {product}")
print(f"Division: {num1} ÷ {num2} = {quotient}")
Ans. 3(a) # (i) Copy a file [Link] to [Link]
import shutil
[Link]('[Link]', '[Link]')
(ii) Reading a file using with statement
with open('[Link]', 'r') as file:
content = [Link]()
print("File Content:")
print(content)
(iii) Writing a file using with statement
with open('[Link]', 'w') as file:
[Link]("This is a new file created using the with statement.\n")
[Link]("It allows easy file handling without explicit closing.")
(iv) Appending a file using with statement
with open('[Link]', 'a') as file:
[Link]("\nAppending a new line to the existing file.")
Ans. 3(b) Function to calculate factorial of a number
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
# Function to calculate exponential series e^x
def exponential_series(x, n_terms=10):
sum_exp = 0
for n in range(n_terms):
sum_exp += (x ** n) / factorial(n)
return sum_exp
# Input from user
x = float(input("Enter the value of x: "))
n_terms = int(input("Enter the number of terms for the series: "))
# Compute e^x
result = exponential_series(x, n_terms)
# Display result
print(f"The calculated value of e^{x} using {n_terms} terms is: {result}")
Ans. 4(a) #include <stdio.h>
#include <ctype.h> // For tolower() function
int main() {
char text[1000]; // Array to store user input text
int vowels = 0, commas = 0, fullStops = 0; // Counters for vowels, commas, and full stops
int i = 0;
// Prompt user for input
printf("Enter a text (max 1000 characters):\n");
fgets(text, sizeof(text), stdin); // Read input including spaces
// Process each character in the input string
while (text[i] != '\0') {
char ch = tolower(text[i]); // Convert character to lowercase for uniformity
// Check if character is a vowel
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
}
// Check if character is a comma
else if (ch == ',') {
commas++;
}
// Check if character is a full stop (period)
else if (ch == '.') {
fullStops++;
}
i++; // Move to the next character
}
// Display the results
printf("\nStatistics:\n");
printf("Vowels: %d\n", vowels);
printf("Commas: %d\n", commas);
printf("Full Stops: %d\n", fullStops);
return 0;
}
Ans. 4(b) Ref: See Chapter-2, Page No. 19-20, Q. No. 4
Also Add:
Preprocessors in C
Preprocessors in C are directives that are processed before the actual compilation of the code
begins. They start with a # symbol and perform various tasks such as including files, defining
constants, macros, and conditional compilation.
Some common preprocessor directives:
#include – Includes header files.
#define – Defines macros.
#ifdef, #ifndef, #endif – Used for conditional compilation.
Using #define to Define Macros
The #define directive is used to create macros, which are symbolic constants or expressions.
Macros are replaced by their defined values before the program is compiled.
Example:
#define PI 3.14159
This replaces PI with 3.14159 throughout the code.
C Program to Calculate Area Using a Macro
The following program defines a macro AREA to calculate the area of a rectangle using
length * width. The user provides the length and width as input.
#include <stdio.h>
// Macro definition
#define AREA(length, width) (length * width)
int main() {
float length, width, area;
// User input
printf("Enter length: ");
scanf("%f", &length);
printf("Enter width: ");
scanf("%f", &width);
// Using macro to calculate area
area = AREA(length, width);
// Displaying result
printf("The area of the rectangle is: %.2f\n", area);
return 0;
}
Ans. 5(a) #include <stdio.h>
#define SIZE 3 // Define the size of the matrix
// Function to take input for a 3x3 matrix
void inputMatrix(int matrix[SIZE][SIZE], const char *name) {
printf("Enter elements for matrix %s (3x3):\n", name);
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
printf("Element [%d][%d]: ", i + 1, j + 1);
scanf("%d", &matrix[i][j]);
}
}
}
// Function to add two matrices
void addMatrices(int matrix1[SIZE][SIZE], int matrix2[SIZE][SIZE], int result[SIZE]
[SIZE]) {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
}
// Function to display a 3x3 matrix
void displayMatrix(int matrix[SIZE][SIZE], const char *name) {
printf("\nMatrix %s:\n", name);
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
}
int main() {
int matrix1[SIZE][SIZE], matrix2[SIZE][SIZE], result[SIZE][SIZE];
// Input matrices from user
inputMatrix(matrix1, "A");
inputMatrix(matrix2, "B");
// Perform matrix addition
addMatrices(matrix1, matrix2, result);
// Display matrices
displayMatrix(matrix1, "A");
displayMatrix(matrix2, "B");
displayMatrix(result, "A + B (Result)");
return 0;
}
Ans. 5(b)(i) Ref: See Chapter-1, Page No. 5, “Linker Errors”
Ans, 5(b)(ii) Ref: See Chapter-3, Page No. 31-32, The Break Statement and The Continue
Statement”
Ans. 5(b)(iii) malloc()
malloc() (Memory Allocation) is a standard library function in C used to allocate a
specified amount of memory dynamically.
Returns a pointer to the allocated memory block but does not initialize it.
Syntax: void* malloc(size_t size);
Example:
int *ptr = (int*) malloc(5 * sizeof(int));
If memory allocation fails, malloc() returns NULL.
Ans. 5(b)(iv) calloc()
calloc() (Contiguous Allocation) is a standard library function used to allocate
memory for an array of elements.
It initializes the allocated memory block to zero.
Syntax: void* calloc(size_t num, size_t size);
Example:
int *ptr = (int*) calloc(5, sizeof(int));
Returns NULL if memory allocation fails.