MCS-11 JUNE 2023 QUESTION AND ANSWER
1. (a) Write an algorithm to calculate simple interest. Also draw flow chart for this algorithm (Hint : SI = (PTR)/100).
Read 1.3 (unit-1)
Answer: In this post, we will write a simple algorithm and draw a flowchart for calculating Simple Interest.
Inputs: Principle Amount(PA), RateOfInterest(ROI), Time
Formula to Calculate Simple Interest(SI): SI=((PA*ROI*Time)/100)
Algorithm to find Simple Interest:
Step 1: Start
Step 2: Read Principle Amount(PA), Rate Of Interest(ROI), Time
Step 3: SI= ((PA*ROI*Time)/100)
Step 4: Print SI
Step 5: Stop
Flowchart to Calculate Simple Interest:
(b) Write a C program to create a structure to store name, rollnumber, address and course (BCA, MCA) of ten students. Use array of structure to display details of the students.
Here's a C program to create a structure to store the details of ten students (name, roll number, address, and course) using an array of structures:
#include <stdio.h>
// Define a structure for student
struct Student {
char name[50];
int rollNumber;
char address[100];
char course[4]; // Assuming course code (BCA, MCA) fits in 4 characters
};
int main() {
// Declare an array of structures to store details of ten students
struct Student students[10];
// Input details for each student
for (int i = 0; i < 10; i++) {
printf("Enter details for student %d:\n", i + 1);
printf("Name: ");
scanf("%s", students[i].name);
printf("Roll Number: ");
scanf("%d", &students[i].rollNumber);
printf("Address: ");
scanf("%s", students[i].address);
printf("Course (BCA/MCA): ");
scanf("%s", students[i].course);
}
// Display details of all students
printf("\nDetails of all students:\n");
for (int i = 0; i < 10; i++) {
printf("Student %d\n", i + 1);
printf("Name: %s\n", students[i].name);
printf("Roll Number: %d\n", students[i].rollNumber);
printf("Address: %s\n", students[i].address);
printf("Course: %s\n", students[i].course);
printf("\n");
}
return 0;
}
In this program, a structure `Student` is defined to hold the details of each student. An array of `Student` structures is declared to store the details of ten students. The program then prompts the user to input details for each student one by one. Finally, it displays the details of all the students entered.
(c) Write a C program which read an array of ten integer values and search a given value in the array. If that value exist in the array display its square otherwise display. “The value is missing.”
(d) Write a program in ‘C’ using printf to find the length of a given string. 10
#include <stdio.h>
int main() {
char str[100]; // Assuming maximum length of string is 100 characters
printf("Enter a string: ");
scanf("%s", str); // Input a string from user
int length = 0;
// Iterate through the string until the null terminator is reached
while (str[length] != '\0') {
length++;
}
printf("Length of the string is: %d\n", length);
return 0;
}
or 2nd solution :
#include <stdio.h>
// Function to find the length of a string
int stringLength(char *str) {
int length = 0;
// Iterate through the string until the null terminator is reached
while (*str != '\0') {
length++;
str++;
}
return length;
}
int main() {
char str[100]; // Assuming maximum length of string is 100 characters
printf("Enter a string: ");
scanf("%s", str); // Input a string from user
int length = stringLength(str); // Call the function to find the length
printf("Length of the string is: %d\n", length);
return 0;
}
2. (a) Write a C program to find the sum of the following series upto 20 terms :
1 4 7 10 13 +++ + ..............
#include <stdio.h>
int main() {
int i;
int sum = 0;
int term = 1;
for (i = 0; i < 20; i++) {
sum += term;
term += 3;
}
printf("Sum of the series up to 20 terms: %d\n", sum);
return 0;
}
(b) Briefly explain two categories of constants in C. 4
In C programming, constants are values that do not change during program execution. They are categorized into two main types:
1. Primary Constants: These are basic constants with fixed values. They are subdivided into:
- Integer Constants: Whole number values, such as 5, -10, or 0.
- Floating-point Constants: Real numbers with decimal points or exponents, like 3.14 or 2.5e3.
- Character Constants: Single characters enclosed in single quotes, such as 'A' or '$'.
- String Constants: Sequences of characters enclosed in double quotes, like "hello" or "world".
2. **Secondary Constants**: These are derived constants or symbolic constants defined using #define preprocessor directive or const keyword. They are typically used to improve code readability and maintainability. Examples include:
- #define PI 3.14159: Defines a symbolic constant PI.
- const int MAX_SIZE = 100;: Defines a constant variable MAX_SIZE with a value of 100.
These categories of constants provide a way to represent fixed values in C programs, enhancing code clarity, maintainability, and flexibility.
(c) Write a C program for multiplication of two 4 × 4 matrices. 10
https://youtu.be/55l-aZ7_F24?si=bgOG_GHuimWU44sx
3. (a) Explain the difference between a++ and ++a. Also find the value that would be printed by the following code : 6
int a = 4;
int b = 2;
int c = 0;
a = c++;
a = a + b++;
printf (" a %d ",a); = IGNOUAssignment
Answer:
The expressions `a++` and `++a` are both increment operators in C and C++. They are used to increment the value of a variable by 1. However, they have a slight difference in their behavior:
1. `a++`: This is the post-increment operator. It first uses the current value of `a` in the expression and then increments `a` by 1.
2. ++a : This is the pre-increment operator. It first increments a by 1 and then uses the updated value in the expression.
Let's analyze the code snippet you provided:
int a = 4;
int b = 2;
int c = 0;
a = c++; // This assigns the current value of c (which is 0) to a and then increments c by 1
a = a + b++; // This assigns the sum of a and the current value of b to a, and then increments b by 1
printf("a %d ", a);
Here's the breakdown of the code:
1. a = c++; : a gets assigned the value of c, which is 0. After the assignment, c is incremented by 1. So, a becomes 0, and c becomes 1.
2. a = a + b++;: `a` is incremented by the current value of `b` (which is 2), resulting in `a` becoming 2. Then, `b` is incremented by 1. So, after this line, `a` becomes 2, and `b` becomes 3.
Therefore, the value printed by printf would be `a 2`.
1. https://youtu.be/sTSvGTcPeRU?si=mU2f6R5sziLtvwAA
(b) Explain the use of conditional operator with the help of an example.
Answer:
In C language, the conditional operator (also known as the ternary operator) is represented by the question mark `?` and the colon , :, . It's a shorthand way of writing an if-else statement.
Here's the syntax:
condition ? expression1 : expression2;
If the condition is true, the expression1 is evaluated; otherwise, expression2 is evaluated.
Here's an example:
#include <stdio.h>
int main() {
int num = 10;
int result;
// Using conditional operator to determine if num is even or odd
result = (num % 2 == 0) ? 1 : 0;
if (result == 1) {
printf("%d is even.\n", num);
} else {
printf("%d is odd.\n", num);
}
return 0;
}
In this example, if num is divisible by 2 (i.e., num % 2 == 0), then result will be assigned the value 1. Otherwise, result will be assigned the value 0. Then, based on the value of result, it will print whether num is even or odd.
(c) What is for loop ? How is it different from do .......... while loop ? Explain with the help of an example. Also explain use of “break statement”.
A for loop and a do...while loop are both control flow constructs in programming used for iteration, but they differ in their execution order and conditions.
A for loop:
- It iterates a specific number of times.
- It typically consists of three parts: initialization, condition, and increment/decrement.
- The loop body is executed as long as the condition remains true.
Example:
#include <stdio.h>
int main() {
// Example of a for loop
int i;
for (i = 0; i < 5; i++) {
printf("Iteration %d\n", i);
}
return 0;
}
This loop will print "Iteration 0" to "Iteration 4".
A "do...while" loop:
- It executes the loop body at least once before checking the condition.
- It continues to execute the loop body as long as the condition remains true.
Example:
#include <stdio.h>
int main() {
// Example of a do...while loop
int i = 0;
do {
printf("Iteration %d\n", i);
i++;
} while (i < 5);
return 0;
}
This loop will also print "Iteration 0" to "Iteration 4", but the key difference is that the condition is checked after the first execution.
The break statement:
- It is used to exit a loop prematurely.
- It can be used within loops to terminate the loop early based on a certain condition.
Example:
#include <stdio.h>
int main() {
// Example of using break statement
int i;
for (i = 0; i < 10; i++) {
if (i == 5) {
break; // Exit the loop when i equals 5
}
printf("Iteration %d\n", i);
}
return 0;
}
This loop will print "Iteration 0" to "Iteration 4", and then it will terminate when `i` becomes 5 due to the `break` statement.
4. (a) Write a ‘C’ program, using structures, to calculate the gross salary and net salary if Basic, D. A., T. A. and deduction are given as input.
Certainly! Here's a simple 'C' program using structures to calculate the gross salary and net salary based on the inputs of Basic salary, Dearness Allowance (D.A.), Travel Allowance (T.A.), and deductions:
#include <stdio.h>
// Structure definition for an Employee
struct Employee {
float basic;
float da;
float ta;
float deduction;
float gross_salary;//gros_salary=basic+da+ta
float net_salary;//net= gross-deduction
};
// Function to calculate gross salary
float calculateGross(struct Employee emp) {
return emp.basic + emp.da + emp.ta;
}
// Function to calculate net salary
float calculateNet(struct Employee emp) {
return emp.gross_salary - emp.deduction;
}
int main() {
struct Employee emp;
// Input Basic, D.A., T.A., and deductions
printf("Enter Basic Salary: ");
scanf("%f", &emp.basic);
printf("Enter Dearness Allowance (D.A.): ");
scanf("%f", &emp.da);
printf("Enter Travel Allowance (T.A.): ");
scanf("%f", &emp.ta);
printf("Enter Deductions: ");
scanf("%f", &emp.deduction);
// Calculate Gross Salary
emp.gross_salary = calculateGross(emp);
// Calculate Net Salary
emp.net_salary = calculateNet(emp);
// Output Gross and Net Salaries
printf("\nGross Salary: %.2f\n", emp.gross_salary);
printf("Net Salary: %.2f\n", emp.net_salary);
return 0;
}
This program prompts the user to input the basic salary, D.A., T.A., and deductions. Then it calculates the gross salary by adding basic, D.A., and T.A., and the net salary by subtracting deductions from the gross salary. Finally, it prints out the gross and net salaries.
Sure, here's a breakdown of each function's syntax and purpose in C:
(b) Write the syntax and explain the use of the following functions in C : 2×4=8 (i) return (ii) malloc (iii) isupper (iv) fclose
(i) return:
- Syntax: return expression;
- Explanation: The return statement is used to exit a function and return a value to the calling code. The expression following the return keyword is optional and represents the value to be returned. If the function has a return type other than `void`, it must return a value of that type.
(ii) malloc:
- Syntax: void *malloc(size_t size);
- Explanation: The `malloc` function is used to allocate memory dynamically during program execution. It allocates a block of memory of size `size` bytes and returns a pointer to the beginning of the allocated memory. It does not initialize the memory, so the content of the allocated memory block is undetermined. It returns `NULL` if it fails to allocate the requested memory.
(iii) supper:
- Syntax: int isupper(int c);
- Explanation: The isupper function is used to check if a character is an uppercase letter in the ASCII character set. It takes a single argument `c`, which is an integer representing a character, and returns a non-zero value (true) if the character is an uppercase letter, and 0 (false) otherwise.
(iv) fclose:
- Syntax: int fclose(FILE *stream);
- Explanation: The `fclose` function is used to close a file stream that was previously opened using `fopen`, `freopen`, or `fdopen`. It takes a pointer to a `FILE` object (`stream`) as its argument and returns zero if the stream is successfully closed. It also flushes any buffered data associated with the stream before closing it. If the function fails to close the stream, it returns `EOF` and sets the `errno` variable to indicate the error.
Sure, here's the syntax and explanation for each of the functions you mentioned in C:
(ii) malloc:
Syntax:
void* malloc(size_t size);
Explanation:
malloc is a function in C that stands for "memory allocation". It is used to dynamically allocate memory during the execution of a program. It takes one argument, `size`, which specifies the number of bytes of memory to allocate. The function returns a pointer to the allocated memory block if the allocation is successful, or `NULL` if the allocation fails.
Example usage:
#include <stdlib.h>
int *ptr;
ptr = (int*) malloc(10 * sizeof(int)); // Allocates memory for an array of 10 integers
if (ptr == NULL) {
// Allocation failed
printf("Memory allocation failed.\n");
} else {
// Allocation successful, use the allocated memory
// Remember to free the allocated memory when it's no longer needed
free(ptr);
}
(iii) isupper:
Syntax:
int isupper(int c);
Explanation:
`isupper` is a function in C that checks whether a given character is an uppercase alphabet letter or not. It takes one argument `c`, which is the character to be checked. It returns a non-zero value (true) if the character is an uppercase letter, and 0 (false) otherwise.
Example usage:
#include <ctype.h>
char ch = 'A';
if (isupper(ch)) {
printf("%c is an uppercase letter.\n", ch);
} else {
printf("%c is not an uppercase letter.\n", ch);
}
(iv) fclose:
Syntax:
int fclose(FILE *stream);
Explanation:
`fclose` is a function in C that closes the given file stream. It takes one argument `stream`, which is a pointer to the file stream to be closed. The function returns 0 if the stream is successfully closed, and `EOF` if an error occurs.
Example usage:
#include <stdio.h>
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file.\n");
} else {
// File operations
// After finishing file operations, close the file
if (fclose(file) == 0) {
printf("File closed successfully.\n");
} else {
printf("Error closing file.\n");
}
}
(c) Define a macro to find the cube of a given number .
Let's define the macro in C programming language. Here's how I can define a macro to find the cube of a given number:
#define CUBE(x) ((x) * (x) * (x))
I can use this macro by passing the number I want to find the cube of as an argument. For example:
#include <stdio.h>
#define CUBE(x) ((x) * (x) * (x))
int main() {
int num = 5;
int result = CUBE(num);
printf("The cube of %d is %d\n", num, result);
return 0;
}
This will output:
The cube of 5 is 125
5(a) Write C program which take a string as input and print it in reverse order, without using any in-built function.
Here's a simple C program that takes a string as input and prints it in reverse order without using any built-in functions:
#include <stdio.h>
// Function to calculate the length of a string
int stringLength(char *str) {
int length = 0;
while (*str != '\0') {
length++;
str++;
}
return length;
}
// Function to print a string in reverse order
void printReverse(char *str) {
int length = stringLength(str);
// Traverse the string in reverse order and print each character
for (int i = length - 1; i >= 0; i--) {
printf("%c", str[i]);
}
}
int main() {
char str[100];
// Input string from the user
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
// Print the string in reverse order
printf("Reversed string: ");
printReverse(str);
return 0;
}
NEXT SOLUTION
Here's a simple C program to achieve that:
#include <stdio.h>
// Function to find the length of the string
int length(char *str) {
int len = 0;
while (*(str + len) != '\0') {
len++;
}
return len;
}
// Function to print the string in reverse order
void printReverse(char *str) {
int len = length(str);
// Start from the end of the string and print each character
for (int i = len - 1; i >= 0; i--) {
printf("%c", *(str + i));
}
printf("\n");
}
int main() {
char str[100];
// Input the string
printf("Enter a string: ");
scanf("%s", str);
// Print the string in reverse order
printf("Reverse of the string: ");
printReverse(str);
return 0;
}
This program takes a string as input, calculates its length without using any built-in functions, and then prints the string in reverse order by iterating through the string from the end to the beginning.
https://youtu.be/UPfpVm5PWes?si=Qs7JgLbJsBLV9iR9
https://youtu.be/bk-Bw7jzZK4?si=L5Ut7udXkarR9sae
(b) Write a C program to check whether a file whose name is given exist or not in the given list of file names.
Here's a simple C program that checks if a file with a given name exists in a list of file names:
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
// Function to check if a file exists in the list
bool fileExists(const char *fileName, const char *fileList[], int numFiles) {
for (int i = 0; i < numFiles; i++) {
if (strcmp(fileName, fileList[i]) == 0) {
return true;
}
}
return false;
}
int main() {
const char *fileList[] = {"file1.txt", "file2.txt", "file3.txt"}; // List of file names
int numFiles = sizeof(fileList) / sizeof(fileList[0]); // Calculate number of files in the list
char fileName[100];
printf("Enter the name of the file to check: ");
scanf("%s", fileName);
if (fileExists(fileName, fileList, numFiles)) {
printf("File '%s' exists in the list.\n", fileName);
} else {
printf("File '%s' does not exist in the list.\n", fileName);
}
return 0;
}
This program prompts the user to enter the name of the file they want to check. It then compares this input against the list of file names using the fileExists function. If the file is found in the list, it prints a message stating that the file exists, otherwise, it prints a message stating that the file does not exist.
(c) Explain the following with the help of a suitable example for each :
(i) File access modes
(ii) Array of pointers
(iii) Automatic variable
(iv) Size of operator
Here's an explanation of each term with an example:
(i) File Access Modes:
File access modes determine how files can be opened and manipulated in a programming language. Common modes include read, write, append, etc.
Example:
#include <stdio.h>
int main() {
FILE *file_pointer;
char data[100];
// Open file for writing
file_pointer = fopen("example.txt", "w");
// Write data to the file
fprintf(file_pointer, "Hello, world!");
// Close the file
fclose(file_pointer);
return 0;
}
In this example, `"w"` mode is used to open the file example.txt for writing. Other modes like `"r"` (read) and `"a"` (append) can also be used.
(ii) Array of Pointers:
An array of pointers is an array where each element is a pointer to some data type.
Example:
#include <stdio.h>
int main() {
int *ptr_array[3]; // Array of integer pointers
int var1 = 10, var2 = 20, var3 = 30;
// Assign addresses of variables to array elements
ptr_array[0] = &var1;
ptr_array[1] = &var2;
ptr_array[2] = &var3;
// Access and dereference pointers
printf("Value at ptr_array[0]: %d\n", *ptr_array[0]);
printf("Value at ptr_array[1]: %d\n", *ptr_array[1]);
printf("Value at ptr_array[2]: %d\n", *ptr_array[2]);
return 0;
}
In this example, `ptr_array` is an array of integer pointers. Each element of `ptr_array` holds the address of a different integer variable.
(iii) **Automatic Variable**:
An automatic variable is a variable declared within a function. It is created when the function is called and destroyed when the function exits.
Example:
#include <stdio.h>
void func() {
int x = 10; // Automatic variable
printf("Value of x: %d\n", x);
}
int main() {
func();
return 0;
}
In this example, X is an automatic variable declared inside the function func(). It is created when `func()` is called and destroyed when func() exits.
(iv) Size of Operator :
The sizeof operator in C/C++ returns the size of a variable or data type in bytes.
Example:
#include <stdio.h>
int main() {
int a;
double b;
char c;
printf("Size of int: %lu bytes\n", sizeof(a));
printf("Size of double: %lu bytes\n", sizeof(b));
printf("Size of char: %lu bytes\n", sizeof(c));
return 0;
}
In this example, sizeof is used to determine the size of int, double , and char data types. The result is dependent on the compiler and the platform being used.
Comments
Post a Comment