MCS–011, December, 2023, Question & answer
1. (a) Write an algorithm and draw a corresponding flow chart to check whether the number is prime or not.
(b) Write a program in C to find the sum of digits of a 5-digit number.
Certainly! Here's a simple C program to find the sum of digits of a 5-digit number:
#include <stdio.h>
int main() {
int number, sum = 0;
printf("Enter a 5-digit number: ");
scanf("%d", &number);
if(number < 10000 || number > 99999) {
printf("Invalid input. Please enter a 5-digit number.\n");
return 1;
}
while(number != 0) {
sum += number % 10; // Extract the last digit and add it to sum
number /= 10; // Remove the last digit from number
}
printf("Sum of digits: %d\n", sum);
return 0;
}
This program first checks if the input number is a 5-digit number or not. If it's not, it prints an error message. Otherwise, it proceeds to calculate the sum of digits using a while loop. Finally, it prints the sum of digits.
#include <stdio.h>
int main() {
int number, sum = 0;
printf("Enter a 5-digit number: ");
scanf("%d", &number);
if(number < 10000 || number > 99999) {
printf("Invalid input. Please enter a 5-digit number.\n");
return 1;
}
while(number != 0) {
sum += number % 10; // Extract the last digit and add it to sum
number /= 10; // Remove the last digit from number
}
printf("Sum of digits: %d\n", sum);
return 0;
}
This program first checks if the input number is a 5-digit number or not. If it's not, it prints an error message. Otherwise, it proceeds to calculate the sum of digits using a while loop. Finally, it prints the sum of digits.
or
#include <stdio.h>
int main() {
int number, sum = 0;
printf("Enter a 5-digit number: ");
scanf("%d", &number);
// Check if the entered number is a 5-digit number
if (number < 10000 || number > 99999) {
printf("Please enter a valid 5-digit number.\n");
return 1; // Exit the program with an error code
}
// Calculate the sum of digits
while (number > 0) {
sum += number % 10; // Add the last digit to the sum
number /= 10; // Remove the last digit from the number
}
printf("Sum of digits: %d\n", sum);
return 0;
}
(c) Write a C program to generate the following pattern :
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
Here's a C program to generate the pattern you described:
#include <stdio.h>
int main() {
int rows = 5; // Number of rows in the pattern
// Loop through rows
for (int i = 1; i <= rows; i++) {
// Loop to print each number in the row
for (int j = 1; j <= i; j++) {
printf("%d ", i); // Print the current row number
}
printf("\n"); // Move to the next line for the next row
}
return 0;
}
This program generates the pattern by printing the row number `i` a total of `i` times for each row, starting from 1 and going up to 5, as specified in your pattern.
(d) Write a C function to find the square of an integer.
Certainly! Below is a simple C function that takes an integer as input and returns the square of that integer:
#include <stdio.h>
int square(int num) {
return num * num;
}
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
int result = square(number);
printf("The square of %d is %d\n", number, result);
return 0;
}
This program defines a function called square that takes an integer num as input and returns the square of that number. In the main function, it prompts the user to enter an integer, calculates its square using the square function, and then prints the result.
(e) Explain the use of pointers and its
characteristics.
(f) Describe the conditional statements
“Multiple-if” and “nested-if” with one
example for each
Here's a brief explanation of both "multiple-if" and "nested-if" conditional statements in C language along with an example for each:
1. **Multiple-if statement**: In this type of conditional statement, multiple independent if conditions are checked sequentially. If any of the conditions are true, the corresponding block of code is executed.
#include <stdio.h>
int main() {
int num = 10;
if (num == 5) {
printf("Number is equal to 5\n");
}
if (num == 10) {
printf("Number is equal to 10\n");
}
if (num == 15) {
printf("Number is equal to 15\n");
}
return 0;
}
In this example, if the variable num is equal to 10, the second `if` condition will be true, and the corresponding block of code will be executed, printing "Number is equal to 10".
2. **Nested-if statement**: In this type of conditional statement, an if statement is nested inside another if statement. This is useful when you want to check for multiple conditions with a certain hierarchy.
#include <stdio.h>
int main() {
int num = 15;
if (num > 10) {
printf("Number is greater than 10\n");
if (num < 20) {
printf("Number is less than 20\n");
}
}
return 0;
}
In this example, if the variable num is greater than 10, it enters the outer `if` statement, then it checks if num is less than 20 within the inner `if` statement. If both conditions are true, it prints "Number is greater than 10" followed by "Number is less than 20".
2. (a) Explain the type of errors in C program by
giving an example for each.
In C programming, errors can broadly be categorized into three types: syntax errors, runtime errors, and logical errors. Here's an explanation of each type with examples:
1. Syntax Errors: Syntax errors occur when the rules of the programming language are not followed. These errors are detected by the compiler during the compilation process. They prevent the program from being compiled successfully.Example:
#include <stdio.h>
int main() {
printf("Hello, world!\n") // Missing semicolon
return 0;
}
In this example, the syntax error is the missing semicolon at the end of the printf statement. The compiler will report an error like "expected ';' before 'return'".
2.Runtime Errors: Runtime errors occur while the program is running. These errors cause the program to terminate abnormally. Runtime errors are often caused by illegal operations or unexpected conditions that occur during program execution.Example:
#include <stdio.h>
int main() {
int a = 10, b = 0, result;
result = a / b; // Division by zero
printf("Result: %d\n", result);
return 0;
}
In this example, a runtime error occurs because the program tries to divide by zero, which is not allowed in mathematics. When executed, this program will produce a runtime error, such as a "floating-point exception" or "division by zero" error.
3.Logical Errors: Logical errors occur when the program compiles and runs without any errors, but it does not produce the expected output due to incorrect logic or algorithmic mistakes.Example:
#include <stdio.h>
int main() {
int num1 = 5, num2 = 7, sum;
sum = num1 * num2; // Incorrect operation
printf("Sum of %d and %d is %d\n", num1, num2, sum);
return 0;
}
In this example, the program intends to calculate the sum of num1 and num2, but it uses the multiplication operator instead of the addition operator. As a result, the output will be incorrect, and the program will have a logical error.
(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.
#include <stdio.h>
// Define structure for employee details
struct Employee {
char name[50];
float basicPay;
float TA;
float DA;
float gradePay;
float otherAllowances;
};
// Function to calculate total salary
float calculateSalary(struct Employee emp) {
// Salary calculation formula
float totalSalary = emp.basicPay + emp.TA + emp.DA + emp.gradePay + emp.otherAllowances;
return totalSalary;
}
int main() {
struct Employee emp;
// Input employee details
printf("Enter employee name: ");
scanf("%[^\n]s", emp.name);
printf("Enter basic pay: ");
scanf("%f", &emp.basicPay);
printf("Enter travel allowance (TA): ");
scanf("%f", &emp.TA);
printf("Enter dearness allowance (DA): ");
scanf("%f", &emp.DA);
printf("Enter grade pay: ");
scanf("%f", &emp.gradePay);
printf("Enter other allowances: ");
scanf("%f", &emp.otherAllowances);
// Calculate and display total salary
float totalSalary = calculateSalary(emp);
printf("\n%s's total salary is: $%.2f\n", emp.name, totalSalary);
return 0;
}
This program prompts the user to input the employee's details such as name, basic pay, travel allowance, dearness allowance, grade pay, and other allowances. Then, it calculates the total salary using the provided formula and displays it.
(c) What is an operator ? List and explain
various categories of operators in C.
In C programming, an operator is a symbol that performs an operation on one or more operands to produce a result. Operators are crucial for manipulating data in expressions and statements. They can be categorized into several groups based on their functionality and the number of operands they operate on:
1. **Arithmetic Operators:**
- Arithmetic operators perform mathematical operations such as addition, subtraction, multiplication, division, and modulus.
- Examples:
+ (addition)
- (subtraction)
* (multiplication)
/ (division)
% (modulus)
2. **Relational Operators:**
- Relational operators are used to compare values. They return a boolean value (`true` or `false`) based on the relationship between the operands.
- Examples:
== (equal to)
!= (not equal to)
> (greater than)
< (less than)
>= (greater than or equal to)
<= (less than or equal to)
3. **Logical Operators:**
Logical operators are used to perform logical operations such as AND, OR, and NOT.
Examples:
&& (logical AND)
|| (logical OR)
! (logical NOT)
4. **Assignment Operators:**
- Assignment operators are used to assign values to variables.
- Examples:
- = (assignment)
- += (addition assignment)
- -= (subtraction assignment)
- *= (multiplication assignment)
- /= (division assignment)
- %=(modulus assignment)
5. **Increment and Decrement Operators:**
- These operators are used to increment or decrement the value of a variable by one.
- Examples:
- `++` (increment)
- `--` (decrement)
6. **Bitwise Operators:**
- Bitwise operators perform operations at the bit level.
- Examples:
- `&` (bitwise AND)
- `|` (bitwise OR)
- `^` (bitwise XOR)
- `~` (bitwise NOT)
- `<<` (left shift)
- `>>` (right shift)
7. **Conditional Operator (Ternary Operator):**
- It is a ternary operator, taking three operands. It evaluates a condition and returns one of two values based on whether the condition is true or false.
- Syntax: `condition ? value_if_true : value_if_false`
These are the primary categories of operators in C, each serving a specific purpose in manipulating data and controlling program flow. Understanding and mastering their usage is essential for writing efficient and expressive C code
3. (a) Explain the following variables with an example for each :
(i) Automatic
(ii) Extern
(iii) Static
(iv) Register
Sure, let's go through each of these variables with examples:
(i) Automatic:
- Automatic variables are those that are declared within a block of code, and their memory is automatically allocated when the block is entered and deallocated when the block is exited. They are typically local to a function and are created anew each time the function is called.
- Example:
#include <stdio.h>
void function() {
int x = 10; // Automatic variable
printf("The value of x is: %d\n", x);
}
int main() {
function();
return 0;
}
In this example, the variable `x` is declared inside the `function()` block. It is automatically allocated when the function is called and deallocated when the function exits.
(ii) Extern:
- Extern variables are declared outside of any function and can be accessed by multiple source files in a program. They are typically used when a variable needs to be shared among multiple files.
- Example:
File: file1.c
int count; // Extern variable declaration
File: file2.c
#include <stdio.h>
extern int count; // Extern variable declaration
int main() {
count = 10; // Accessing the extern variable
printf("The value of count is: %d\n", count);
return 0;
}
In this example, the variable `count` is declared as `extern` in both `file1.c` and `file2.c`, allowing them to share the same variable.
(iii) Static:
- Static variables in C retain their values between function calls and have a scope limited to the function or block in which they are declared. They are initialized only once before the program starts execution.
- Example:
#include <stdio.h>
void function() {
static int x = 0; // Static variable
x++;
printf("The value of x is: %d\n", x);
}
int main() {
function();
function();
function();
return 0;
}
In this example, the variable `x` is declared as `static` inside the `function()` block. It retains its value between function calls and is initialized only once.
(iv) Register:
- Register variables are similar to automatic variables but are stored in the CPU registers for faster access. However, the compiler may or may not allocate a register for these variables, depending on the optimization level and the availability of registers.
- Example:
#include <stdio.h>
int main() {
register int i; // Register variable
for (i = 0; i < 10; i++) {
printf("The value of i is: %d\n", i);
}
return 0;
}
In this example, the variable `i` is declared as a `register` variable. The compiler may choose to allocate a CPU register for it, enhancing the efficiency of the loop. However, the use of `register` keyword is more of a hint to the compiler rather than a strict command, and the compiler may choose to ignore it.
(b) Write a program in C to award grade to the students depending on the marks :
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‟
Here's a simple C program that accomplishes the task:
#include <stdio.h>
int main() {
int marks;
printf("Enter the marks: ");
scanf("%d", &marks);
char grade;
if (marks > 75) {
grade = 'A';
} else if (marks >= 60 && marks <= 75) {
grade = 'B';
} else if (marks >= 50 && marks < 60) {
grade = 'C';
} else if (marks >= 40 && marks < 50) {
grade = 'D';
} else {
grade = 'E';
}
printf("Grade: %c\n", grade);
return 0;
}
This program prompts the user to enter the marks, then it checks the entered marks against the defined ranges and assigns the appropriate grade accordingly. Finally, it prints the grade assigned to the student.
4.(a) Check a string for palindrome using library functions.
You can check if a string is a palindrome in C using library functions by comparing the string with its reverse. Here's a short example:
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
printf("Enter a string: ");
scanf("%s", str);
int len = strlen(str);
int isPalindrome = 1; // Assume it's a palindrome by default
for (int i = 0; i < len / 2; i++) {
if (str[i] != str[len - i - 1]) {
isPalindrome = 0;
break;
}
}
if (isPalindrome)
printf("%s is a palindrome.\n", str);
else
printf("%s is not a palindrome.\n", str);
return 0;
}
This code reads a string from the user, then iterates through the string to compare characters from the beginning and end. If any pair of characters doesn't match, it concludes that the string is not a palindrome.
(b) Describe file handling in C. Explain
various functions like fopen (), fclose () and
fseek ().
In C, file handling involves manipulating files on the system, including tasks like opening, reading from, writing to, and closing files. Here's a brief explanation of the key file handling functions:
1. **`fopen()`:** This function is used to open a file. It takes two parameters: the file path and the mode in which the file is to be opened (like read, write, append, etc.). It returns a pointer to a FILE object, which is used for subsequent file operations.
2. **`fclose()`:** This function is used to close a file that was opened using `fopen()`. It takes a FILE pointer as its parameter and closes the associated file.
3. **`fseek()`:** This function is used to move the file pointer to a specified location within the file. It takes three parameters: the FILE pointer, the offset (number of bytes to move), and the origin (starting position for the offset, such as the beginning, current position, or end of file).
Here's a simple example demonstrating these functions:
#include <stdio.h>
int main() {
FILE *fp;
char ch;
// Open file in read mode
fp = fopen("example.txt", "r");
// Check if file opened successfully
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
// Read and print each character in the file
while ((ch = fgetc(fp)) != EOF) {
printf("%c", ch);
}
// Close the file
fclose(fp);
return 0;
}
In this example, fopen() is used to open the file "example.txt" in read mode, fgetc() is used to read each character from the file until the end of file (EOF) is reached, and `fclose()` is used to close the file once reading is complete.
(c) Define an array. How are arrays declared
and initialised ? Write a C code segment to
explain it.
In C programming, an array is a collection of elements of the same type, stored in contiguous memory locations. Each element in an array is accessed by its index.
Arrays in C are declared with a specific type and size. The syntax for declaring an array is:
type arrayName[arraySize];
Here, `type` specifies the data type of the elements in the array, `arrayName` is the identifier for the array, and `arraySize` is the number of elements in the array.
Arrays can be initialized at the time of declaration or later using assignment statements.
Here's an example C code segment demonstrating the declaration and initialization of an array:
#include <stdio.h>
int main() {
// Declaration and initialization of an array of integers
int numbers[5] = {1, 2, 3, 4, 5};
// Accessing and printing array elements
printf("Array elements:\n");
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
return 0;
}
In this code:
- We declare an array of integers named `numbers` with a size of 5.
- We initialize the array with values `{1, 2, 3, 4, 5}` at the time of declaration.
- We use a loop to iterate over the elements of the array and print them out.
Output:
Array elements:
1 2 3 4 5
This code demonstrates how to declare, initialize, and access elements of an array in C.
5. Differentiate the following : 5×4=20
(i) Function vs. Macro
(ii) Structure vs. Union
(iii) Call by value vs. Call by reference
(iv) Break statement vs. Continue statement
Here are the differentiations for each pair:
(i) Function vs. Macro:
- **Function**: A function is a block of reusable code that performs a specific task. It can accept parameters and return a value. Functions are executed when they are called.
- **Macro**: A macro is a fragment of code which has been given a name. Whenever the name is used, it is replaced by the contents of the macro. Macros are expanded by the preprocessor before compilation, and they lack type-checking.
(ii) Structure vs. Union:
- **Structure**: A structure is a user-defined data type in C/C++ that allows grouping of items of possibly different types into a single unit. Each item within a structure is called a member.
- **Union**: A union is also a user-defined data type that allows storing different data types in the same memory location. However, only one member of the union can contain a value at any given time. This means that the memory allocated for a union will be large enough to hold the largest member.
(iii) Call by value vs. Call by reference:
- **Call by value**: In call by value, a copy of the actual parameter is passed to the function. Any changes made to the parameter within the function do not affect the original value.
- **Call by reference**: In call by reference, a reference to the actual parameter is passed to the function. This means that changes made to the parameter within the function will affect the original value.
(iv) Break statement vs. Continue statement:
- **Break statement**: The break statement is used to terminate the loop or switch statement and transfer control to the statement immediately following the 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 rather jumps to the next iteration.
Comments
Post a Comment