0% found this document useful (0 votes)
30 views21 pages

Sol. Dec 2023

The document outlines various programming tasks related to the Bachelor of Computer Applications curriculum, including algorithms, C programming exercises, and explanations of concepts like pointers and operators. It provides specific examples, such as checking for prime numbers, summing digits of a number, and using structures for salary calculations. Additionally, it discusses types of errors in C programming and the characteristics of different variable types.
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)
30 views21 pages

Sol. Dec 2023

The document outlines various programming tasks related to the Bachelor of Computer Applications curriculum, including algorithms, C programming exercises, and explanations of concepts like pointers and operators. It provides specific examples, such as checking for prime numbers, summing digits of a number, and using structures for salary calculations. Additionally, it discusses types of errors in C programming and the characteristics of different variable types.
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/ 21

BACHELOR OF COMPUTER APPLICATIONS

DECEMEB 2023

MCS-011

1. (a) Write an algorithm and draw a

corresponding flow chart to check whether

the number is prime or not. (10m)

Ans:- Algorithm to Check if a Number is Prime:

1. Start

2. Input: Read the number `n`.

3. If n <= 1 :

- Output: `n` is not a prime number.

- Go to step 9.

4. If n == 2 :

- Output: `n` is a prime number.

- Go to step 9.

5. For i from 2 to √n (inclusive):

- If n % i == 0 :

- Output: `n` is not a prime number.

- Go to step 9.

6. End For loop.

7. Output : n is a prime number.

8. End

9. Stop
(b) Write a program in C to find the sum of

digits of a 5-digit number. (6m)

Ans :- #include <stdio.h>

int main() {

int number, sum = 0;

// Prompt the user to enter a 5-digit number

printf("Enter a 5-digit number: ");

scanf("%d", &number);

// Ensure the number is positive

if (number < 0) {

number = -number; }

// Extract each digit and add it to the sum

sum += number % 10; // Get the last digit

number /= 10; // Remove the last digit

sum += number % 10;

number /= 10;
sum += number % 10;

number /= 10;

sum += number % 10;

number /= 10;

sum += number % 10;

// Print the result

printf("Sum of the digits: %d\n", sum);

return 0; }

(c) Write a C program to generate the

following pattern : (8m)

22

333

4444

55555

Ans :- #include <stdio.h>

int main() {

int i, j;

// Loop for rows

for(i = 1; i <= 5; i++) {

// Loop for columns

for(j = 1; j <= i; j++) {


printf("%d ", i); }

// Move to the next line

printf("\n"); }

return 0;

(d) Write a C function to find the square of an

integer. (5m)

Note : Do not use inbuilt functions.

Ans :- #include <stdio.h>

// Function to find the square of an integer

int square(int num) {

return num * num; }

int main() {

int number = 5;

int result = square(number);

printf("The square of %d is %d\n", number, result);

return 0; }

(e) Explain the use of pointers and its

characteristics. (5m)

Ans :- Pointers are a fundamental feature in many programming languages, particularly in C, C++, and related
languages. They are variables that store memory addresses, typically the address of another variable.
Understanding pointers is crucial for managing memory directly, optimizing performance, and working with
dynamic data structures.

Uses of Pointers
1. Dynamic Memory Allocation : Pointers allow programs to allocate memory at runtime using functions like
`malloc` in C. This is essential for creating data structures like linked lists, trees, and graphs that need to
dynamically resize.

2. Array and String Manipulation : Pointers can be used to iterate through arrays and strings efficiently. Instead
of using index-based access, you can move a pointer through the array to access elements directly.

3. Function Arguments : Passing large structures or arrays to functions by value can be inefficient. Instead, you
can pass a pointer to the structure or array, which is much faster since only the address is copied, not the entire
data.

4. Pointer Arithmetic : Pointers support arithmetic operations like addition and subtraction, which allow
traversing arrays or buffers by manipulating the pointer directly.

5. Creating Complex Data Structures : Pointers are essential for creating complex data structures like linked lists,
trees, graphs, and hash tables. These structures rely on pointers to connect different elements dynamically.

Characteristics of Pointers

1. Data Type Specific : Pointers are associated with a specific data type (e.g., `int*`, `char*`). This means a pointer
knows what type of data it points to, which affects how much memory it accesses when dereferencing.

2. Dereferencing : The process of accessing the value at the address a pointer is holding is called dereferencing.
This is done using the `*` operator (e.g., `*ptr`).

3. NULL Pointer : A pointer can be assigned a special value `NULL` to indicate that it does not point to any valid
memory location. This is useful for error checking and initializing pointers.

4. Pointer Arithmetic : Pointers can be incremented or decremented to traverse arrays or buffer memory.
However, the arithmetic is scaled according to the size of the data type the pointer points to. For example,
incrementing an `int*` pointer by 1 actually increases the memory address by `sizeof(int)` bytes.

5. Pointer to Pointer : Pointers can point to other pointers, leading to multiple levels of indirection (e.g., `int**
ptr`). This is particularly useful in dynamic memory allocation for multi-dimensional arrays and in implementing
complex data structures.

(f) Describe the conditional statements

“Multiple-if” and “nested-if” with one

example for each. (6m)

Ans :-

1. Multiple-if Statements:
A "multiple-if" statement involves a series of `if` statements where each condition is evaluated independently.
This means each `if` statement is separate and not dependent on the others. All the conditions are checked, and
if any condition is true, the corresponding block of code will be executed.

Example: temperature = 30

humidity = 80

wind_speed = 20

if temperature > 25:

print("It's a hot day.")

if humidity > 70:

print("It's quite humid.")

if wind_speed > 15:

print("It's windy outside.")

In this example, all three conditions are evaluated independently.

The output could be:

It's a hot day.

It's quite humid.

It's windy outside.

2. Nested-if Statements:

A "nested-if" statement is an `if` statement inside another `if` statement. Here, the second `if` statement is only
evaluated if the first `if` condition is true. This creates a dependency between the conditions.

Example: temperature = 30

humidity = 80

if temperature > 25:

printf("It's a hot day.")

if humidity > 70:

printf("It's also very humid.")

In this example, the second `if` statement checking the humidity will only be evaluated if the first condition
about the temperature is true.

The output could be:

It's a hot day.

It's also very humid.

2. (a) Explain the type of errors in C program by

giving an example for each. (6m)

Ans :- In C programming, errors can be broadly categorized into three types: syntax errors, runtime errors, and
logical errors. Each type of error affects the program differently, and understanding them is crucial for
debugging. Here’s an explanation with examples for each:

1. Syntax Errors : Syntax errors occur when the code violates the grammar rules of the C programming language.
These errors are detected by the compiler during the compilation process.

Example:

#include <stdio.h>

int main() {

int num = 10

printf("The number is %d\n", num);

return 0; }

Explanation: The semicolon `;` is missing after `int num = 10`. This will cause a syntax error because the compiler
expects a semicolon to terminate the statement.

2. Runtime Errors : Runtime errors occur while the program is running. These errors often happen due to illegal
operations such as dividing by zero or accessing invalid memory locations.

Example :

#include <stdio.h>

int main() {

int a = 10;

int b = 0;
int result = a / b; // Division by zero

printf("Result: %d\n", result);

return 0; }

Explanation : This program will compile successfully, but when you run it, a runtime error will occur because
dividing a number by zero is undefined and causes the program to crash or produce unexpected behavior.

3. Logical Errors : Logical errors occur when the program compiles and runs, but the output is not as expected.
These errors are due to mistakes in the algorithm or incorrect use of logic in the code.

Example:

#include <stdio.h>

int main() {

int num = 5;

int square = num * num; // Intended to calculate the square, but let's say we mistakenly wrote:

// int square = num + num;

printf("The square of %d is %d\n", num, square);

return 0; }

Explanation: If you mistakenly write `int square = num + num;` instead of `int square = num * num;`, the program
will run without errors, but the output will be incorrect. For `num = 5`, it should print "The square of 5 is 25", but
instead, it will print "The square of 5 is 10".

(b) Write an interactive C program to

calculate the salary of an employee based

on Basic-pay, TA, DA, Grade pay and other

allowances. Use structures. (8m)

Ans :- #include <stdio.h>

// Structure to hold the salary components

struct SalaryComponents {
float basicPay;

float ta; // Travel Allowance

float da; // Dearness Allowance

float gradePay;

float otherAllowances;

};

// Function to calculate the total salary

float calculateTotalSalary(struct SalaryComponents sc) {

return sc.basicPay + sc.ta + sc.da + sc.gradePay + sc.otherAllowances;

int main() {

struct SalaryComponents empSalary;

float totalSalary;

// Input the salary components from the user

printf("Enter Basic Pay: ");

scanf("%f", &empSalary.basicPay);

printf("Enter Travel Allowance (TA): ");

scanf("%f", &empSalary.ta);

printf("Enter Dearness Allowance (DA): ");

scanf("%f", &empSalary.da);

printf("Enter Grade Pay: ");


scanf("%f", &empSalary.gradePay);

printf("Enter Other Allowances: ");

scanf("%f", &empSalary.otherAllowances);

// Calculate the total salary

totalSalary = calculateTotalSalary(empSalary);

// Display the total salary

printf("\nTotal Salary of the Employee: %.2f\n", totalSalary);

return 0; }

(c) What is an operator ? List and explain

various categories of operators in C. (6m)

Ans :- An **operator** in C is a symbol that tells the compiler to perform specific mathematical, relational, or
logical operations on variables and values. Operators are essential in writing expressions and control flow in a C
program. Here's a breakdown of the various categories of operators in C:

1. Arithmetic Operators : These operators are used to perform mathematical calculations like addition,
subtraction, multiplication, etc.

- `+` (Addition): Adds two operands. a + b

- - (Subtraction): Subtracts the second operand from the first. a - b

- `*` (Multiplication): Multiplies two operands. a * b

- `/` (Division): Divides the numerator by the denominator. a / b

- `%` (Modulus): Returns the remainder after division. a % b

- `++` (Increment): Increases an integer's value by one. `++a` or `a++`

- `--` (Decrement): Decreases an integer's value by one. `--a` or `a--`


2. Relational Operators : These operators are used to compare two values. They return a Boolean result (true or
false).

- `==` (Equal to): Checks if two operands are equal. `a == b`

- `!=` (Not equal to): Checks if two operands are not equal. `a != b`

- `>` (Greater than): Checks if the first operand is greater than the second. `a > b`

- `<` (Less than): Checks if the first operand is less than the second. `a < b`

- `>=` (Greater than or equal to): Checks if the first operand is greater than or equal to the second. `a >= b`

- `<=` (Less than or equal to): Checks if the first operand is less than or equal to the second. `a <= b`

3. Logical Operators : These operators are used to perform logical operations and return true or false.

- `&&` (Logical AND): Returns true if both operands are true. `a && b`

- `||` (Logical OR): Returns true if at least one operand is true. `a || b`

- `!` (Logical NOT): Reverses the logical state of its operand. `!a`

4. Bitwise Operators : These operators perform operations on bits and are used for manipulation at the bit
level.

- `&` (Bitwise AND): Performs AND operation on each bit. `a & b`

- `|` (Bitwise OR): Performs OR operation on each bit. `a | b`

- `^` (Bitwise XOR): Performs XOR operation on each bit. `a ^ b`

- `~` (Bitwise NOT): Inverts all the bits of the operand. `~a`

- `<<` (Left Shift): Shifts bits of the first operand left by the number of positions specified by the second
operand. `a << 1`

- `>>` (Right Shift): Shifts bits of the first operand right by the number of positions specified by the second
operand. `a >> 1`

5. Assignment Operators : These operators are used to assign values to variables.

- `=` (Assignment): Assigns the value of the right operand to the left operand. `a = b`

- `+=` (Add and Assign): Adds the right operand to the left operand and assigns the result to the left operand. `a
+= b` (equivalent to `a = a + b`)
- `-=` (Subtract and Assign):Subtracts the right operand from the left operand and assigns the result to the left
operand. `a -= b` (equivalent to `a = a - b`)

- `*=` (Multiply and Assign): Multiplies the right operand with the left operand and assigns the result to the left
operand. `a *= b` (equivalent to `a = a * b`)

- `/=` (Divide and Assign): Divides the left operand by the right operand and assigns the result to the left
operand. `a /= b` (equivalent to `a = a / b`)

- `%=` (Modulus and Assign): Takes modulus using two operands and assigns the result to the left operand. `a
%= b` (equivalent to `a = a % b`)

6. Conditional (Ternary) Operator : This is a shorthand way of writing an if-else statement.

- `? :` (Conditional): Returns one of two values depending on the condition. `condition ? expression1 :
expression2`

7. Comma Operator : This operator allows multiple expressions to be evaluated in a single statement, with the
result of the entire expression being the value of the last expression.

- `,` (Comma): Separates multiple expressions. `a = (b = 3, b + 2)`

8. Sizeof Operator : This operator returns the size (in bytes) of a variable or data type.

- `sizeof`: Returns the size of a variable/data type. `sizeof(int)`

9. Pointer Operators : These operators are used in conjunction with pointers.

- `` (Dereference): Used to access the value at the memory address stored in a pointer. `*ptr`

- `&` (Address of): Returns the memory address of a variable. `&a`

10. Special Operators

- `->` (Member Access via Pointer): Used to access members of a structure through a pointer. `ptr->member`

- `.` (Member Access): Used to access members of a structure or union. `struct.member`

- `[]` (Array Subscript): Used to access elements of an array. `arr[i]`

- `()` (Function Call): Used to call a function. `func()`


3. (a) Explain the following variables with an

example for each : 10m

(i) Automatic Variables : Automatic variables are local variables that are automatically allocated and
deallocated when a function is called and exited. They are typically stored on the stack.

Example :

#include <stdio.h>

void function() {

int x = 10; // x is an automatic variable

printf("%d\n", x); }

int main() {

function(); // Output: 10

return 0; }

(ii) Extern Variables : Extern variables are declared outside of any function and can be accessed from any
function within the same file or across multiple files. They are used to share variables between files.

Example:

#include <stdio.h>

extern int globalVar; // Declaration of extern variable

void function() {

printf("%d\n", globalVar);

// Accessing extern variable }

int globalVar = 20;

// Definition of extern variable


int main() {

function(); // Output: 20

return 0; }

(iii) Static Variables : Static variables maintain their value between function calls. They are initialized only once
and have a lifetime that lasts for the duration of the program.

Example :

#include <stdio.h>

void function() {

static int count = 0; // Static variable

count++;

printf("%d\n", count); }

int main() {

function(); // Output: 1

function(); // Output: 2

function(); // Output: 3

return 0; }

(iv) Register Variables : Register variables are stored in the CPU registers instead of RAM, which makes access to
them faster. They are typically used for variables that require quick access and are declared with the `register`
keyword.

Example :

#include <stdio.h>

void function() {

register int i; // Register variable

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

printf("%d\n", i); }

// Fast access to i
}

int main() {

function(); // Output: 0 1 2 3 4

return 0; }

(b) Write a program in C to award grade to the

students depending on the marks : 10

If mark > 75 then grade – „A‟

60–75 then grade „B‟

50–60 then grade „C‟

40–50 then grade „D‟

< 40 then grade „E‟

Ans :- #include <stdio.h>

int main() {

int marks;

char grade;

// Input marks from user

printf("Enter the marks obtained (0-100): ");

scanf("%d", &marks);

// Determine grade based on marks

if (marks > 75) {

grade = 'A';

} else if (marks >= 60) {

grade = 'B';

} else if (marks >= 50) {


grade = 'C';

} else if (marks >= 40) {

grade = 'D';

} else {

grade = 'E';

// Output the grade

printf("The grade is: %c\n", grade);

return 0; }

4. (a) Check a string for palindrome using library functions. (5m)

Ans :- def is_palindrome(s):

# Normalize the string: remove spaces and convert to lowercase

normalized_str = ''.join(s.split()).lower()

# Check if the string is equal to its reverse

return normalized_str == normalized_str[::-1]

# Example usage

string = "A man a plan a canal Panama"

if is_palindrome(string):

print(f'"{string}" is a palindrome.')

else:

print(f'"{string}" is not a palindrome.')

(b) Describe file handling in C. Explain

various functions like fopen (), fclose () and


fseek (). (10m)

Ans :- File handling in C is a crucial aspect of programming that allows you to read from and write to files on disk.
It enables programs to persist data and interact with the file system. The C Standard Library provides a set of
functions to handle files.

Key Functions for File Handling

1. fopen() :

• Purpose : Opens a file and returns a file pointer.

• Syntax : FILE *fopen(const char *filename, const char *mode);

• Parameters :

-filename: Name of the file to be opened.

-mode : Mode in which to open the file (e.g., "r" for read, "w" for write, "a" for append, etc.).

• Returns : A pointer to a `FILE` object that can be used to identify the file. Returns `NULL` if the file cannot be
opened.

Example :

FILE *file = fopen("example.txt", "r");

if (file == NULL) {

printf("Error opening file.\n"); }

2. fclose() :

• Purpose : Closes an opened file.

• Syntax : int fclose(FILE *stream);

• Parameters :

- stream: The file pointer to be closed.

- Returns : 0 if successful, or EOF if an error occurs.

Example :
if (fclose(file) != 0) {

printf("Error closing file.\n"); }

3. fseek() :

• Purpose : Sets the file position of the stream to a given offset.

• Syntax : int fseek(FILE *stream, long offset, int whence);

• Parameters :

-stream: The file pointer to the file.

-offset : The number of bytes to offset from whence.

•whence :The position from which the offset is applied. It can be:

- SEEK_SET: Beginning of the file.

- SEEK_CUR: Current position in the file.

- SEEK_END : End of the file.

• Returns : 0 if successful, or -1 if an error occurs.

Example:

fseek(file, 0, SEEK_END); // Move to the end of the file

long size = ftell(file); // Get the size of the file

(c) Define an array. How are arrays declared

and initialised ? Write a C code segment to

explain it. (5m)

Ans :- An array is a collection of elements, all of the same type, stored in contiguous memory locations. It allows
for efficient storage and access to multiple items using a single identifier. In C, arrays can be declared and
initialized in various ways.

1. Declaration : An array is declared by specifying the type of its elements and the number of elements it can
hold.
The syntax is:

type arrayName[size];

2. Initialization : Arrays can be initialized at the time of declaration using curly braces.

The synatx is:

type arrayName[size] = {value1, value2, ..., valueN};

Example Code Segment

#include <stdio.h>

int main() {

// Declaration of an array of integers

int numbers[5]; // Array declaration

// Initialization of the array

numbers[0] = 10;

numbers[1] = 20;

numbers[2] = 30;

numbers[3] = 40;

numbers[4] = 50;

// Alternatively, declare and initialize in one line

int moreNumbers[5] = {1, 2, 3, 4, 5};

// Printing the values of the array

printf("First array values:\n");

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

printf("%d ", numbers[i]); }


printf("\nSecond array values:\n");

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

printf("%d ", moreNumbers[i]); }

return 0; }

5. Differentiate the following : 5×4=20

(i) Function vs. Macro

• Function :

- A function is a block of code that performs a specific task and can take parameters and return a value.

- Functions are type-checked, and errors are caught at compile time or runtime.

• Macro :

- A macro is a preprocessor directive that defines a sequence of code to be expanded inline during
preprocessing before compilation.

- Macros do not perform type-checking and can lead to errors if not used carefully.

(ii) Structure vs. Union

• Structure :

- A structure is a user-defined data type that allows grouping of variables of different types under a single
name.

- Each member in a structure has its own memory location, and the total size is the sum of the sizes of its
members.

•Union :

- A union is also a user-defined data type, but it allows storing different data types in the same memory
location.

- All members share the same memory space, meaning only one member can hold a value at any given time.
The total size is determined by the largest member.

(iii) Call by Value vs. Call by Reference


• 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 original argument.

• Call by Reference : In call by reference, a reference (or address) of the actual parameter is passed to the
function. Changes made to the parameter inside the function affect the original argument.

(iv) Break Statement vs. Continue Statement

• Break Statement : The break statement is used to exit from a loop or switch statement prematurely. It
terminates the nearest enclosing loop or switch.

• Continue Statement : The continue statement is used to skip the current iteration of a loop and proceed to the
next iteration. It does not terminate the loop but instead continues with the next cycle.

You might also like