MCS-011 Problem Solving and Programming Solve Question paper Dec-2023 Term-End Exam.
Q1.(a) Write an algorithm and draw a corresponding flow chart to check whether the number is prime or not .
Answer: Algorithm to Check if a Number is Prime
- Start
- Input: Read an integer
n
. - Initialize: Set
is_prime = true
. - Check Special Cases:
- If
n <= 1
, setis_prime = false
and go to step 8.
- If
- Loop Through Divisors:
- For
i = 2
tosqrt(n)
:- If
n % i == 0
, setis_prime = false
and exit the loop.
- If
- For
- End of Loop:
- If
is_prime
is stilltrue
,n
is a prime number. - Otherwise,
n
is not a prime number.
- If
- Output Result: Display whether
n
is a prime number or not. - Stop
Flowchart Description
- Start: Begin the process.
- Input
n
: Accept the number to check. - Check if
n <= 1
:- If true, print “Not Prime” and end.
- If false, continue.
- Initialize Loop: Set
i = 2
. - Condition
i <= sqrt(n)
:- If false, print “Prime” and end.
- If true, proceed.
- Check Divisibility:
- If
n % i == 0
, print “Not Prime” and end. - If not, increment
i
by 1 and repeat step 5.
- If
- End Loop: If the loop completes without finding a divisor, print “Prime”.
- Stop: End the process.
Flowchart
Here’s a textual flowchart representation:
Start
|
Input n
|
n <= 1? ----> Yes ----> Output "Not Prime" --> Stop
| No
|
Initialize i = 2
|
i <= sqrt(n)? -----> No -----> Output "Prime" --> Stop
| Yes
|
n % i == 0? -----> Yes -----> Output "Not Prime" --> Stop
| No
|
Increment i, repeat from "i <= sqrt(n)?"
Q1 (b) Write a program in C to find the sum of digits of a 5-digit number.
Answer: Here’s a C program to calculate the sum of the digits of a 5-digit number:
#include <stdio.h>
int main() {
int number, sum = 0, digit;
// Input a 5-digit number
printf("Enter a 5-digit number: ");
scanf("%d", &number);
// Validate input
if (number < 10000 || number > 99999) {
printf("Invalid input! Please enter a 5-digit number.\n");
return 1; // Exit the program with an error code
}
// Calculate the sum of the digits
while (number > 0) {
digit = number % 10; // Extract the last digit
sum += digit; // Add it to the sum
number /= 10; // Remove the last digit
}
// Output the result
printf("The sum of the digits is: %d\n", sum);
return 0;
}
Sample Output:
Case 1:
Enter a 5-digit number: 12345
The sum of the digits is: 15
Case 2:
Enter a 5-digit number: 54321
The sum of the digits is: 15
Q1. (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
Answer: Here is the C program to generate the specified pattern:
#include <stdio.h>
int main() {
int i, j, n = 5; // n is the number of rows
// Generate the pattern
for (i = 1; i <= n; i++) { // Loop through rows
for (j = 1; j <= i; j++) { // Loop to print numbers in each row
printf("%d ", i);
}
printf("\n"); // Move to the next line after each row
}
return 0;
}
Explanation:
- Outer Loop (
for i
):- Controls the rows.
- Runs from
i = 1
toi = n
, wheren
is the number of rows (5 in this case).
- Inner Loop (
for j
):- Controls the number of elements printed in each row.
- For row
i
, it printsi
exactlyi
times.
- Printing:
- For each iteration of the inner loop, the current row number
i
is printed, followed by a space. - At the end of each row, a newline character (
\n
) is printed to start a new row.
- For each iteration of the inner loop, the current row number
Output:
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
Q1 (d) Write a C function to find the square of an integer.
Answer: Here is a C function to calculate the square of an integer:
#include <stdio.h>
// Function to find the square of an integer
int square(int num) {
return num * num;
}
int main() {
int number, result;
// Input an integer
printf("Enter an integer: ");
scanf("%d", &number);
// Call the function to calculate the square
result = square(number);
// Display the result
printf("The square of %d is %d.\n", number, result);
return 0;
}
Explanation:
- Function Definition:
- The
square
function takes an integer (num
) as its parameter and returns its square by multiplying the number with itself.
- The
- Main Function:
- The user is prompted to enter an integer.
- The
square
function is called with the user-inputted number as the argument. - The result is displayed.
Sample Output:
Enter an integer: 5
The square of 5 is 25.
Q1 (e) Explain the use of pointers and its characteristics.
Answer: Pointers in C
Pointers are a fundamental concept in the C programming language, providing powerful capabilities for memory access and manipulation. A pointer is a variable that stores the memory address of another variable.
Uses of Pointers
- Dynamic Memory Allocation:
- Pointers are essential for working with dynamically allocated memory using functions like
malloc
,calloc
, andfree
.
- Pointers are essential for working with dynamically allocated memory using functions like
- Efficient Function Argument Passing:
- Passing pointers to functions allows direct access to variables’ memory addresses, enabling efficient modification of data without copying it.
- Array and String Manipulation:
- Pointers provide a convenient way to traverse arrays and manipulate strings.
- Data Structures:
- Pointers are used to create and manipulate complex data structures like linked lists, trees, and graphs.
- Function Pointers:
- Pointers can store the address of functions, enabling dynamic invocation and callback mechanisms.
- Accessing Hardware:
- In low-level programming, pointers allow direct access to memory-mapped hardware registers.
Characteristics of Pointers
- Storage of Address:
- A pointer stores the memory address of another variable, allowing indirect access to the variable’s value.
- Dereferencing:
- The value stored at the memory address pointed to by the pointer can be accessed using the dereference operator (
*
).
- The value stored at the memory address pointed to by the pointer can be accessed using the dereference operator (
- Pointer Arithmetic:
- Pointers support arithmetic operations, such as increment (
++
) and decrement (--
), which move the pointer to the next or previous memory location (useful in arrays).
- Pointers support arithmetic operations, such as increment (
- Type Sensitivity:
- Pointers are strongly typed, meaning a pointer to an
int
is different from a pointer to afloat
.
- Pointers are strongly typed, meaning a pointer to an
- Null Pointer:
- A pointer can be assigned a
NULL
value to indicate that it is not pointing to any valid memory location.
- A pointer can be assigned a
- Pointer to Pointer:
- C allows pointers to point to other pointers, enabling the creation of multi-level indirection.
- Void Pointers:
- A
void
pointer (void *
) can point to any data type, providing generic pointer functionality.
- A
- Memory Management:
- Pointers allow direct manipulation of memory, but incorrect usage (e.g., dereferencing uninitialized pointers) can lead to undefined behavior or crashes.
Example: Basic Pointer Usage
#include <stdio.h>
int main() {
int x = 10;
int *ptr = &x; // Pointer to x
printf("Value of x: %d\n", x);
printf("Address of x: %p\n", &x);
printf("Value stored in ptr (address of x): %p\n", ptr);
printf("Value pointed to by ptr: %d\n", *ptr);
return 0;
}
Output:
Value of x: 10
Address of x: 0x7ffeea12abc8
Value stored in ptr (address of x): 0x7ffeea12abc8
Value pointed to by ptr: 10
Advantages of Pointers
- Enables dynamic memory allocation.
- Allows efficient passing of large data structures to functions.
- Facilitates advanced programming constructs like linked lists and trees.
Disadvantages of Pointers
- Risk of memory leaks if dynamically allocated memory is not freed.
- Can cause undefined behavior if uninitialized or invalid pointers are used.
- Increased complexity and potential for bugs like segmentation faults.
Pointers are powerful but require careful handling to ensure program stability and correctness.
Q1 (f) Describe the conditional statements “Multiple-if” and “nested-if” with one example for each.
Answer: Conditional Statements:
- Multiple-if Statement:
- The
multiple-if
statement is used to evaluate multiple independent conditions. - Each condition is evaluated independently, and corresponding actions are executed if the condition is true.
- The
Example: Multiple-if
#include <stdio.h>
int main() {
int age;
printf("Enter your age: ");
scanf("%d", &age);
if (age < 18) {
printf("You are a minor.\n");
}
if (age >= 18 && age < 60) {
printf("You are an adult.\n");
}
if (age >= 60) {
printf("You are a senior citizen.\n");
}
return 0;
}
Explanation:
- Each
if
statement checks a separate condition:- If the age is below 18, it prints “You are a minor.”
- If the age is between 18 and 59, it prints “You are an adult.”
- If the age is 60 or above, it prints “You are a senior citizen.”
Output:
Enter your age: 45
You are an adult.
- Nested-if Statement:
- The
nested-if
statement involves placing oneif
statement inside another. - It is used to check dependent conditions.
- The
Example: Nested-if
#include <stdio.h>
int main() {
int marks;
printf("Enter your marks: ");
scanf("%d", &marks);
if (marks >= 50) {
printf("You passed!\n");
if (marks >= 90) {
printf("Excellent performance!\n");
} else if (marks >= 75) {
printf("Good performance!\n");
} else {
printf("Keep improving.\n");
}
} else {
printf("You failed. Try harder next time.\n");
}
return 0;
}
Explanation:
- The outer
if
checks if the marks are 50 or above (pass condition). - If the student has passed, the inner
if
checks the grade:- Marks >= 90: “Excellent performance!”
- Marks >= 75: “Good performance!”
- Otherwise: “Keep improving.”
- If marks are below 50, the student has failed.
Output:
Enter your marks: 82
You passed!
Good performance!
Key Differences:
Aspect | Multiple-if | Nested-if |
---|---|---|
Evaluation | Each condition is independent. | Conditions depend on one another. |
Use Case | For unrelated conditions. | For hierarchically related conditions. |
Complexity | Easier to read and debug. | Slightly harder to read and debug. |
Q2. (a) Explain the type of errors in C program by ngiving an example for each.
Answer: Errors in a C program can be categorized into three main types: syntax errors, runtime errors, and logical errors. Below is an explanation of each with examples.
1. Syntax Errors
- Definition: Occur when the rules of the C programming language are violated.
- Detected: During compilation.
- Effect: The program does not compile until the errors are corrected.
Example:
#include <stdio.h>
int main() {
printf("Hello, World!); // Missing closing double-quote
return 0;
}
Explanation:
- The error occurs because the closing double-quote (
"
) is missing in theprintf
statement. - Compiler Message: Expected ‘)’ before ‘;’ token.
2. Runtime Errors
- Definition: Occur while the program is running, typically due to invalid operations such as dividing by zero or accessing invalid memory.
- Detected: During execution.
- Effect: The program crashes or behaves unpredictably.
Example:
#include <stdio.h>
int main() {
int a = 10, b = 0;
int result = a / b; // Division by zero
printf("Result: %d\n", result);
return 0;
}
Explanation:
- The error occurs because dividing a number by zero is undefined.
- Runtime Behavior: The program may crash or throw an exception like Floating-point exception.
3. Logical Errors
- Definition: Occur when the program compiles and runs but produces incorrect results due to flawed logic.
- Detected: Only through testing and debugging.
- Effect: The program produces unexpected or incorrect output.
Example:
#include <stdio.h>
int main() {
int a = 5, b = 10;
int sum = a - b; // Logical error: Using subtraction instead of addition
printf("Sum: %d\n", sum);
return 0;
}
Explanation:
- The error occurs because the programmer intended to add
a
andb
but used the subtraction operator (-
) instead of the addition operator (+
). - Output:
Sum: -5
(Incorrect result).
Summary Table
Type | Cause | Detection | Effect | Example |
---|---|---|---|---|
Syntax Error | Violating language grammar rules | During compilation | Prevents program compilation | Missing semicolon or bracket |
Runtime Error | Invalid operations during runtime | During execution | Program crashes or produces exceptions | Division by zero |
Logical Error | Faulty logic in code | During testing/debugging | Program runs but produces wrong output | Incorrect calculation logic |
Each error type requires a specific debugging approach to resolve.
Q2.(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.
Answer: Here’s an interactive C program that calculates an employee’s salary based on various components like Basic Pay, TA (Travel Allowance), DA (Dearness Allowance), Grade Pay, and other allowances using structures.
Program
#include <stdio.h>
// Define a structure to hold salary components
struct SalaryComponents {
float basicPay;
float TA; // Travel Allowance
float DA; // Dearness Allowance
float gradePay;
float otherAllowances;
};
int main() {
struct SalaryComponents empSalary; // Declare a structure variable
float totalSalary;
// Input salary components from the user
printf("Enter the Basic Pay: ");
scanf("%f", &empSalary.basicPay);
printf("Enter the Travel Allowance (TA): ");
scanf("%f", &empSalary.TA);
printf("Enter the Dearness Allowance (DA): ");
scanf("%f", &empSalary.DA);
printf("Enter the Grade Pay: ");
scanf("%f", &empSalary.gradePay);
printf("Enter Other Allowances: ");
scanf("%f", &empSalary.otherAllowances);
// Calculate total salary
totalSalary = empSalary.basicPay + empSalary.TA + empSalary.DA +
empSalary.gradePay + empSalary.otherAllowances;
// Display the total salary
printf("\n---- Employee Salary Details ----\n");
printf("Basic Pay: %.2f\n", empSalary.basicPay);
printf("Travel Allowance (TA): %.2f\n", empSalary.TA);
printf("Dearness Allowance (DA): %.2f\n", empSalary.DA);
printf("Grade Pay: %.2f\n", empSalary.gradePay);
printf("Other Allowances: %.2f\n", empSalary.otherAllowances);
printf("Total Salary: %.2f\n", totalSalary);
return 0;
}
Explanation
- Structure Definition:
- The
struct SalaryComponents
is defined to group all components of the salary, making it easier to manage and access the data.
- The
- Input:
- The program prompts the user to enter the values for each salary component.
- Calculation:
- The total salary is calculated by summing all components.
- Output:
- The program displays each salary component and the total salary.
Sample Output
Case 1:
Enter the Basic Pay: 25000
Enter the Travel Allowance (TA): 2000
Enter the Dearness Allowance (DA): 3000
Enter the Grade Pay: 5000
Enter Other Allowances: 1000
---- Employee Salary Details ----
Basic Pay: 25000.00
Travel Allowance (TA): 2000.00
Dearness Allowance (DA): 3000.00
Grade Pay: 5000.00
Other Allowances: 1000.00
Total Salary: 36000.00
Key Features:
- Modular Approach: Using a structure ensures all related data is grouped together.
- Interactive Input: User can input each component dynamically.
- Readability: Clear display of each salary component and total salary.
Q2. (c) What is an operator ? List and explain various categories of operators in C.
Answer: What is an Operator?
An operator in C is a symbol or keyword used to perform specific operations on one or more operands (variables, constants, or expressions). Operators enable mathematical, logical, and other types of operations within a program.
Categories of Operators in C
1. Arithmetic Operators
- Used for mathematical calculations.
- Operate on numerical values.
Operator | Description | Example |
---|---|---|
+ | Addition | a + b |
- | Subtraction | a - b |
* | Multiplication | a * b |
/ | Division | a / b |
% | Modulus (remainder) | a % b |
2. Relational Operators
- Compare two values and return
true
(1) orfalse
(0).
Operator | Description | Example |
---|---|---|
== | Equal to | a == b |
!= | Not equal to | a != b |
> | Greater than | a > b |
< | Less than | a < b |
>= | Greater than or equal | a >= b |
<= | Less than or equal | a <= b |
3. Logical Operators
- Perform logical operations and return a boolean value.
Operator | Description | Example |
---|---|---|
&& | Logical AND | (a > 0 && b > 0) |
` | ` | |
! | Logical NOT | !(a > 0) |
4. Bitwise Operators
- Operate at the bit level.
Operator | Description | Example |
---|---|---|
& | Bitwise AND | a & b |
` | ` | Bitwise OR |
^ | Bitwise XOR | a ^ b |
~ | Bitwise Complement | ~a |
<< | Left shift | a << 2 |
>> | Right shift | a >> 2 |
5. Assignment Operators
- Assign values to variables.
Operator | Description | Example |
---|---|---|
= | Assign | a = 10 |
+= | Add and assign | a += 5 |
-= | Subtract and assign | a -= 3 |
*= | Multiply and assign | a *= 2 |
/= | Divide and assign | a /= 4 |
%= | Modulus and assign | a %= 3 |
6. Unary Operators
- Operate on a single operand.
Operator | Description | Example |
---|---|---|
+ | Unary plus | +a |
- | Unary minus | -a |
++ | Increment | ++a or a++ |
-- | Decrement | --a or a-- |
! | Logical NOT | !a |
7. Conditional/Ternary Operator
- A compact form of the
if-else
statement. - Syntax:
condition ? value_if_true : value_if_false;
Example:
int a = 10, b = 20;
int max = (a > b) ? a : b; // Assigns the larger value to max
8. Special Operators
- Includes
sizeof
, comma,
, and pointer operators.
Operator | Description | Example |
---|---|---|
sizeof | Returns size of a variable | sizeof(int) |
, | Separates expressions | a = (b = 2, b + 3) |
& | Address-of | &a |
* | Dereference | *ptr |
9. Other Operators
- Type Cast Operator: Converts one data type into another.
- Example:
(float)a
- Example:
- Member Access Operators:
.
: Access structure members.->
: Access members through a pointer to a structure.
Example Program
#include <stdio.h>
int main() {
int a = 10, b = 20, result;
float c = 5.5;
// Arithmetic Operator
result = a + b;
printf("Addition: %d\n", result);
// Relational Operator
if (a > b) {
printf("a is greater than b\n");
} else {
printf("b is greater than a\n");
}
// Logical Operator
if (a > 0 && b > 0) {
printf("Both a and b are positive numbers.\n");
}
// Sizeof Operator
printf("Size of int: %lu bytes\n", sizeof(a));
return 0;
}
Output
Addition: 30
b is greater than a
Both a and b are positive numbers.
Size of int: 4 bytes
Understanding these categories helps write efficient and error-free C programs.
Q3. (a) Explain the following variables with an example for each :
(i) Automatic
(ii) Extern
(iii) Static
(iv) Register
Answer: Types of Variables in C
1. Automatic Variables
- Definition:
- These are the default variables declared inside a function or block. They are stored in the stack memory and have local scope.
- Automatically created when the function is called and destroyed when it exits.
- Characteristics:
- Scope: Local to the block where it is defined.
- Default Value: Garbage value.
- Storage Class:
auto
(optional keyword, rarely used).
Example:
#include <stdio.h>
void demo() {
auto int x = 10; // Automatic variable (keyword auto is optional)
printf("Automatic variable x = %d\n", x);
}
int main() {
demo();
return 0;
}
Output:
Automatic variable x = 10
2. External (Extern) Variables
- Definition:
- Variables declared outside all functions and accessible globally across multiple files.
- The
extern
keyword is used to declare the variable in a file where it is not defined.
- Characteristics:
- Scope: Global.
- Lifetime: Throughout the program execution.
- Storage: Stored in the data segment.
Example:
// File1.c
#include <stdio.h>
extern int num; // Declared but defined elsewhere
void printNum() {
printf("Extern variable num = %d\n", num);
}
// File2.c
#include <stdio.h>
int num = 100; // Defined here
int main() {
printNum(); // Use extern variable from File1.c
return 0;
}
Output:
Extern variable num = 100
3. Static Variables
- Definition:
- Variables that retain their value between function calls.
- They are initialized only once and stored in the data segment.
- Characteristics:
- Scope: Local to the function or block.
- Lifetime: Entire program execution.
- Default Value: Zero.
Example:
#include <stdio.h>
void demo() {
static int count = 0; // Static variable
count++;
printf("Static variable count = %d\n", count);
}
int main() {
demo();
demo();
demo();
return 0;
}
Output:
Static variable count = 1
Static variable count = 2
Static variable count = 3
4. Register Variables
- Definition:
- Variables stored in the CPU registers instead of RAM for faster access.
- Used for frequently accessed variables.
- Characteristics:
- Scope: Local to the function.
- Lifetime: Limited to the block in which they are defined.
- Storage: CPU register (if available, otherwise RAM).
- Cannot use the
&
operator to get the address of a register variable.
Example:
#include <stdio.h>
void demo() {
register int i; // Register variable
for (i = 0; i < 5; i++) {
printf("Register variable i = %d\n", i);
}
}
int main() {
demo();
return 0;
}
Output:
Register variable i = 0
Register variable i = 1
Register variable i = 2
Register variable i = 3
Register variable i = 4
Summary Table
Type | Keyword | Scope | Lifetime | Default Value | Storage |
---|---|---|---|---|---|
Automatic | auto | Local to block | Function call only | Garbage value | Stack memory |
Extern | extern | Global | Entire program | Zero | Data segment |
Static | static | Local to block | Entire program | Zero | Data segment |
Register | register | Local to block | Function call only | Undefined | CPU register |
Q3. (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‟
Answer: Here’s a C program to award grades to students based on their marks:
#include <stdio.h>
int main() {
int marks;
char grade;
// Input student marks
printf("Enter the marks of the student: ");
scanf("%d", &marks);
// Determine the grade based on marks
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';
}
// Output the grade
printf("The grade for marks %d is: %c\n", marks, grade);
return 0;
}
Explanation of the Program
- The program takes the student’s marks as input using
scanf
. - It uses a series of
if-else if
statements to check the range of marks and assign the corresponding grade:- Marks greater than 75: Grade
A
- Marks between 60 and 75 (inclusive): Grade
B
- Marks between 50 and 60: Grade
C
- Marks between 40 and 50: Grade
D
- Marks less than 40: Grade
E
- Marks greater than 75: Grade
- The final grade is printed as output.
Sample Run
Input:
Enter the marks of the student: 68
Output:
The grade for marks 68 is: B
Q4. (a) Check a string for palindrome using library functions.
Answer: Here’s a C program to check if a string is a palindrome using library functions:
#include <stdio.h>
#include <string.h>
int main() {
char str[100], reversed[100];
// Input the string
printf("Enter a string: ");
scanf("%s", str);
// Copy the original string and reverse it
strcpy(reversed, str); // Copy str to reversed
strrev(reversed); // Reverse the string using strrev (string.h)
// Compare the original and reversed strings
if (strcmp(str, reversed) == 0) {
printf("The string \"%s\" is a palindrome.\n", str);
} else {
printf("The string \"%s\" is not a palindrome.\n", str);
}
return 0;
}
Explanation of the Program
- The program uses
string.h
library functions:strcpy
: Copies the original string to a new string for manipulation.strrev
: Reverses the copied string.strcmp
: Compares the original string with the reversed string.
- If the original string matches the reversed string, it is a palindrome.
Sample Run
Input:
Enter a string: madam
Output:
The string "madam" is a palindrome.
Input:
Enter a string: hello
Output:
The string "hello" is not a palindrome.
Note:
The strrev()
function is not part of the standard C library, but it is supported in many compilers (like Turbo C). If strrev()
is not available, you can manually reverse the string by writing a helper function.
Q4. (b) Describe file handling in C. Explain various functions like fopen (), fclose () and fseek ().
Answer: File Handling in C
File handling in C is a mechanism to store data permanently on a disk through file operations. Files can be used for reading, writing, and updating data. File handling is performed using standard I/O functions provided by the stdio.h
library.
File Handling Modes
The fopen()
function uses the following modes to open a file:
Mode | Description |
---|---|
r | Opens a file for reading. The file must exist. |
w | Opens a file for writing. Creates a new file if it doesn’t exist; overwrites it if it does. |
a | Opens a file for appending. Data is written at the end of the file. |
r+ | Opens a file for reading and writing. The file must exist. |
w+ | Opens a file for reading and writing. Creates a new file if it doesn’t exist. |
a+ | Opens a file for reading and appending. |
File Handling Functions
1. fopen()
- Purpose: Opens a file in the specified mode and returns a pointer to the
FILE
structure. - Syntax:
FILE *fopen(const char *filename, const char *mode);
- Parameters:
filename
: Name of the file to open.mode
: Mode in which the file is to be opened (e.g.,"r"
,"w"
).
- Example:
FILE *file = fopen("example.txt", "w"); if (file == NULL) { printf("Error opening file.\n"); } else { printf("File opened successfully.\n"); }
2. fclose()
- Purpose: Closes an open file to free system resources.
- Syntax:
int fclose(FILE *file);
- Parameters:
file
: Pointer to the file to close.
- Example:
fclose(file); // Closes the file opened by fopen
3. fseek()
- Purpose: Moves the file pointer to a specific position within the file.
- Syntax:
int fseek(FILE *file, long offset, int origin);
- Parameters:
file
: Pointer to the file.offset
: Number of bytes to move the pointer.origin
: Reference position (SEEK_SET
,SEEK_CUR
,SEEK_END
).SEEK_SET
: Beginning of the file.SEEK_CUR
: Current position in the file.SEEK_END
: End of the file.
- Example:
fseek(file, 0, SEEK_END); // Move to the end of the file
Example Program: Writing and Reading a File
#include <stdio.h>
int main() {
FILE *file;
char data[100];
// Open the file in write mode
file = fopen("example.txt", "w");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
// Write data to the file
fprintf(file, "Hello, File Handling in C!\n");
fclose(file); // Close the file after writing
// Open the file in read mode
file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
// Read data from the file
while (fgets(data, sizeof(data), file) != NULL) {
printf("Read from file: %s", data);
}
fclose(file); // Close the file after reading
return 0;
}
Output
Read from file: Hello, File Handling in C!
Summary
Function | Purpose |
---|---|
fopen | Opens a file in the specified mode and returns a pointer to the file. |
fclose | Closes an open file and releases associated resources. |
fseek | Moves the file pointer to a specific position in the file. |
These functions form the foundation of file handling in C.
Q4. (c) Define an array. How are arrays declared and initialised ? Write a C code segment to explain it.
Answer: Definition of an Array
An array is a collection of elements of the same data type, stored in contiguous memory locations. Arrays allow efficient access and manipulation of elements using an index.
Declaration of Arrays
To declare an array, specify the data type, array name, and size.
Syntax:
data_type array_name[size];
data_type
: Type of data stored (e.g.,int
,float
,char
).array_name
: Name of the array.size
: Number of elements the array can hold.
Example:
int numbers[5]; // Declares an array of 5 integers
Initialization of Arrays
An array can be initialized during declaration or later.
1. During Declaration
Syntax:
data_type array_name[size] = {value1, value2, ..., valueN};
- The size can be omitted when values are provided.
Example:
int numbers[5] = {10, 20, 30, 40, 50}; // Declares and initializes
char vowels[] = {'a', 'e', 'i', 'o', 'u'}; // Size omitted
2. After Declaration
Values can be assigned individually:
numbers[0] = 10;
numbers[1] = 20; // and so on
C Code Segment to Demonstrate Declaration and Initialization
#include <stdio.h>
int main() {
// Declaration and initialization
int numbers[5] = {10, 20, 30, 40, 50};
// Access and modify array elements
printf("Original array elements:\n");
for (int i = 0; i < 5; i++) {
printf("numbers[%d] = %d\n", i, numbers[i]);
}
// Modifying an element
numbers[2] = 100;
printf("\nArray elements after modification:\n");
for (int i = 0; i < 5; i++) {
printf("numbers[%d] = %d\n", i, numbers[i]);
}
return 0;
}
Explanation of the Code
- Declaration and Initialization:
- The array
numbers
is initialized with values{10, 20, 30, 40, 50}
.
- The array
- Accessing Array Elements:
- A loop prints the elements using the index.
- Modifying an Element:
- The value at
index 2
is updated to100
.
- The value at
- Reprinting the Modified Array:
- The updated array is displayed.
Output
Original array elements:
numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
numbers[3] = 40
numbers[4] = 50
Array elements after modification:
numbers[0] = 10
numbers[1] = 20
numbers[2] = 100
numbers[3] = 40
numbers[4] = 50
Arrays are powerful structures used in various programming applications, including data manipulation, sorting, and searching algorithms.
Q5. Differentiate the following :
(i) Function vs. Macro
(ii) Structure vs. Union
(iii) Call by value vs. Call by reference
(iv) Break statement vs. Continue statement
Answer: Here’s a detailed differentiation for each pair:
(i) Function vs. Macro
Function | Macro |
---|---|
A function is a block of code that performs a specific task and is executed when called. | A macro is a preprocessor directive that defines a code snippet to be replaced by the preprocessor before compilation. |
Functions are executed at runtime. | Macros are expanded at compile-time. |
Functions may have a return type and can accept parameters. | Macros do not have a return type and can be parameterized. |
Functions are more memory-efficient as they only exist in memory once during execution. | Macros may consume more memory because they are replaced inline. |
Example: | Example: |
“`c | “`c |
int square(int x) { | #define SQUARE(x) ((x)*(x)) |
return x * x; | “` |
} | |
“` | |
Function calls involve stack operations, such as pushing arguments and return addresses. | Macros do not involve function calls or stack operations. |
Example usage: | Example usage: |
“`c | “`c |
int result = square(5); | int result = SQUARE(5); |
“` |
(ii) Structure vs. Union
Structure | Union |
---|---|
A structure is a user-defined data type that allows grouping of different data types. | A union is a user-defined data type that allows grouping of different data types, but only one member can store a value at a time. |
In structures, each member has its own memory location. | In unions, all members share the same memory location. |
The size of a structure is the sum of the sizes of its members. | The size of a union is the size of its largest member. |
Example: | Example: |
“`c | “`c |
struct Person { | union Data { |
char name[50]; | int i; |
int age; | float f; |
}; | char c; |
“` | }; |
In structures, memory is allocated for all members. | In unions, memory is allocated only for the largest member. |
(iii) Call by Value vs. Call by Reference
Call by Value | Call by Reference |
---|---|
In call by value, the actual value of the argument is passed to the function. | In call by reference, the address of the argument is passed to the function. |
Changes made to the parameter inside the function do not affect the actual argument. | Changes made to the parameter inside the function directly affect the actual argument. |
It is safer as the original value is not modified by the function. | It is more efficient for large data structures as no copying of data is required. |
Example: | Example: |
“`c | “`c |
void increment(int a) { | void increment(int *a) { |
a = a + 1; | *a = *a + 1; |
} | } |
“` | |
“`c | “`c |
int main() { | int main() { |
int x = 5; | int x = 5; |
increment(x); | increment(&x); |
} | } |
“` |
(iv) Break Statement vs. Continue Statement
Break Statement | Continue Statement |
---|---|
The break statement is used to exit from a loop (for, while, do-while) or a switch statement. | The continue statement is used to skip the current iteration of a loop and move to the next iteration. |
After a break statement, the program execution continues after the loop or switch block. | After a continue statement, the program skips the remaining statements in the loop and moves to the next iteration of the loop. |
The break statement is used when you need to terminate a loop or a case in a switch early. | The continue statement is used when you want to skip the current iteration based on a condition and continue with the next iteration. |
Example: | Example: |
“`c | “`c |
for (int i = 0; i < 5; i++) { | for (int i = 0; i < 5; i++) { |
if (i == 3) | if (i == 3) |
break; | continue; |
printf(“%d “, i); | printf(“%d “, i); |
} | } |
“` | “` |
In the first example, the loop stops when i is 3. | In the second example, when i is 3, it skips printing 3 and continues with the next iteration. |
MCS-011 June-2024 Solve Question Paper Click here
Latest Posts:
- MCS-011 DEC-2023 Solve Question Paper FOR BCA/MCA
- ECO-01 Solve Assignment For January 2025 Session
- BCS062: E-Commerce December 2023 Solve Question Paper
- IGNOU December 2024 Exam Admit Card Released: Here’s What You Need to Know
- Admission Open for Ph.D. Programmes (Regular Mode) for July 2024 Session at IGNOU
- IGNOU Extends Assignment Submission Deadline for December 2024 Term-End Exams: Submit by November 30, 2024
- IGNOU Extends Last Date for Exam Form Submission: New Deadline is November 3, 2023
- MCS-011 JUNE-2024 Solve Question Paper FOR BCA/MCA
- BEVAE-181 DEC-2023 Solve Question Paper ignou assignment
- BCA BCS-011 TEE -JUNE 2023 Solve Question Paper
- IGNOU Extends Last Date for Fresh Admission July 2024 Cycle till 15th October 2024
- IGNOU December 2024 TEE Date Sheet Released: Exam Dates and Important Details