POST GRADUATE DIPOLOMA IN COMPUTER APPLICATIONS (PGDCA-NEW) - Apna Bhai Hai Na (अपना भाई है ना)

Wednesday, 24 May 2023

POST GRADUATE DIPOLOMA IN COMPUTER APPLICATIONS (PGDCA-NEW)

POST GRADUATE DIPOLOMA IN COMPUTER APPLICATIONS (PGDCA-NEW) 

Term-End Examination December, 2021 MCS-201 : 

PROGRAMMING IN C AND PYTHON 

Time : 3 Hours Maximum Marks :100 Weightage : 70% Note : 

Question 

No. 1 is compulsory. Attempt any three questions from the rest. 

Ans.  

Recursion and iteration are two different approaches to solving problems in programming. 


Recursion involves solving a problem by breaking it down into smaller, similar subproblems and solving them recursively until a base case is reached. In a recursive function, the function calls itself within its own definition. Recursion is often used when a problem can be naturally divided into smaller subproblems.


Iteration, on the other hand, involves solving a problem using loops and repetitive statements. It uses a loop construct, such as a for loop, while loop, or do-while loop, to repeatedly execute a block of code until a certain condition is met. Iteration is useful when a problem can be solved by repeatedly executing a certain set of instructions.


Here's an example of a recursive function to calculate the factorial of a number in C:


```c

#include <stdio.h>


int factorial(int n) {

    if (n == 0) {

        return 1; // Base case: factorial of 0 is 1

    } else {

        return n * factorial(n - 1); // Recursive call to calculate factorial

    }

}


int main() {

    int num = 5;

    int result = factorial(num);

    printf("Factorial of %d is %d\n", num, result);

    return 0;

}

```


And here's an example of an iterative loop to calculate the factorial of a number in C:


```c

#include <stdio.h>


int factorial(int n) {

    int result = 1;

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

        result *= i;

    }

    return result;

}


int main() {

    int num = 5;

    int result = factorial(num);

    printf("Factorial of %d is %d\n", num, result);

    return 0;

}

```


Both approaches will yield the same result, which is the factorial of the given number. However, recursion involves function calls and can have higher memory consumption due to the recursive stack. Iteration, on the other hand, uses loop constructs and is generally more efficient in terms of memory usage. The choice between recursion and iteration depends on the problem and the programming language being used.


(b) Compare flowchart and algorithm. Draw flowchart to find factorial of a number entered by user.

Ans. 

Flowchart and algorithm are two tools used in programming to represent and solve problems.

 

A flowchart is a graphical representation of a process or algorithm. It uses various symbols and arrows to depict the flow of control and decision-making within a program. Flowcharts are helpful in visualizing the sequence of steps and logic involved in solving a problem. They are often used as a communication tool to illustrate the structure and flow of a program.

 

An algorithm, on the other hand, is a step-by-step procedure or set of rules to solve a specific problem or perform a task. It is a precise and unambiguous description of the solution to a problem. Algorithms are independent of programming languages and can be implemented in various programming languages. They provide a clear and logical approach to problem-solving.

 

Here's a flowchart to find the factorial of a number entered by the user:

 



In this flowchart, we start by taking input from the user. We then check if the entered number is zero. If it is zero, the factorial is set to 1. Otherwise, we multiply the factorial by the number and decrement the number by 1. The process continues until the number becomes zero. Finally, we display the calculated factorial.

 

Please note that the flowchart provided is a basic representation and may vary based on the specific requirements and conventions used in flowcharting.


(h) Compare overloading and overriding in Python. Give suitable example code for each.

Ans.

In Python, both overloading and overriding are object-oriented programming concepts that involve the use of methods, but they serve different purposes.


Overloading refers to defining multiple methods with the same name but different parameters within a single class. The specific method to be called is determined based on the number of arguments or the types of arguments passed during the method invocation. Overloading provides flexibility and allows the same method name to perform different operations based on the provided arguments.


Here's an example of method overloading in Python:


```python

class Calculator:

    def add(self, a, b):

        return a + b

    

    def add(self, a, b, c):

        return a + b + c


# Creating an instance of the Calculator class

calculator = Calculator()


print(calculator.add(2, 3))  # This will call the first add method and output 5

print(calculator.add(2, 3, 4))  # This will call the second add method and output 9

```


In the example above, the `Calculator` class defines two `add` methods with the same name but different parameters. Depending on the number of arguments provided, the appropriate method will be called. The first `add` method takes two arguments and returns their sum, while the second `add` method takes three arguments and returns their sum.


Overriding, on the other hand, occurs when a subclass provides a different implementation of a method that is already defined in its superclass. The method in the subclass must have the same name and the same number and type of parameters as the method in the superclass. Overriding allows the subclass to modify the behavior of the inherited method according to its specific needs.


Here's an example of method overriding in Python:


```python

class Animal:

    def make_sound(self):

        print("The animal makes a generic sound.")


class Dog(Animal):

    def make_sound(self):

        print("The dog barks.")


# Creating an instance of the Dog class

dog = Dog()


dog.make_sound()  # This will call the make_sound method in the Dog class and output "The dog barks."

```


In the example above, the `Animal` class defines a method called `make_sound`. The `Dog` class, which is a subclass of `Animal`, overrides the `make_sound` method with its own implementation. When we call the `make_sound` method on an instance of the `Dog` class, it will invoke the overridden method in the subclass, printing "The dog barks."


In summary, overloading allows a class to define multiple methods with the same name but different parameters, while overriding allows a subclass to provide a different implementation of a method that is already defined in its superclass.


2. (a) What are different data types in C ? Explain use of these data types with the help of a C program.

Ans.

In C, there are several data types available to store different kinds of values. The commonly used data types in C are:


1. int: It is used to store integer values, which are whole numbers without any fractional part. The `int` data type typically allocates 4 bytes of memory.


2. float: It is used to store floating-point numbers, which are numbers with a fractional part. The `float` data type typically allocates 4 bytes of memory and can store values with a precision of about 6 decimal places.


3. double: It is used to store double-precision floating-point numbers, which have a higher precision than `float`. The `double` data type typically allocates 8 bytes of memory and can store values with a precision of about 15 decimal places.


4. char: It is used to store individual characters, such as letters, digits, or special symbols. The `char` data type typically allocates 1 byte of memory.


5. short: It is used to store small integer values. The `short` data type typically allocates 2 bytes of memory.


6. long: It is used to store large integer values. The `long` data type typically allocates 4 bytes of memory and can store larger values than `int`.


7. unsigned: It is used to represent positive values of a data type, effectively doubling the range of positive values that can be stored.


Here's an example C program that demonstrates the use of these data types:


```c

#include <stdio.h>


int main() {

    int num1 = 10;

    float num2 = 3.14;

    double num3 = 2.71828;

    char ch = 'A';

    short num4 = 100;

    long num5 = 10000;

    unsigned int num6 = 20;


    printf("Integer: %d\n", num1);

    printf("Float: %f\n", num2);

    printf("Double: %lf\n", num3);

    printf("Character: %c\n", ch);

    printf("Short: %hd\n", num4);

    printf("Long: %ld\n", num5);

    printf("Unsigned Integer: %u\n", num6);


    return 0;

}

```


In this program, variables of different data types are declared and initialized with sample values. The `printf` function is then used to print the values of these variables, with appropriate format specifiers used to match the data types. The program demonstrates the usage of `int`, `float`, `double`, `char`, `short`, `long`, and `unsigned int` data types.


By understanding and utilizing the appropriate data types in C, you can efficiently store and manipulate different types of values in your programs.


(b) Write Python code to perform the following : 

(i) Reading data from a file 

(ii) Creating a file and add content to it Support your code with suitable comments.

Ans.

Here's Python code that demonstrates how to perform the following tasks:


(i) Reading data from a file:

```python

# Open the file in read mode

file = open("data.txt", "r")


# Read and print the contents of the file

content = file.read()

print(content)


# Close the file

file.close()

```


In this code, we open the file named "data.txt" in read mode using the `open` function. We then read the contents of the file using the `read` method and store it in the `content` variable. Finally, we print the contents and close the file using the `close` method.


(ii) Creating a file and adding content to it:

```python

# Open the file in write mode

file = open("new_file.txt", "w")


# Write content to the file

file.write("This is the first line.\n")

file.write("This is the second line.\n")

file.write("This is the third line.")


# Close the file

file.close()

```


3. (a) List various looping control statements. Write syntax of each statement. Also draw flowchart for each statement. 

 (b) What are Lambda functions ? How do Lambda functions differ from Built-in functions ? Write lambda function to calculate cube of a number. Also write the program to find cube of a number without using lambda function.

(c) How does syntax error differ from semantic error ? Give suitable example for each. 

(d) Explain the concept of call by reference, with suitable code in C. Give advantage and disadvantage of call by reference. 

(e) What is C-Python ? Briefly discuss the relation between framework, library, package and module in Python.

(f) Differentiate between mutable and immutable data types in Python. Briefly discuss the following data types of Python : 

(i) Lists 

(ii) Tuples 

(iii) Dictionaries 

(g) What does map( ) function do ? Write a program in Python to print the square of the numbers present in the list, by using map( ) function. 

Ans.

(a) Looping control statements in C:


1. for loop:

Syntax:

```

for (initialization; condition; increment/decrement) {

    // Code to be executed

}

```

Flowchart:

```

+---------+

| Start   |

+---------+

|         |

|         |

+----+----+

     |

     V

+----+---------+

| Initialization |

+----+---------+

     |

     V

+----+---------+

|   Condition    |

+----+---------+

     |

     V

+----+---------+

|     Code       |

|   Execution    |

+----+---------+

     |

     V

+----+---------+

|Increment/Decrement|

+----+---------+

     |

     V

+----+---------+

|   Condition    |

+----+---------+

     |

     V

+----+----+

|  End   |

+----+----+

```


2. while loop:

Syntax:

```

while (condition) {

    // Code to be executed

}

```

Flowchart:

```

+---------+

| Start   |

+---------+

|         |

|         |

+----+----+

     |

     V

+----+---------+

|   Condition    |

+----+---------+

     |

     V

+----+---------+

|     Code       |

|   Execution    |

+----+---------+

     |

     V

+----+----+

|  End   |

+----+----+

```


3. do-while loop:

Syntax:

```

do {

    // Code to be executed

} while (condition);

```

Flowchart:

```

+---------+

| Start   |

+---------+

|         |

|         |

+----+----+

     |

     V

+----+---------+

|     Code       |

|   Execution    |

+----+---------+

     |

     V

+----+---------+

|   Condition    |

+----+---------+

     |

     V

+----+----+

|  End   |

+----+----+

```


(b) Lambda functions, also known as anonymous functions, are small and anonymous functions that can be defined without a name. They are typically used when we need a simple, one-line function.


Lambda functions differ from built-in functions in that they do not have a name and are created using the `lambda` keyword. They are often used in combination with higher-order functions like `map`, `filter`, and `reduce`.


Example of a lambda function to calculate the cube of a number:

```python

cube = lambda x: x ** 3


result = cube(5)

print(result)  # Output: 125

```


Program to find the cube of a number without using a lambda function:

```python

def cube(x):

    return x ** 3


result = cube(5)

print(result)  # Output: 125

```


(c) Syntax error and semantic error are types of errors in programming.


Syntax error refers to errors in the syntax or structure of the code. It occurs when the code violates the rules of the programming language. These errors are typically detected by the compiler or interpreter during the compilation or execution process. Examples of syntax errors include missing or mismatched parentheses, incorrect variable names, or using incorrect syntax for control flow statements.


Example of a syntax error:

```python

print("Hello, world!"  # Missing closing parenthesis

```


Semantic error, on the other hand, refers to errors that occur when the code is logically incorrect and does not produce the desired output. These errors do not result in any error messages but lead to incorrect program behavior. Semantic errors are harder to detect as they do not violate the syntax rules. They


4. (a) Differentiate between Random access and Sequential access of files in C. Discuss the syntax and role of fseek( ) and rewind( ) function, while accessing any file. 10 (b) What are Cursor Objects ? Briefly discuss the utility of cursor objects. Write Python code for a cursor to execute the SQL query, to print the version of database. Support your program with suitable comments.


4. (a) Differentiate between Random access and Sequential access of files in C. Discuss the syntax and role of fseek( ) and rewind( ) function, while accessing any file. 

(b) What are Cursor Objects ? Briefly discuss the utility of cursor objects. Write Python code for a cursor to execute the SQL query, to print the version of database. Support your program with suitable comments.  

Ans.

(a) Random access and sequential access are two different methods of accessing files in C.


1. Random access: In random access, the file is accessed in a non-sequential manner, allowing direct access to any specific location within the file. Random access allows reading or writing data at any position in the file.


Syntax and role of `fseek()` function: The `fseek()` function is used to set the file position indicator for the specified file stream. It allows moving the position indicator to a specific location within the file.


Syntax:

```

int fseek(FILE *stream, long offset, int origin);

```

- `stream`: Pointer to a FILE object representing the file stream.

- `offset`: Number of bytes to offset from the origin.

- `origin`: Position from where the offset is applied. It can have one of the following values: `SEEK_SET` (beginning of the file), `SEEK_CUR` (current position of the file pointer), or `SEEK_END` (end of the file).


Role of `fseek()` function:

- `fseek()` is used to set the position within the file, allowing random access to read or write data.

- It moves the file pointer to the specified location based on the offset and origin provided.


Syntax and role of `rewind()` function: The `rewind()` function is used to reset the file position indicator to the beginning of the file. It is equivalent to calling `fseek()` with an offset of 0 from the beginning of the file.


Syntax:

```

void rewind(FILE *stream);

```


Role of `rewind()` function:

- `rewind()` is used to reset the file position indicator to the beginning of the file.

- It allows sequential access to the file from the start.


2. Sequential access: In sequential access, the file is accessed in a linear or sequential manner, starting from the beginning of the file and continuing until the end. It reads or writes data in the order it appears in the file.


(b) In Python, cursor objects are used to interact with databases using the Python Database API (DB-API). A cursor is an object that allows executing SQL queries and fetching the results from a database. It provides methods to execute queries, fetch rows, and perform other database operations.


The utility of cursor objects:

- Cursors enable executing SQL queries and retrieving the results from the database.

- They provide methods to fetch rows from the result set, such as `fetchone()` (fetches the next row), `fetchall()` (fetches all rows), or `fetchmany(n)` (fetches the next n rows).

- Cursors also allow executing other database operations like inserting, updating, or deleting data.


Example Python code to print the version of a database using a cursor:

```python

import sqlite3


# Connect to the database

connection = sqlite3.connect("mydb.db")


# Create a cursor object

cursor = connection.cursor()


# Execute the SQL query

cursor.execute("SELECT sqlite_version();")


# Fetch the result

result = cursor.fetchone()


# Print the version

print("Database version:", result[0])


# Close the cursor and the connection

cursor.close()

connection.close()

```


In this code, we import the `sqlite3` module to work with a SQLite database. We establish a connection to the database using `sqlite3.connect()`. Then, we create a cursor object using the `cursor()` method of the connection. We execute an SQL query using the `execute()` method of the cursor. The `fetchone()` method is used to fetch the result, and we print the version obtained. Finally, we close the cursor and the connection to release the resources.


Note: The code assumes the existence of a SQLite database file named


No comments:

Post a Comment