MCS-011, Question & Answer , December 2022
1 (a) Write an algorithm to find highest and lowest marks obtained by students of batch size 10. Also draw a flowchart for this algorithm.
Here's a simple algorithm to find the highest and lowest marks obtained by students of batch size 10:
Algorithm: Find Highest and Lowest Marks
1. Initialize variables highest_mark and lowest_mark to store the highest and lowest marks.
2. Set highest_mark and lowest_mark to the first student's marks in the batch.
3. For each subsequent student's marks in the batch:
a. If the marks are higher than highest_mark, update highest_mark.
b. If the marks are lower than lowest_mark, update lowest_mark.
4. Print highest_mark and lowest_mark as the highest and lowest marks obtained by the students.
Flowchart:
[Start]
|
V
[Initialize highest_mark, lowest_mark]
|
V
[Read marks]
|
V
[Is marks > highest_mark ?]
/ \
[No] [Yes]
| |
V V
[Is marks < lowest_mark ?] [Update highest_mark]
| |
V |
[Yes] |
| |
V |
[Update lowest_mark] |
| |
V |
[Read next marks] ---------------|
|
V
[End of batch size]
|
V
[Print highest_mark, lowest_mark]
|
V
[End]
(b) Write a recursive program/function in C to
find factorial of a given number between
1 to 10.
Here's a recursive C function to find the factorial of a given number between 1 to 10:
#include <stdio.h>
int factorial(int n) {
// Base case: factorial of 0 and 1 is 1
if (n == 0 || n == 1) {
return 1;
}
// Recursive case: factorial of n is n * factorial of (n - 1)
else {
return n * factorial(n - 1);
}
}
int main() {
int num;
printf("Enter a number between 1 and 10: ");
scanf("%d", &num);
// Checking if the entered number is within the specified range
if (num < 1 || num > 10) {
printf("Number out of range. Please enter a number between 1 and 10.\n");
return 1; // indicating error
}
// Calculating factorial and printing the result
printf("Factorial of %d is %d\n", num, factorial(num));
return 0;
}
This program takes a number as input, checks if it's within the specified range (1 to 10), calculates its factorial using a recursive function, and then prints the result.
(c) Write a program in ‘C’ to sort an array of
10 elements in ascending order
Certainly! Here's a simple implementation of the bubble sort algorithm in C to sort an array of 10 elements in ascending order:
#include <stdio.h>
void bubbleSort(int arr[], int n) {
int i, j, temp;
for (i = 0; i < n-1; i++) {
for (j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
// Swap arr[j] and arr[j+1]
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
int main() {
int arr[10];
int i;
printf("Enter 10 elements:\n");
for (i = 0; i < 10; i++) {
scanf("%d", &arr[i]);
}
// Sort the array
bubbleSort(arr, 10);
printf("Sorted array in ascending order:\n");
for (i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
This program takes 10 integer inputs from the user, sorts them using the bubble sort algorithm, and then prints the sorted array in ascending order.
(d) Explain difference between call by value and call by reference with the help of
examples
In C, "call by value" and "call by reference" are two different ways to pass arguments to functions. Let's break down each method with examples:
1. **Call by Value**:
- In call by value, a copy of the actual parameter's value is passed to the function parameter. Any modifications made to the parameter inside the function do not affect the original argument.
- This method is typically used for passing basic data types like integers, characters, or floats.
- Here's an example:
#include <stdio.h>
// Function prototype
void modify(int x);
int main() {
int num = 10;
printf("Before calling modify function, num = %d\n", num);
// Calling the function
modify(num);
printf("After calling modify function, num = %d\n", num);
return 0;
}
// Function definition
void modify(int x) {
x = x * 2;
printf("Inside modify function, x = %d\n", x);
}
Output:
Before calling modify function, num = 10
Inside modify function, x = 20
After calling modify function, num = 10
In this example, the value of num remains unchanged after calling the modify function because num is passed by value.
2. **Call by Reference**:
- In call by reference, the memory address of the actual parameter is passed to the function parameter. This allows the function to directly access and modify the original data.
- This method is often used for passing arrays or structures where passing by value would be inefficient.
- Here's an example:
#include <stdio.h>
// Function prototype
void modify(int *ptr);
int main() {
int num = 10;
printf("Before calling modify function, num = %d\n", num);
// Calling the function
modify(&num);
printf("After calling modify function, num = %d\n", num);
return 0;
}
// Function definition
void modify(int *ptr) {
*ptr = *ptr * 2;
printf("Inside modify function, *ptr = %d\n", *ptr);
}
Output:
Before calling modify function, num = 10
Inside modify function, *ptr = 20
After calling modify function, num = 20
In this example, the value of num is modified inside the modify function because num is passed by reference (by passing its memory address). Hence, changes made to *ptr inside the function affect the original num variable.
2. (a) What is Union ? How is it different from
structure ? Explain declaration and use of
union in C with the help of an example and
program.
In C programming, a union is a user-defined data type that allows storing different types of data in the same memory location. It is similar to a structure in that it can hold multiple members, but in a union, all members share the same memory space. This means that only one member of the union can hold a value at any given time.
Here's how a union declaration looks:
union MyUnion {
int intValue;
float floatValue;
char charValue;
};
In the above example, `MyUnion` is declared as a union with three members: an integer intValue, a float floatValue, and a character charValue. All of these members share the same memory space, so only one of them can contain a value at a time.
Here's an example of how you might use a union in a C program:
#include <stdio.h>
union MyUnion {
int intValue;
float floatValue;
char charValue;
};
int main() {
union MyUnion myUnion;
myUnion.intValue = 10;
printf("Integer value: %d\n", myUnion.intValue);
myUnion.floatValue = 3.14;
printf("Float value: %f\n", myUnion.floatValue);
myUnion.charValue = 'A';
printf("Char value: %c\n", myUnion.charValue);
return 0;
}
In this program:
- We declare a union `MyUnion` with three members: intValue, floatValue, and charValue.
- We create a variable `myUnion` of type `MyUnion`.
- We assign values to each member of the union (intValue, `floatValue`, `charValue`) and print them out.
- Notice that each time we assign a value to a member, it overwrites the previous value because they share the same memory space.
When you run this program, you'll see that each member of the union holds the value assigned to it, but only one member can hold a value at a time due to the shared memory space.
(b) Write a C program to find the average of
diagonal elements of a matrix of 6 × 6.
Sure, here's a simple C program to find the average of the diagonal elements of a 6x6 matrix:
#include <stdio.h>
int main() {
int matrix[6][6];
int i, j;
float sum = 0.0;
float avg;
// Input matrix elements
printf("Enter the elements of the 6x6 matrix:\n");
for (i = 0; i < 6; i++) {
for (j = 0; j < 6; j++) {
printf("Enter element [%d][%d]: ", i, j);
scanf("%d", &matrix[i][j]);
}
}
// Calculate sum of diagonal elements
for (i = 0; i < 6; i++) {
sum += matrix[i][i]; // Diagonal elements have same row and column index
}
// Calculate average
avg = sum / 6.0;
// Display the average
printf("Average of diagonal elements: %.2f\n", avg);
return 0;
}
This program prompts the user to enter the elements of the 6x6 matrix, calculates the sum of diagonal elements, and then finds the average by dividing the sum by the number of diagonal elements (which is 6 in this case). Finally, it displays the average value.
3. (a) Write the syntax and explain the use of the following functions in C :
(i) malloc
(ii) fputc
(iii) strcat
(iv) fclose
Certainly! Here's the syntax and explanation for each of the mentioned functions in C:
### (i) malloc
**Syntax:**
void* malloc(size_t size);
**Explanation:**
malloc is short for "memory allocation". It is used to dynamically allocate memory during the execution of a program. It takes the number of bytes to allocate as an argument and returns a pointer to the beginning of the allocated memory. If the allocation fails (for example, due to insufficient memory), it returns NULL. It's important to remember to free dynamically allocated memory using the free() function when it is no longer needed to avoid memory leaks.
### (ii) fputc
**Syntax:**
int fputc(int character, FILE *stream);
**Explanation:**
fputc is used to write a single character to a file. It takes two arguments: the character to be written (`character`) and a pointer to the file (`stream`) where the character will be written. It returns the character written on success and EOF if an error occurs.
### (iii) strcat
**Syntax:**
char *strcat(char *dest, const char *src);
**Explanation:**
`strcat` is short for "string concatenate". It is used to concatenate (join) two strings. It takes two arguments: `dest`, the destination string where the content of `src` will be appended, and `src`, the source string whose content will be appended to `dest`. It returns a pointer to the resulting string (`dest`).
### (iv) fclose
**Syntax:**
int fclose(FILE *stream);
**Explanation:**
fclose is used to close a file. It takes a pointer to the file (`stream`) that needs to be closed as its argument. Once a file is closed, further operations on it are not allowed unless it is reopened. `fclose` returns zero upon success and `EOF` if an error occurs while closing the file.
These functions are fundamental in C programming for tasks related to memory management, file I/O, and string manipulation.
(b) Write a C program using pointers to find whether a given string is palidrome or not.
Certainly! Below is a simple C program that uses pointers to determine whether a given string is a palindrome or not:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
// Function to check if a character is alphanumeric
int isAlphanumeric(char ch) {
return (isalpha(ch) || isdigit(ch));
}
// Function to convert a character to lowercase
char toLower(char ch) {
return tolower(ch);
}
// Function to check if a string is a palindrome
int isPalindrome(char *str) {
// Pointers for beginning and end of the string
char *start = str;
char *end = str + strlen(str) - 1;
// Loop until pointers meet
while (start < end) {
// Skip non-alphanumeric characters from start
while (!isAlphanumeric(*start))
start++;
// Skip non-alphanumeric characters from end
while (!isAlphanumeric(*end))
end--;
// If characters are not same, not a palindrome
if (toLower(*start) != toLower(*end))
return 0;
// Move pointers
start++;
end--;
}
return 1;
}
int main() {
char str[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
// Remove trailing newline character if present
if (str[strlen(str) - 1] == '\n')
str[strlen(str) - 1] = '\0';
if (isPalindrome(str))
printf("The string is a palindrome.\n");
else
printf("The string is not a palindrome.\n");
return 0;
}
This program prompts the user to enter a string, then checks whether it's a palindrome using pointers. It disregards non-alphanumeric characters and considers case-insensitivity while comparing characters.
4. (a) Write a ‘C’ program to copy a given string into another string without using inbuilt function. Also display the length of the resultant string.
Sure, here's a simple 'C' program to copy a given string into another string without using any inbuilt functions, and then display the length of the resultant string:
#include <stdio.h>
// Function to calculate string length
int stringLength(char *str) {
int len = 0;
while (*str != '\0') {
len++;
str++;
}
return len;
}
// Function to copy string
void stringCopy(char *src, char *dest) {
while (*src != '\0') {
*dest = *src;
src++;
dest++;
}
*dest = '\0'; // Null-terminate the destination string
}
int main() {
char source[100], destination[100];
printf("Enter a string: ");
scanf("%s", source);
stringCopy(source, destination);
printf("Copied string: %s\n", destination);
printf("Length of the copied string: %d\n", stringLength(destination));
return 0;
}
This program prompts the user to enter a string, then copies that string into another string without using any inbuilt functions, and finally displays the copied string and its length.
b) Explain the use of the following statements with the help of an example :
(i) Switch statement
(ii) Else-if statement
Sure, here's an explanation in C for both the switch statement and the else-if statement with examples:
(i) Switch statement:
The switch statement is used to perform different actions based on different conditions. It evaluates an expression and matches the result to one of several possible cases. It's a cleaner alternative to using multiple if-else statements when you have multiple conditions to check against the same variable.
Example:
#include <stdio.h>
int main() {
int choice;
printf("Enter a number (1-3): ");
scanf("%d", &choice);
switch(choice) {
case 1:
printf("You entered 1.\n");
break;
case 2:
printf("You entered 2.\n");
break;
case 3:
printf("You entered 3.\n");
break;
default:
printf("Invalid choice.\n");
}
return 0;
}
In this example, the user inputs a number, and based on that input, the program prints a corresponding message.
(ii) Else-if statement:
The else-if statement allows you to test multiple conditions and execute a block of code for each condition that evaluates to true. It's used when you have multiple conditions to check sequentially.
Example:
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if(num > 0) {
printf("The number is positive.\n");
}
else if(num < 0) {
printf("The number is negative.\n");
}
else {
printf("The number is zero.\n");
}
return 0;
}
In this example, the program checks whether the entered number is positive, negative, or zero, and prints a corresponding message based on the condition. If the first condition is false, it moves to the next else-if condition, and so on, until it finds a true condition or reaches the final else statement.
(c) Write a macro to evaluate :
\(𝑓(𝑥) = 5𝑥^3 + 2𝑥 + 3\)
You can write a macro in C to evaluate the function \( f(x) = 5x^3 + 2x + 3 \) like this:
#include <stdio.h>
#define FUNCTION(x) (5 * (x) * (x) * (x) + 2 * (x) + 3)
int main() {
double x = 2.0; // You can change x to any value you want to evaluate the function at
double result = FUNCTION(x);
printf("f(%lf) = %lf\n", x, result);
return 0;
}
This macro substitutes the value of \( x \) into the function \( f(x) \) and calculates the result. Remember to include the necessary headers and define the appropriate data types based on your needs.
5. (a) Write a program to display the following pattern :
1 2 3 4
5 6 7
8 9
Here's a simple C program to display the given pattern:
#include <stdio.h>
int main() {
int rows = 3;
int number = 1;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < rows - i; j++) {
printf("%d ", number++);
}
printf("\n");
}
return 0;
}
This program will display the pattern:
1 2 3 4
5 6 7
8 9
(b) Write C program to swap two given values.
Certainly! Below is a simple C program to swap two given values using a temporary variable:
#include <stdio.h>
// Function to swap two values
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x, y;
// Input the values to swap
printf("Enter value for x: ");
scanf("%d", &x);
printf("Enter value for y: ");
scanf("%d", &y);
// Print values before swapping
printf("Before swapping:\n");
printf("x = %d, y = %d\n", x, y);
// Call swap function
swap(&x, &y);
// Print values after swapping
printf("After swapping:\n");
printf("x = %d, y = %d\n", x, y);
return 0;
}
This program takes two integers as input, swaps their values using a temporary variable, and then prints the swapped values.
(c) Write C program to open an existing file “My.TXT” and read its content and display it.
Sure, here's a simple C program to open an existing file named "My.txt", read its content, and display it:
#include <stdio.h>
int main() {
FILE *file_pointer;
char ch;
// Open the file in read mode
file_pointer = fopen("My.txt", "r");
// Check if file opened successfully
if (file_pointer == NULL) {
printf("Unable to open file.\n");
return 1;
}
// Read and display contents character by character
printf("Contents of the file:\n");
while ((ch = fgetc(file_pointer)) != EOF) {
printf("%c", ch);
}
// Close the file
fclose(file_pointer);
return 0;
}
Make sure that the file "My.txt" is in the same directory as your C program or provide the correct path to the file in the `fopen()` function.
Comments
Post a Comment