Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PYQ with Solution-2

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

PYQ with Solution

PPS (ESC-103)
End Semester Paper April 2022

Part-A (1.5 mark each)


1. Define linked list.
2. What is purpose of break statement?
3. What is “\0”?
4. Which is better: switch case or nested if else?
5. Mention the advantages of algorithm?
6. Describe working of linear search in brief?
7. Can we have two return statements in a function?
8. What are syntax errors?
9. What are logical and relational operators?
10. Differentiate between RAM and ROM?

Part-B

1. (a) Explain the types of iterative loops in detail. (10 mark)


(b) WAP to calculate the area and circumference of a circle using call by reference. (5
mark)

2. (a) What is Operating system? Discuss its various functions. (5 mark)


(b) WAP to print the upper and lower triangular of the matrix along with the sum of their
elements. (10 mark)

3. What is Recursion? How it is different from iteration? WAP to print the Fibonacci series
up to n terms using recursion. (15 mark)

4. (a) WAP to copy the elements of one file to another. (5 mark)


(b) Explain each step for sorting the given array using selection sort. (10 mark)
(5, 10, 15, 20, 18, 12, 8, 1, 30)

5. (a) Differentiate between array and structure. Explain array of structure with the help of a
program. (10 mark)
(b) WAP to count the number of vowels in a string without using inbuilt functions. (5
mark)

6. Define flowchart. Draw a flowchart to compute factorial for a given number N, where N
is a non-negative integer. Write an algorithm for the same problem. (15 mark)

Solutions
Solutions for Part-A
1. Define linked list
A linked list is a data structure that consists of a sequence of elements, where each
element, called a node, contains data and a reference (or a link) to the next node in the
sequence. Unlike arrays, linked lists do not store elements in contiguous memory
locations. This structure allows for efficient insertions and deletions since they don't
require shifting elements, unlike arrays. Linked lists are mainly used when the size of the
data structure needs to vary dynamically or when memory utilization is crucial. There are
several types of linked lists, such as singly linked lists (where each node points to the next
node only), doubly linked lists (where nodes have links to both the previous and next
nodes), and circular linked lists (where the last node points back to the first node).

2. What is the purpose of break statement?


The break statement is used in programming to exit from a loop or switch case
prematurely, before the loop condition fails or all cases are evaluated. In loops like for,
while, or do-while, a break statement causes an immediate termination of the loop’s
execution, transferring control to the statement following the loop. In a switch statement,
break helps exit a case, preventing fall-through to subsequent cases. This makes break
essential for controlling the flow of the program.

3. What is “\0”?
The \0 character, also known as the null character, is used in C and C++ to mark the end
of a string. It has an ASCII value of zero and is essential in languages that use null-
terminated strings. The null character lets functions like strlen, strcpy, and others
recognize where a string terminates, thus preventing memory from being accessed beyond
the intended string boundaries. Without \0, the program may continue reading adjacent
memory, leading to errors.

4. Which is better: switch case or nested if-else?


The choice between switch and nested if-else depends on readability, efficiency, and
the number of conditions. Switch statements are often preferred when there are many
conditions based on the value of a single variable, as they offer clearer syntax and can
sometimes be more efficient than a series of if-else checks. However, if-else
statements provide more flexibility for complex conditions that cannot be easily evaluated
by a switch, such as range-based comparisons.

5. Mention the advantages of algorithm.


An algorithm is a step-by-step procedure for solving a problem. The advantages of using
algorithms include clarity, as they provide a clear path to problem-solving; efficiency, as
well-optimized algorithms save time and resources; and reusability, since a single
algorithm can be adapted for different implementations. Algorithms also aid in analyzing
a program's performance and make it easier to spot potential issues.

6. Describe the working of linear search in brief.


Linear search is a simple searching algorithm used to find a particular element in a list or
array. It works by sequentially checking each element of the array until the desired
element is found or the end of the list is reached. Linear search has a time complexity of
O(n) and is inefficient for large data sets but effective for smaller, unsorted lists due to its
straightforward implementation.
7. Can we have two return statements in a function?
Yes, a function can contain multiple return statements, but only one will be executed
during a single call of the function. Different return statements are often used in
conditional branches to exit the function under various conditions. This can make code
clearer by providing a quick exit from a function once the required result is achieved.

8. What are syntax errors?


Syntax errors are mistakes in the code that violate the language’s rules, preventing the
program from compiling successfully. These errors occur when the programmer does not
follow the proper syntax required by the programming language, such as missing
semicolons, unmatched parentheses, or incorrect keyword usage. Syntax errors are
usually detected by the compiler or interpreter.

9. What are logical and relational operators?


Logical operators, such as && (and), || (or), and ! (not), are used to combine or invert
Boolean expressions. Relational operators, such as == (equal to), != (not equal), > (greater
than), and < (less than), are used to compare values. Together, these operators help
control the flow of programs by enabling decision-making based on conditions.

10. Differentiate between RAM and ROM.


RAM (Random Access Memory) is volatile memory used for temporary data storage
while a program is running. Its contents are lost when the power is off. ROM (Read-Only
Memory), on the other hand, is non-volatile memory that stores critical information
required for the computer’s initial startup, such as the BIOS. ROM retains its contents
even after power is turned off, making it ideal for permanent data storage.

Solutions for Part-B

Question 1

(a) Explain the types of iterative loops in detail. (10 marks)

In C, loops allow for repetitive execution of a block of code. There are three primary types of
loops: for, while, and do-while.

1. For Loop: Used when the number of iterations is known. It has three parts within the
loop: initialization, condition, and increment/decrement. Syntax:

for(initialization; condition; increment/decrement) {


// Statements to be executed
}

Example:

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


printf("%d ", i);
}

2. While Loop: Checks the condition before executing the loop. It’s useful when the
number of iterations isn’t predetermined. Syntax:

while(condition) {
// Statements to execute
}

Example:

int i = 0;
while(i < 5) {
printf("%d ", i);
i++;
}

3. Do-While Loop: Executes the loop body first and checks the condition afterward,
ensuring the loop runs at least once. Syntax:

do {
// Statements to execute
} while(condition);

Example:

int i = 0;
do {
printf("%d ", i);
i++;
} while(i < 5);

(b) Write a program to calculate the area and circumference of a circle using call by
reference. (5 marks)

Here’s a C program that calculates the area and circumference of a circle by passing values
using pointers.

#include <stdio.h>
#define PI 3.14159

void calculateCircle(float radius, float *area, float *circumference) {


*area = PI * radius * radius;
*circumference = 2 * PI * radius;
}

int main() {
float radius, area, circumference;
printf("Enter radius of circle: ");
scanf("%f", &radius);
calculateCircle(radius, &area, &circumference);
printf("Area: %.2f\nCircumference: %.2f\n", area, circumference);
return 0;
}
Question 2

(a) What is an Operating System? Discuss its various functions. (5 marks)

An Operating System (OS) is system software that manages hardware and software resources
and provides services for computer programs. Functions include:

1. Process Management: Manages the execution of processes, handles creation and


termination, and ensures efficient CPU utilization.
2. Memory Management: Allocates and deallocates memory spaces as needed by
processes.
3. File Management: Manages files and directories, allowing operations like creation,
deletion, and access.
4. Device Management: Coordinates and manages input/output devices through device
drivers.
5. Security and Access Control: Protects data and resources from unauthorized access.
6. User Interface: Provides interfaces like CLI or GUI for users to interact with the
system.

(b) Write a program to print the upper and lower triangular matrix along with the sum
of their elements. (10 marks)

#include <stdio.h>

void printUpperLower(int matrix[3][3], int size) {


int upperSum = 0, lowerSum = 0;
printf("Upper Triangular Matrix:\n");
for(int i = 0; i < size; i++) {
for(int j = 0; j < size; j++) {
if(i <= j) {
printf("%d ", matrix[i][j]);
upperSum += matrix[i][j];
} else {
printf("0 ");
}
}
printf("\n");
}

printf("\nLower Triangular Matrix:\n");


for(int i = 0; i < size; i++) {
for(int j = 0; j < size; j++) {
if(i >= j) {
printf("%d ", matrix[i][j]);
lowerSum += matrix[i][j];
} else {
printf("0 ");
}
}
printf("\n");
}

printf("\nSum of Upper Triangular Elements: %d\n", upperSum);


printf("Sum of Lower Triangular Elements: %d\n", lowerSum);
}
int main() {
int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
printUpperLower(matrix, 3);
return 0;
}

Question 3

What is Recursion? How is it different from iteration? Write a program to print the
Fibonacci series up to n terms using recursion. (15 marks)

Recursion is a programming technique where a function calls itself to solve a problem in


smaller subproblems. Unlike iteration, which uses loops, recursion divides problems into
simpler ones and typically includes a base case to stop the recursive calls.

Difference between Recursion and Iteration:

 Recursion uses repeated function calls, while iteration uses loops.


 Recursive solutions can be more readable but may use more memory due to function
stack frames.
 Iteration is generally more efficient in terms of memory.

Program for Fibonacci series using recursion:

#include <stdio.h>

int fibonacci(int n) {
if(n <= 1)
return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}

int main() {
int n;
printf("Enter the number of terms: ");
scanf("%d", &n);

printf("Fibonacci series: ");


for(int i = 0; i < n; i++) {
printf("%d ", fibonacci(i));
}
return 0;
}

Question 4

(a) Write a program to copy the elements of one file to another. (5 marks)

#include <stdio.h>

void copyFile(const char *sourceFile, const char *destinationFile) {


FILE *source = fopen(sourceFile, "r");
FILE *dest = fopen(destinationFile, "w");
char ch;
if(source && dest) {
while((ch = fgetc(source)) != EOF) {
fputc(ch, dest);
}
printf("File copied successfully.\n");
} else {
printf("Error opening file.\n");
}

fclose(source);
fclose(dest);
}

int main() {
copyFile("source.txt", "destination.txt");
return 0;
}

(b) Explain each step for sorting the given array using selection sort. (10 marks)

Selection sort works by repeatedly finding the minimum element from the unsorted portion
and moving it to the sorted portion. For example, given [5, 10, 15, 20, 18, 12, 8, 1,
30]:

1. Find the minimum in the array [1] and swap with the first element.
2. Continue to find the minimum in the unsorted portion and move to the sorted portion.
3. Repeat until the array is fully sorted.

Question 5

(a) Differentiate between array and structure. Explain array of structures with a
program. (10 marks)

Here's a tabular comparison between arrays and structures in C:

Feature Array Structure


Collection of elements of the same Collection of elements of different data
Definition
data type. types.
struct StructName { dataType1
Syntax dataType arrayName[size];
var1; dataType2 var2; };
Homogeneous (all elements are of Heterogeneous (elements can be of
Data Type
the same type). different types).
Memory Allocates contiguous memory for all Allocates memory as needed for each
Allocation elements. member.
Accessed using index (e.g., Accessed using the dot operator (e.g.,
Access Method
array[index]). structVar.member).
Fixed for all elements based on data Varies based on the size of each
Storage Size
type size. member.
Typically used for lists of similar Used to group related data of different
Usage
items, like integers or floats. types, like a student record.
Feature Array Structure
Initialized with a set of values (e.g., Initialized using individual assignments
Initialization
{1, 2, 3}). or an initializer list.
Memory Efficient for large collections of Useful when organizing mixed data
Efficiency similar data. types together.
struct Student { int id; char
Example int arr[5] = {1, 2, 3, 4, 5};
name[20]; float grade; };

An array is a collection of elements of the same type, accessed by indexing. A structure,


however, is a collection of variables of different data types grouped under one name.

Array of Structures Program:

#include <stdio.h>
#include <string.h>

struct Student {
int id;
char name[20];
float grade;
};

int main() {
struct Student students[3];
students[0].id = 1;
strcpy(students[0].name, "Alice");
students[0].grade = 85.5;

printf("Student ID: %d\nName: %s\nGrade: %.2f\n", students[0].id,


students[0].name, students[0].grade);
return 0;
}

(b) Write a program to count the number of vowels in a string without using inbuilt
functions. (5 marks)

#include <stdio.h>

int countVowels(char *str) {


int count = 0;
for(int i = 0; str[i] != '\0'; i++) {
char ch = str[i];
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
count++;
}
}
return count;
}

int main() {
char str[100];
printf("Enter a string: ");
gets(str);
printf("Number of vowels: %d\n", countVowels(str));
return 0;
}

Question 6

Define flowchart. Draw a flowchart to compute factorial for a given number N, where N
is a non-negative integer. Write an algorithm for the same problem. (15 marks)

A flowchart is a visual representation of the sequence of steps required to solve a problem or


complete a process. It uses symbols to depict different actions, decisions, inputs, and outputs,
providing a clear and concise view of the flow of control in a program or algorithm.
Flowcharts are particularly helpful in planning, troubleshooting, and understanding
algorithms or processes, as they make it easier to visualize the logic and flow of tasks.

Here are some common symbols used in flowcharts:

1. Oval (Terminator): Represents the start and end points of a flowchart.


2. Rectangle (Process): Represents a process or action step, such as a calculation or
assignment.
3. Parallelogram (Input/Output): Represents input and output operations.
4. Diamond (Decision): Represents a decision point that branches based on a condition.
5. Arrow: Shows the direction of flow from one step to the next.

Flowchart to Compute Factorial for a Given Number N

1. Start: Begin the flowchart.


2. Input N: Get the input NNN from the user.
3. Initialize Factorial: Set a variable fact to 1, which will hold the factorial value.
4. Loop (N times): Multiply fact by each integer from 1 up to NNN.
5. Output Result: Display the computed factorial of NNN.
6. End: Finish the process.

Below is the flowchart to compute the factorial of a given non-negative integer NNN:

+-----------------+
| Start |
+-----------------+
|
v
+-----------------+
| Input N |
+-----------------+
|
v
+-----------------+
| fact <- 1 |
+-----------------+
|
v
+----------------------------+
| i <- 1 |
| While (i <= N) do |
| fact <- fact * i |
| i <- i + 1 |
+----------------------------+
|
v
+-----------------+
| Output fact |
+-----------------+
|
v
+-----------------+
| End |
+-----------------+

Algorithm for Factorial Calculation

1. Start the process.


2. Input the integer NNN (assuming N≥0N \geq 0N≥0).
3. Initialize a variable fact to 1 (this will store the factorial value).
4. Loop from 1 to NNN:
o Multiply fact by the current loop counter i.
o Increment i by 1.
5. Output the value of fact, which is the factorial of NNN.
6. End the algorithm.

Example Code in C for Factorial Calculation

Here is a C program to calculate the factorial of a number using a similar approach:

#include <stdio.h>

int main() {
int N, fact = 1;

// Step 1: Input the integer N


printf("Enter a non-negative integer: ");
scanf("%d", &N);

// Check if input is valid


if (N < 0) {
printf("Factorial is not defined for negative numbers.\n");
return 1;
}

// Step 2: Calculate factorial


for (int i = 1; i <= N; i++) {
fact *= i;
}

// Step 3: Output the factorial


printf("Factorial of %d is %d\n", N, fact);
return 0;
}
Explanation of the Code

 Input: The user inputs a non-negative integer NNN.


 Loop: A for loop iterates from 1 to NNN, multiplying the current value of fact by the loop
counter i.
 Output: Once the loop completes, the program outputs the factorial of NNN.

This flowchart and algorithm are ideal for calculating factorials in iterative programs,
providing clear visual and step-by-step guides for understanding factorial computation.

You might also like