0% found this document useful (0 votes)
31 views52 pages

231CSC201T-Programming in C-CAT II QB With Answers

The document outlines the Continuous Assessment Test II for first-year students in various computer science programs, focusing on C programming concepts. It includes objectives related to functions, pointers, structures, and unions, along with specific questions and programming tasks to assess students' understanding. The content is structured into parts, covering definitions, programming examples, and theoretical questions to evaluate knowledge and application skills in C programming.

Uploaded by

maglevrs3m
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)
31 views52 pages

231CSC201T-Programming in C-CAT II QB With Answers

The document outlines the Continuous Assessment Test II for first-year students in various computer science programs, focusing on C programming concepts. It includes objectives related to functions, pointers, structures, and unions, along with specific questions and programming tasks to assess students' understanding. The content is structured into parts, covering definitions, programming examples, and theoretical questions to evaluate knowledge and application skills in C programming.

Uploaded by

maglevrs3m
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/ 52

CONTINUOUS ASSESSMENT TEST – II

Regulations R 2023

First Year / Second Semester (Common to CSE,IT,AIDS,CSE(AIML),CSBS,CSD,CSE(CS)


231CSC201T – PROGRAMMING IN C

CO1: Execute simple programs using basic C programming concepts.


CO2: Apply arrays and strings for simple application development.
CO3: Solve complex problems using functions and pointers.
CO4: Organize heterogeneous data with structures and unions.
CO5:Select suitable file access techniques for data processing.

Unit – III FUNCTIONS AND POINTERS

CO‟s Bloom‟s
Q.No Questions
Level
PART A
How will you define enumerated data type?
An enumerated data type(orenum) in C is a user-defined data type
1. that consists of a set of named integer constants. It allows you to CO3 K2
define a variable that can hold a set of predefined values, making the
code more readable and easier to maintain.
What is a pointer?
2. A Pointer in C language is a variable which holds the address of CO3 K1
another variable of same data type.
Write the features of a pointer
1. Pointers are more efficient in handling Arrays and Structures.
2. Pointers allow references to function and thereby helps in passing
3. of function as arguments to other functions. CO3 K1
3. It reduces length of the program and its execution time as well.
4. It allows C language to support Dynamic Memory management.

What is the difference between Array and Pointer?

4.
CO3 K2

Write a C program to swap two numbers using call by address


5.
Instead of passing the value of variable, address or reference is CO3 K1
passed and the function operate on address of the variable
rather than value.
Here formal argument is alter to the actual argument, it means
formal arguments calls the actual arguments
Mentiontheadvantage ofpassbyreference.
1. Efficiency.
6. 2. Modifying the actual argument. CO3 K1
3. Improved memory usage
4. Multiple Return values
Point out the error in the program
#include<stdio.h>
int main()
{
int a=10;
void f( );
a = f( );
printf("%d\n", a); return 0;
7. } CO3 K2
void f( )
{
printf("a");
}
The function f() is declared with a void return type, meaning it does
not return any value. However, in the statement a = f();, the result of
f() is assigned to the variable a, which is not valid since f() does not
return anything

CO‟s Bloom‟s
Q.No Questions
Level
Part – B
Create a C program that swaps two numbers by using pointers
to pass the numbers to a function.
#include <stdio.h>
int main()
{
int x, y, *a, *b, temp;
printf("Enter the value of x and y\n");
scanf("%d%d", &x, &y);
1. printf("Before Swapping\nx = %d\ny = %d\n", x, y); CO3 K4
a = &x;
b = &y;
temp = *b;
*b = *a;
*a = temp;
printf("After Swapping\nx = %d\ny = %d\n", x, y);
return 0;
}
Output
Enter the value of x and y
10
20
Before Swapping
x = 10
y = 20
After Swapping
x = 20
y=
Write a C program to calculate the sum of the series:1/1! + 1/2! +
1/3! + ……+ 1/n!. Use a function to compute the terms of the
series, and pass variables by pointer to handle the sum
calculation.

#include <stdio.h>

long long int factorial(int n) {


long long int fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}

2. void calculateSeries(int n, double *sum) { CO3 K5


for (int i = 1; i <= n; i++) {
*sum += 1.0 / factorial(i);
}
}

int main() {
int n;
double sum = 0.0;
printf("Enter the value of n: ");
scanf("%d", &n);
calculateSeries(n, &sum);
printf("Sum of the series: %.6f\n", sum);

return 0;
}
Enumerate the difference between call by value and call by
3. CO3 K4
reference with suitable examples.
Explain about pointers and write the use of pointers in arrays
with suitable example.
 A Pointer in C language is a variable which holds the
address of another variable ofsame data type.
 Pointers are used to access memory and manipulate the
address.
 Pointers are one of the most distinct and exciting
features of C language. It providespower and flexibility
to the language.
We can also have array of pointers. Pointers are very helpful
in handling character Array with rows of varying length.
char *name[3] = {
"Adam",
"chris",
"Deniel"
4. }; CO3 K4
char name[3][20] = {
45
"Adam",
"chris",
"Deniel
};

In the second approach memory wastage is more, hence it is


preferred to use pointer in such cases.
When we say memory wastage, it doesn't means that the strings
will start occupying less space, no, characters will take the
same space, but when we define array of characters, a
contiguous memory space is located equal to the maximum size
of the array, which is a wastage, which can be avoided if we
use pointers instead.
EXAMPLE:
#include<stdio.h>
void main()
{
int a[50],*p,i,n;
p=a;
printf(“Enter size of array:”);
scanf(“%d”,&n);
printf(“Enter elements of array:”);
for(i=0;i<n;++i)
{
scanf(“%d”,p+i);
}
for(i=0;i<n;++i)
{
printf(“%d “,*(p+i));
}
}

CO‟s Bloom‟s
Q.No Questions
Level
Part C
i) Explain pointer arithmetic with an example.
ii) Write a C program to take a string as input, reverse it using
pointers (without an extra array), and print the reversed string.
i)POINTER ARITHMETIC IN C
In C pointer holds address of a value, so there can be arithmetic
operations on the
pointer variable. Following arithmetic operations are possible
on pointer in C language:
Increment
1 CO3 K5
Decrement
Adding an integer to a pointer
Subtracting an integer from a pointer
Subtracting a pointer from another pointer
1. Incrementing Pointer in C
Incrementing a pointer is used in array because it is contiguous
memory location.
Moreover, we know the value of next location.
Increment operation depends on the data type of the pointer
variable. The formula of
incrementing pointer is given below:
new_address= current_address + i * size_of(data type)
32 bit
For 32 bit int variable, it will increment to 2 byte.
64 bit
For 64 bit int variable, it will increment to 4 byte.
Let's see the example of incrementing pointer variable on 64 bit
OS.
#include<stdio.h>
int main()
{
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p+1;
printf("After increment: Address of p variable is %u \n",p);
return 0;
}
ii)#include <stdio.h>

void reverseString(char *str) {


char *end = str;
// Move the end pointer to the last character of the string
while (*end != '\0') {
end++;
}
end--;

while (str < end) {


char temp = *str;
*str = *end;
*end = temp;
str++;
end--;
}
}

int main() {
char str[100];

printf("Enter a string: ");


fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = '\0';
reverseString(str);

printf("Reversed string: %s\n", str);


return 0;
}

UNIT IV STRUCTURES AND UNIONS

CO‟s Bloom‟s
Q.No Questions
Level
PART A
Define a structure in C.

A structure contains one or more data items of different data type in


1. which the individual elements can differ in type. A simple structure may CO4 K1
contain the integer elements, float elements and character elements etc.
The individual structure elements are called members.

Explain how a structure within a structure is declared and accessed.

The structure can be declared with the keyword struct following the
name and opening brace with data elements of different type then
closing brace with semicolon, as shown below.
Syntax:
struct structure_name
{
structure_element 1;
2. structure_element 2; CO4 K2
structure_element 3;
……………… structure_element n;
}structure_variable;

Example:
struct book
{
}b;

What is the size of an empty structure in C?

In C, the size of an empty structure is not zero, even though it has


no members. Instead, it typically takes up at least 1 byte.
3. CO4 K1
 Uniqueness in Memory: If an empty structure had a size of 0,
two different empty structure instances would have the same
memory address, which would violate the fundamental rule that
distinct objects must have unique memory addresses.
 Pointer Arithmetic: If an empty structure had 0 bytes, pointer
arithmetic (like incrementing a pointer to an empty structure)
wouldn't work correctly.
 Standard Compliance: The C standard (C99 and later) does not
define a zero-size object in memory.

What is the difference between a structure and a union?


Parameter Structure Union

A union is a user-defined
A structure is a user-
data type that allows
defined data type that
Definition storing different data types
groups different data
at the same memory
types into a single entity.
location.

The keyword struct is The keyword union is


Keyword
used to define a structure used to define a union

The size is the sum of the


The size is equal to the
sizes of all members,
4. size of the largest member, CO4 K2
Size with padding if
with possible padding.
necessary.

Each member within a


Memory allocated is
Memory structure is allocated
shared by individual
Allocation unique storage area of
members of union.
location.

No data overlap as Full data overlap as


Data
members are members shares the same
Overlap
independent. memory.

Accessing Individual member can Only one member can be


Members be accessed at a time. accessed at a time.

How to Declare a members in Structure?


After declaring the structure type, variables and members, the
member of the structure can be accessed by using the structure variable
along with the dot (.) operator.
5. CO4 K1
Example:
Struct std
{
} s;
int no;
Char name [20]; int marks;
For accessing the structure members from the above example. s.no;
s.name; s.marks; Where„s‟ is the structure variable.
What is the purpose of the sizeof operator in structures?
In C, the "size of" operator, when used with structures, determines the
total amount of memory (in bytes) needed to store a variable of that
structure type, including any padding added by the compiler to align
data properly on the system's memory architecture; essentially, it tells
6. you how much space a structure occupies in memory. CO4 K2
Key points about the "sizeof" operator with structures:
 Calculates total size:
 Useful for memory management:
 Platform-independent:

Differentiate between malloc() and calloc() functions in C?

7. CO4 K1

Write a C Program to print the student Reg number, name and


marks through accessing structure elements.
#include <stdio.h>
struct student {
char name[50];
int roll;
float marks;
} s;
int main() {
printf("Enter information:\n");
8. CO4 K2
printf("Enter name: ");
fgets(s.name, sizeof(s.name), stdin);

printf("Enter roll number: ");


scanf("%d", &s.roll);
printf("Enter marks: ");
scanf("%f", &s.marks);

printf("Displaying Information:\n");
printf("Name: ");
printf("%s", s.name);
printf("Roll number: %d\n", s.roll);
printf("Marks: %.1f\n", s.marks);

return 0;
}

Output:
Enter information:
Enter name: ALEN RAJESH
Enter roll number: 6
Enter marks: 44.5
Displaying Information:
Name: ALEN RAJESH
Roll number: 6
Marks: 44.5

Explain the significance of the typedef keyword in structures.

typedef is a keyword used in C language to assign alternative names to


existing datatypes. Its mostly used with user defined datatypes, when
names of the datatypes become slightly complicated to use in programs.
Following is the general syntax for using typedef.
syntax:
typedef current_name new_name;
9. Lets take an example and see how typedef actually works. CO4 K2
typedef unsigned int cse;
 The above statement define a term ulong for an unsigned
long datatype.
 Now this along identifier can be used to define unsigned
long type variables.
cse i, j;

What is the primary advantage of using a union?

The primary advantage of using a union in C is memory


efficiency. A union allows multiple variables to share the same memory
location, meaning that only the largest member's size determines the
total memory allocation.

Advantages:
10. CO4 K2
1. Efficient Memory Usage – Since all members of a union share
the same memory space, it reduces overall memory consumption
compared to a struct, where each member gets separate memory.
2. Flexibility – Unions are useful when a variable may hold
different types of data at different times, such as in variant data
structures.
3. Interpreting Data in Different Ways – They are useful in low-
level programming, such as working with hardware registers,
where the same data can be accessed in multiple formats.

How do you define and declare a union in C?

In C, a union is a special data type that allows storing different types of


data in the same memory location. It is similar to a struct, but with a key
difference: all members of a union share the same memory, and only
one member can hold a value at any given time.
A union is defined using the union keyword, followed by a
name and member variables inside curly braces {}.
11. CO4 K1
Syntax:
CopyEdit
union UnionName {
dataType1 member1;
dataType2 member2;
...
};

How does the register storage class differ from other storage classes?

The register storage class in C and C++ differs from other storage
classes in several key ways:
 Storage Location
 register suggests that the variable should be stored in a CPU
register instead of RAM, leading to faster access.
 Other storage classes (auto, static, extern) typically store
variables in RAM (stack, data, or heap segments).
 Scope & Lifetime
 Scope: Same as auto, meaning it has block scope (local to
12. the function or block where it's declared). CO4 K2
 Lifetime: Exists only during the execution of the block
(automatic duration).
 No Address Retrieval (& Operator)
 You cannot obtain the address of a register variable using
the & operator because it may not have a memory location.
 Usage Hint to the Compiler
 Modern compilers optimize variable storage automatically,
often ignoring the register keyword.
In older systems, it helped compilers decide which variables should be
kept in fast CPU registers.

Explain the differences between static and automatic variables.

13. CO4 K2
Name different storage classes in C.

The four different storage class specifications in C are: auto, register,


static, and extern.
 auto:
 This is the default storage class for local variables, meaning
they are automatically allocated on the stack when a
function is called and deallocated when the function exits.
 register:
14.  This storage class suggests that the variable should be CO4 K1
stored in a CPU register for faster access, although the
compiler may choose to ignore this hint.
 static:
 A static variable retains its value between function calls
within the same scope, unlike a normal local variable.
 extern:
 This storage class is used to declare a global variable that is
defined elsewhere in the program.

How is memory allocated for a union in C?

In C, a union is a special data structure that allows multiple members to


share the same memory location. The memory allocated for a union is
large enough to hold the largest member, but only one member can hold
a value at any given time.
15. CO4 K2
 Size of the Union: The size of a union is determined by the size
of its largest member. If the union has different types of
members, the memory allocated is sufficient to hold the largest
one.
 Shared Memory: All members of the union share the same
starting memory address. When one member is written to, it may
overwrite the values in the other members. This is different from
a struct, where each member has its own memory location.

 Alignment: The compiler may add padding to ensure proper


alignment for certain types (e.g., for int or double), so the size of
the union might be larger than expected, depending on the
architecture and the types involved.

CO‟s Bloom‟s
Q.No Questions
Level
Part – B
Write a C program that demonstrates passing a structure to a
function by value and by reference. Discuss the difference in
behavior.

#include <stdio.h>

// Define a structure to represent a point in 2D space


struct Point {
int x;
int y;
};

// Function to pass structure by value


void passByValue(struct Point p) {
// Modify the structure inside the function
p.x = 100;
p.y = 200;
printf("Inside passByValue function: x = %d, y = %d\n", p.x, p.y);
}
1. CO4 K4
// Function to pass structure by reference
void passByReference(struct Point *p) {
// Modify the structure inside the function
p->x = 300;
p->y = 400;
printf("Inside passByReference function: x = %d, y = %d\n", p-
>x, p->y);
}

int main() {
struct Point p1 = {10, 20};

printf("Before passing by value: x = %d, y = %d\n", p1.x, p1.y);


passByValue(p1);
printf("After passing by value: x = %d, y = %d\n", p1.x, p1.y);

printf("\nBefore passing by reference: x = %d, y = %d\n", p1.x,


p1.y);
passByReference(&p1);
printf("After passing by reference: x = %d, y = %d\n", p1.x, p1.y);

return 0;
}
Output:
Before passing by value: x = 10, y = 20
Inside passByValue function: x = 100, y = 200
After passing by value: x = 10, y = 20

Before passing by reference: x = 10, y = 20


Inside passByReference function: x = 300, y = 400
After passing by reference: x = 300, y = 400

Explanation:

 Passing by Value:

 When the structure is passed by value (as in the


passByValue function), a copy of the structure is
created in the function's local scope. Any
modifications made to the structure inside the
function will not affect the original structure in the
main function.
 In the output, you will notice that after calling
passByValue, the values of x and y in main remain
unchanged.

 Passing by Reference:

 When the structure is passed by reference (as in the


passByReference function), the function receives a
pointer to the original structure. This means any
modifications made to the structure inside the
function directly affect the original structure.
 In the output, after calling passByReference, you will
notice that the values of x and y in main are modified
because the function directly changes the values of
the original structure.

Difference in Behavior:

 By Value: The function works with a copy of the structure,


so changes inside the function do not affect the original
structure.
 By Reference: The function operates on the original
structure, so changes inside the function are reflected in the
original structure.

Write a C program to manage and process student records using


self- referential structures. (The program should receive 20
student’s names, Reg.No and average marks. Rank the students
based on the marks and print them in the rank order)

#include<stdio.h> struct stud


{
int rollno;
char name[30];
int mark1,mark2,mark3,total; float avg;
char grade;
}a[25];
void main()
{
int i,n;
printf(“Enter the number of students :”); scanf(“%d”,&n);
for(i=0;i<n;i++)
{
printf(“Enter the student %d details :”,i+1);
printf(“\n Rollno:”);
scanf(“%d”,&a[i].rollno);
printf(“Name:”);
scanf(“%s”,&a[i].name);
2. printf(“Mark1”); CO4 K4
scanf(“%d”,&a[i].mark1);
printf(“Mark2”);
scanf(“%d”,&a[i].mark2);
printf(“Mark3”);
scanf(“%d”,&a[i].mark3);
a[i].total=a[i].mark1+a[i].mark2+a[i].mark3;
a[i].avg=a[i].total/3;
if(a[i].avg <40)
a[i].grade=‟D‟;
else if(a[i].avg <60) a[i].grade=‟c‟;
else if(a[i].avg <80) a[i].grade=‟B‟;
else a[i].grade=‟A‟;
}
printf(“\t\tStudent mark details :\n”);
printf(“\n Rollno \t Name \tMark 1\t Mark 2\tMark 3\t
Total\tAverage\t Grade”); for(i=0;i<n;i++)
printf(\n%d\t%s\t%d\t%d\t%d\t%d\t%.2f\t%c”,a[i].rollno,a[i].name,a
[i].mark1, a[i].mark2,a[i].mark3,a[i].total,a[i].avg,a[i].grade);
}

OUTPUT:

Enter the number of students :2 Enter the student 1 details : Roll


No:100
Name :venkat Mark 1:89
Mark 2:80
Mark 3:76
Enter the student 2 details : Roll No:101
Name :shankar Mark 1:87
Mark 2:90
Mark 3:67
Students mark details:
Rollno Name mark1 mark2 mark3 total average Grade
100 venkat 89 80 76 245 81.00 A
101 shankar 87 90 67 244 81.00 A

Write a C program to define a structure “Item” with fields: Item


Code, Item Name, and Price. Define another structure “Invoice”
that contains Invoice Number, Date, and an array of Item
structures. Write functions to input and display invoice details.

#include <stdio.h>
#include <string.h>

#define MAX_ITEMS 5 // Maximum number of items in an invoice

// Structure to store item details


struct Item {
int itemCode;
char itemName[50];
float price;
};

// Structure to store invoice details


3. CO4 K4
struct Invoice {
int invoiceNumber;
char date[20];
struct Item items[MAX_ITEMS]; // Array to store items in an
invoice
int itemCount; // Number of items in the invoice
};

// Function to input item details


void inputItem(struct Item* item) {
printf("Enter item code: ");
scanf("%d", &item->itemCode);
getchar(); // to consume newline character
printf("Enter item name: ");
fgets(item->itemName, 50, stdin);
item->itemName[strcspn(item->itemName, "\n")] = '\0'; //
Remove newline from string
printf("Enter item price: ");
scanf("%f", &item->price);
}

// Function to input invoice details


void inputInvoice(struct Invoice* invoice) {
printf("Enter invoice number: ");
scanf("%d", &invoice->invoiceNumber);
getchar(); // to consume newline character
printf("Enter invoice date: ");
fgets(invoice->date, 20, stdin);
invoice->date[strcspn(invoice->date, "\n")] = '\0'; // Remove
newline from string
printf("Enter number of items in the invoice: ");
scanf("%d", &invoice->itemCount);

// Input details for each item in the invoice


for (int i = 0; i < invoice->itemCount; i++) {
printf("\nEnter details for item %d:\n", i + 1);
inputItem(&invoice->items[i]);
}
}

// Function to display item details


void displayItem(struct Item item) {
printf("Item Code: %d\n", item.itemCode);
printf("Item Name: %s\n", item.itemName);
printf("Price: %.2f\n", item.price);
}

// Function to display invoice details


void displayInvoice(struct Invoice invoice) {
printf("\nInvoice Number: %d\n", invoice.invoiceNumber);
printf("Date: %s\n", invoice.date);
printf("Number of Items: %d\n", invoice.itemCount);

// Display details of each item in the invoice


for (int i = 0; i < invoice.itemCount; i++) {
printf("\nItem %d Details:\n", i + 1);
displayItem(invoice.items[i]);
}
}

int main() {
struct Invoice invoice;

// Input invoice details


inputInvoice(&invoice);

// Display invoice details


displayInvoice(invoice);
return 0;
}

Output:

Enter invoice number: 12345


Enter invoice date: 2025-02-01
Enter number of items in the invoice: 2

Enter details for item 1:


Enter item code: 101
Enter item name: Widget
Enter item price: 15.50

Enter details for item 2:


Enter item code: 102
Enter item name: Gadget
Enter item price: 25.75

Invoice Number: 12345


Date: 2025-02-01
Number of Items: 2

Item 1 Details:
Item Code: 101
Item Name: Widget
Price: 15.50

Item 2 Details:
Item Code: 102
Item Name: Gadget
Price: 25.75

Explain the usage of different storage classes in C.

In C, storage classes define the lifetime, visibility, and memory


location of variables or functions. There are four main storage
classes in C: auto, register, static, and extern. Let‟s break down
each one:
 auto:
 The auto storage class is the default for local CO4
4. K4
variables. It means that the variable is automatically
created when the block of code (e.g., a function) is
entered and destroyed when it‟s exited.
 Variables declared with auto are stored in the stack
and have automatic storage duration.
 You usually don't need to explicitly use the auto
keyword, since local variables are automatically
considered to be of type auto unless specified
otherwise.
Example:
void func() {
auto int x = 10; // This is the same as 'int x = 10;' in a local
scope
}
 register:
 The register storage class suggests to the compiler
that the variable should be stored in a CPU register
instead of RAM, if possible, for faster access.
 It is mainly used for frequently accessed variables like
counters or indexes in loops.
 However, it's only a suggestion; the compiler might
choose to ignore it.
 You cannot take the address of a register variable
(i.e., you cannot use the & operator on it).
Example:
void func() {
register int i; // i might be stored in a register, if possible
for (i = 0; i < 1000; i++) {
// Loop code
}
}
 static:
 The static storage class is used for variables or
functions that need to maintain their value across
function calls, but whose scope is limited to the block
(function or file) they are defined in.
 For local variables, static means that the variable
persists between function calls. It is initialized only
once and retains its value between function calls.
 For global or file-level variables/functions, static
means they are not visible outside the file they are
declared in (i.e., they have internal linkage).
Example:
void func() {
static int count = 0; // Retains its value between function
calls
count++;
printf("%d\n", count);
}

int main() {
func(); // Outputs: 1
func(); // Outputs: 2
func(); // Outputs: 3
}
 extern:
 The extern storage class is used to declare variables
or functions that are defined in another file or scope.
It tells the compiler that the variable/function exists
elsewhere, and its definition will be resolved during
linking.
 The extern keyword is used when you want to access
global variables or functions declared in another file
(i.e., it provides external linkage).
 It‟s also used to declare variables that are defined in
another translation unit, allowing them to be shared
across different files in a program.

Example:
// File1.c
int x = 10; // Definition of x

// File2.c
extern int x; // Declaration of x from File1.c
void func() {
printf("%d\n", x); // Accessing x from File1.c
}
Summary of Storage Classes:

These storage classes help control the behavior and storage of


variables and functions at different scopes and lifetimes in a C
program.
Write a program using functions to accept and display details of
a vehicle (Model, Year, Price). Pass structure as a function
argument.

#include <stdio.h>
#include <string.h>
5. CO4 K4
// Structure to represent vehicle details
struct Vehicle {
char model[50];
int year;
float price;
};
// Function to accept vehicle details from the user
void acceptVehicleDetails(struct Vehicle *v) {
printf("Enter vehicle model: ");
scanf(" %[^\n]s", v->model); // Important: Use %[^\n]s to read
strings with spaces

printf("Enter year of manufacture: ");


scanf("%d", &v->year);

printf("Enter price: ");


scanf("%f", &v->price);
}

// Function to display vehicle details


void displayVehicleDetails(struct Vehicle v) { // Note: Pass by
value here
printf("\nVehicle Details:\n");
printf("Model: %s\n", v.model);
printf("Year: %d\n", v.year);
printf("Price: %.2f\n", v.price); // %.2f formats price to two
decimal places
}

int main() {
struct Vehicle myVehicle;

// Accept details
acceptVehicleDetails(&myVehicle); // Pass the address of the
structure

// Display details
displayVehicleDetails(myVehicle); // Pass the structure itself

return 0;
}

Output:

Enter Vehicle Model: hero


Enter Year of Manufacture: 2024
Enter Price of the Vehicle: 95000

Vehicle Details:
Model: hero
Year: 2024
Price: 95000.00
Create a union called Circle that contains the radius as a
member. Implement functions to read the radius, calculate both
6. CO4 K4
the area and perimeter of the circle, and print the results.
#include <stdio.h>
#include <math.h>

// Union to represent a circle (containing its radius)


union Circle {
float radius;
};

// Function to read the radius of the circle


void readRadius(union Circle *c) {
printf("Enter the radius of the circle: ");
scanf("%f", &c->radius);
}

// Function to calculate the area of the circle


float calculateArea(union Circle c) {
return M_PI * c.radius * c.radius; // M_PI is defined in math.h
}

// Function to calculate the perimeter (circumference) of the circle


float calculatePerimeter(union Circle c) {
return 2 * M_PI * c.radius;
}

// Function to print the results


void printResults(union Circle c) {
float area = calculateArea(c);
float perimeter = calculatePerimeter(c);

printf("Radius: %.2f\n", c.radius);


printf("Area: %.2f\n", area);
printf("Perimeter: %.2f\n", perimeter);
}

int main() {
union Circle myCircle;

readRadius(&myCircle); // Read the radius

printResults(myCircle); // Calculate and print area and perimeter

return 0;
}

Output:

Enter the radius of the circle: 50


Radius: 50.00
Area: 7853.98
Perimeter: 314.16
Explain the scope of variables in C. Write a program to
demonstrate the scope of local, global, and block variables.

In C, the scope of a variable refers to the region of the program


where the variable can be accessed or modified. There are different
types of scopes in C, including:

 Global Scope:
 A variable declared outside of any function (usually at
the top of the program) has global scope.
 It is accessible from any function in the program.
 The lifetime of a global variable lasts for the duration
of the program's execution.
 Local Scope:
 A variable declared inside a function has local scope.
 It is only accessible within that specific function and
cannot be accessed outside of it.
 The lifetime of a local variable lasts from the point of
declaration to the end of the function.
 Block Scope:
 A variable declared inside a block (i.e., between curly
braces {}) has block scope.
 It is only accessible within that block and any nested
blocks within it.
7  The lifetime of a block variable lasts from the point of CO4 K5
declaration to the end of the block.

Now, let‟s look at a C program that demonstrates all three types of
variable scopes:

#include <stdio.h>

int global_var = 10; // Global variable

void function1() {
int local_var = 20; // Local variable in function1
printf("In function1, global_var = %d\n", global_var);
printf("In function1, local_var = %d\n", local_var);

{
int block_var = 30; // Block variable inside a nested block
printf("In nested block inside function1, block_var = %d\n",
block_var);
}
// block_var is not accessible here
// printf("In function1, block_var = %d\n", block_var); // Error:
block_var is out of scope
}
void function2() {
// local_var is not accessible here because it's local to function1
// printf("In function2, local_var = %d\n", local_var); // Error:
local_var is out of scope
printf("In function2, global_var = %d\n", global_var);
}

int main() {
printf("In main, global_var = %d\n", global_var);

function1(); // Call to function1


function2(); // Call to function2

// local_var is not accessible here because it's local to function1


// printf("In main, local_var = %d\n", local_var); // Error:
local_var is out of scope

return 0;
}
Explanation:
 Global Variable (global_var):
 Declared outside all functions, so it's accessible from
both function1 and function2, and also inside main().
 Local Variable (local_var):
 Declared inside function1(), so it is only accessible
within that function. It's not accessible in function2()
or main().
 Block Variable (block_var):
 Declared inside a nested block in function1(). It is
accessible only within that block and is not accessible
outside it, not even in the rest of function1().
Output:

In main, global_var = 10
In function1, global_var = 10
In function1, local_var = 20
In nested block inside function1, block_var = 30
In function2, global_var = 10

This example demonstrates how variables are scoped within


functions and blocks in C.
Explain the Preprocessor directives in C.

In C, preprocessor directives are special instructions


processed by the preprocessor before the actual compilation of the
8 code. These directives are not part of the C language syntax but CO4 K5
provide instructions for code manipulation before it is compiled.
Preprocessor directives are typically used to include libraries, define
constants, control the conditional compilation, and more.
Here‟s an overview of the most commonly used preprocessor
directives in C:

 #include:

 Purpose: Used to include header files in the program. It


allows access to functions, constants, and data types
declared in those files.
 Syntax:
#include <header-file> // for standard library
headers
#include "header-file" // for user-defined headers
 Example:
#include <stdio.h> // Includes standard I/O
functions
 #define:
 Purpose: Used to define macros or symbolic constants. It
replaces a value throughout the code before compilation.
 Syntax:
#define MACRO_NAME value
 Example:
#define PI 3.14159 // Defines PI as a constant
 Usage:
float area = PI * radius * radius;
 #undef:
 Purpose: Used to undefine a previously defined macro.
 Syntax:
#undef MACRO_NAME
 Example:
#define MAX_SIZE 100
// Later in the code
#undef MAX_SIZE // MAX_SIZE is no longer
defined

 #if, #else, #elif, #endif:

 Purpose: These directives are used to conditionally


compile code depending on whether a condition is true or
false. This is useful for platform-specific or debugging
code.
 Syntax:
#if condition
 // Code to compile if condition is true
#elif another_condition
 // Code if the first condition is false and
another_condition is true
#else
 // Code if both conditions are false
#endif
 Example:
#define DEBUG 1
#if DEBUG
printf("Debugging is enabled.\n");
#else
printf("Debugging is disabled.\n");
#endif

 #ifdef and #ifndef:

 Purpose: These are used to check if a macro is defined or not


defined. It allows for conditional compilation based on
whether a macro is already defined.
 Syntax:
#ifdef MACRO_NAME
 // Code to include if the macro is defined
#else
 // Code if the macro is not defined
#endif
#ifndef MACRO_NAME
 // Code to include if the macro is not defined
#endif
 Example:
#define FEATURE_X
#ifdef FEATURE_X
printf("Feature X is enabled.\n");
#else
printf("Feature X is not enabled.\n");
#endif

 #pragma:

 Purpose: Used to provide specific instructions to the


compiler, typically related to optimizations, warnings, or
platform-specific behavior. The functionality of #pragma
can vary across different compilers.
 Syntax:
#pragma directive_name
 Example:
#pragma once // Ensures a header file is included
only once
 #error:

 Purpose: This directive generates a compilation error


with a specified error message. It is useful for checking
conditions during precompilation.
 Syntax:
#error message
 Example:
#if !defined(WINDOWS)
#error "This program only runs on Windows"
#endif
 #line:
 Purpose: This directive is used to change the line number
and file name reported by the compiler, often used for
debugging or generating error messages.
 Syntax:
#line line_number "filename"

Example Program Using Preprocessor Directives:

#include <stdio.h> // Including the standard I/O library

#define PI 3.14159 // Define a constant for PI

#if defined(PI) // Check if PI is defined


#define AREA(radius) (PI * (radius) * (radius)) // Calculate area
of a circle
#else
#error "PI is not defined"
#endif

int main() {
float radius = 5.0;
float area = AREA(radius);
printf("Area of the circle: %.2f\n", area);

return 0;
}

How the Preprocessor Works:

 The preprocessor scans the source code.


 It processes the preprocessor directives (starting with #).
 It performs macro substitutions, includes files, and
conditionally compiles code.
 The preprocessed code (without the directives) is then passed
to the compiler.

Importance of Preprocessor Directives:

 Code Reusability: #include makes it easy to reuse code from


header files.
 Code Organization: Header files help organize code into
logical units.
 Portability: Conditional compilation (#ifdef, etc.) helps make
code portable across different platforms.
 Configuration: Macros can be used to configure the
behavior of code at compile time.

Debugging: Conditional compilation can be used to include


debugging code only when needed.

CO‟s Bloom‟s
Q.No Questions
Level
Part C
Design and implement a C program to generate employee salary
slip using structure and search a particular employee using
employee number.

#include<stdio.h> struct employee


{
char ename[25]; int eid;
char edes[20]; char edept[20]; int esal;
};
void salaryslip(struct employee *e,int n)
{
int id,i;
printf("\nEnter the employee id to generate the salary slip\n");
scanf("%d",&id);
for(i=0;i<=n;i++)
{
if((e+i)->eid==id)
{
printf("\n -----------------------------------------------------------------------
1. ------ "); CO4 K5
printf("\nNAME\t\tDEPARTMENT\t\tDESIGNATION\t\tSALARY
"); printf("\n -------------------------------------------------------------------
--- ");
printf("\n%s\t\t%s\t\t%s\t\t%d",(e+i)->ename,(e+i)->edept,(e+i)-
>edes,(e+i)->esal); printf("\n -----------------------------------------------
--------------------------------- ");
}
}
}
void main()
{
struct employee emp[20],*emp1; int m,i;
printf("Enter the no. of employee details"); scanf("%d",&m);
printf("\nEnter employee id, name, department, designation &
salary\n"); for(i=0;i<m;i++)
{
scanf("%d%s%s%s%d",&emp[i].eid,&emp[i].ename,&emp[i].edes,
&emp[i].e dept,&emp[i].esal);
}
emp1=emp; salaryslip(emp1,m);
getch();
}

Write a C program to demonstrate the use of a union to store


and display information about a book (e.g., Title, Author, and
Price). Highlight the memory usage difference between a
structure and a union.

#include <stdio.h>
#include <string.h>

// Define a structure to store book information


struct Book {
char title[50];
char author[50];
float price;
};

// Define a union to store book information


2. union BookUnion { CO4 K5
char title[50];
char author[50];
float price;
};

int main() {
// Create instances of the structure and union
struct Book book1;
union BookUnion book2;

// Storing data in the structure


strcpy(book1.title, "The C Programming Language");
strcpy(book1.author, "Dennis Ritchie");
book1.price = 29.99;

// Storing data in the union


strcpy(book2.title, "The C Programming Language");
// You can overwrite the other members in a union, as they share the
same memory location
strcpy(book2.author, "Dennis Ritchie");
book2.price = 29.99;

// Displaying information using structure


printf("Using Structure:\n");
printf("Title: %s\n", book1.title);
printf("Author: %s\n", book1.author);
printf("Price: %.2f\n", book1.price);

// Displaying information using union


printf("\nUsing Union:\n");
printf("Title: %s\n", book2.title); // Overwritten value
printf("Author: %s\n", book2.author); // Overwritten value
printf("Price: %.2f\n", book2.price); // The last assigned value

// Displaying memory usage


printf("\nMemory usage:\n");
printf("Size of Structure: %lu bytes\n", sizeof(book1));
printf("Size of Union: %lu bytes\n", sizeof(book2));
return 0;
}

Output:
Using Structure:
Title: The C Programming Language
Author: Dennis Ritchie
Price: 29.99

Using Union:
Title: The C Programming Language
Author: Dennis Ritchie
Price: 29.99

Memory usage:
Size of Structure: 104 bytes
Size of Union: 50 bytes

The key difference in memory usage between a structure and


a union lies in how they allocate memory for their members:

 Structure:

 Memory Allocation: A structure allocates memory for


each of its members individually. The members are stored
contiguously in memory, one after the other.
 Size: The size of a structure is (approximately) the sum of
the sizes of its members. There might be some padding
bytes added by the compiler for alignment purposes, but
the overall size is proportional to the sum of the member
sizes.
 Simultaneous Access: All members of a structure can be
accessed and used simultaneously. They each have their
own dedicated memory space.

 Union:

 Memory Allocation: A union allocates memory only for


its largest member. All members of the union share the
same memory location.
 Size: The size of a union is equal to the size of its largest
member.
 Exclusive Access: Only one member of a union can be
actively used at any given time. When you store a value
in one member, the values in other members might be
overwritten (because they share the same memory).

Unit – V FILE HANDLING

CO‟s Bloom‟s
Q.No Questions
Level
PART A
What is a file pointer in C?
 A file pointer in C is a data type that is used to point to a file.
 It is a structure that holds information such as the name of the
file, its location, and the mode in which the file is accessed.
1. CO5 K1
 A file pointer is used to read from and write to files, as well
as to control its position inside the file.
It acts as an interface between the program and the file, allowing the
program to interact with the file in a variety of ways.
What is the difference between fprintf() and fputs()?

fprintf() is used for formatted output with format specifiers


(e.g., %d, %s), allowing different data types to be written to a file.
2.
CO5 K2
is used to write a string to a file without formatting. It is
fputs()
simpler and generally faster but does not support variable
substitution.
3. What function is used to open a file in C? CO5 K1
 The fopen() function is used to open a file in the specified
mode.
 The function returns a file pointer (FILE *) which is used to
perform further operations on the file, such as reading from
or writing to it.
Syntax of fopen()
fopen (filename, mode);
Which C function is used to read a line from a file?
 The fgets() function is a standard way to read a file line by
line.
4.  It reads a string from the specified file until a newline CO5 K1
character is encountered or the end-of-file is reached.
Syntax
char *fgets(char *str, int n, FILE *stream);
Describe the difference between sequential access and random
access file processing in C.
Sequential Memory Access Random Memory Access

The amount of time needed to


Memory access time depends on
access memory is not dependent
where the store is located.
on the storage location.

Random Memory
In Sequential Memory Access,
Access,memory access time is
memory access time is more.
less.
5.
CO5 K2
Sequential Memory Access Random Memory Access having
having non-volatile memory. valatile memory

Implementation of Sequential Implementation of Random


Memory Access is Memory Access is
straightforward. straightforward.

Example: Semi-conductor
Example: Magnetic tape
devices

What does the fseek() function do? Provide an example scenario


where it is used.
fseek() - It is used to moves the reading control to different positions
using fseek() function.
6.
Syntax : CO5 K2
fseek(Filepointer, offset, position/whence);
Example:
fseek(fp, 0, SEEK_SET); /
What is the difference between fwrite() and fscanf()?
fwrite()
7.
The fwrite() function is used to write the objects in the given buffer CO5 K1
to the output stream (i.e.) it is used for writing an entire structure
block to a binary file. It is an unformatted write function.
Syntax: fwrite(&buffer_ptr,size,count,fileptr);
Example: fwrite(&s,n,1,fp);

fscanf():
This is a formatted file input function. This is used to read formatted
data from the given file. It takes three arguments.
Syntax:fscanf(filepointer,”controlstring”,&var1,&var2,……,&varn);
Example:fscanf(fp,”%d%s,&rollno,&name);
What is the default mode of a file when opened with fopen() in
C?
Mode Meaning of Mode
r Open for reading.
Open for reading in binary
rb mode.
w Open for writing.
Open for writing in binary
wb mode.
a Open for append.
Open for append in binary
8. ab mode.
Open for both reading and CO5 K1
r+ writing.
Open for both reading and
rb+ writing in binary mode.
Open for both reading and
w+ writing.
Open for both reading and
wb+ writing in binary mode.
Open for both reading and
a+ appending.
Open for both reading and
ab+ appending in binary mode.
Explain the role of dynamic memory allocation when handling
files in C.
Dynamic memory allocation in C allows efficient handling of files
9. by allocating memory dynamically based on file size or content. It CO5 K2
helps in reading large or unknown-sized files, resizing buffers,
handling variable-length records, and managing linked data
structures efficiently, ensuring optimal resource utilization
What C function is used to detect the end of a file?
The feof() function is used to check whether the file pointer to a
stream is pointing to the end of the file or not. It returns a non-zero
10. value if the end is reached, otherwise, it returns 0. CO5 K1
Syntax
feof(fptr);

11. What function is used to write data to a file in C? CO5 K1


In C, the fprintf(), fputs(), and fwrite() functions are commonly
used to write data to a file.

 fprintf() → Writes formatted data.


 fputs() → Writes a string to a file.

fwrite() → Writes binary data to a file.


Write a C code snippet to read data from a file until the end of
the file is reached.
#include <stdio.h>
int main() {
FILE *fp = fopen("data.txt", "r"); // Open the file in read mode
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
12. } CO5 K3
char line[100]; // Buffer to store each line
while (fgets(line, sizeof(line), fp) != NULL) {
printf("%s", line); // Print the line read from the file
}
fclose(fp); // Close the file
return 0;
}

What does the fclose() function do in C?


A file must be close after completion of all operation related to the
file. For closingfile we need to use the fclose() function.
13. Syntax: CO5 K1
fclose(filepointer);
Example:
fclose(fp);
How would you open a file in append mode using fopen() in C?
To open a file in append mode using fopen() in C, use the "a" or "a+"
mode:
14. Syntax: CO5 K3
FILE *fp = fopen("filename.txt", "a"); // Append mode (write-only)
For both reading & appending:
FILE *fp = fopen("filename.txt", "a+");
Write a C program to handle file reading and error checking for
an invalid file path.
#include <stdio.h>
int main() {
FILE *fp = fopen("file.txt", "r"); // Try to open the file
15. if (fp == NULL) { // Check if the file opened successfully CO5 K3
printf("Error: Cannot open file!\n");
return 1;
}
char ch;
while ((ch = fgetc(fp)) != EOF) { // Read and print file content
putchar(ch);
}
fclose(fp); // Close the file
return 0;
}

CO‟s Bloom‟s
Q.No Questions
Level
Part – B
Write a C program that opens a file in read mode, reads data
line by line using fgets(), and stores it in a dynamically allocated
memory buffer also handle EOF and file errors.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUFFER_SIZE 256

int main() {
FILE *file_ptr = fopen("test.txt", "r");
if (!file_ptr) {
perror("Error opening file");
return EXIT_FAILURE;
}

char buffer[BUFFER_SIZE];
printf("Content of the file:\n");

while (fgets(buffer, BUFFER_SIZE, file_ptr)) {


1. printf("%s", buffer); CO5 K4
}

fclose(file_ptr);
return EXIT_SUCCESS;
}

OUTPUT

If test.txt contains:

Hello, world!
This is a test file.
C programming is fun!

Content of the file:


Hello, world!
This is a test file.
C programming is fun!
Write a C program to open a file in binary mode, write a set of
records to the file, and then read the file back randomly using a
record number. Use functions like fseek() and ftell() for random
access.

#include <stdio.h>
#include <stdlib.h>

#define FILE_NAME "records.dat"

typedefstruct {
int id;
char name[50];
float salary;
} Employee;

// Function to write records to a file


void write_records() {
Employee employees[] = {
{1, "Alice", 50000}, {2, "Bob", 60000},
{3, "Charlie", 70000}, {4, "David", 80000},
{5, "Eve", 90000}
};

2. FILE *file = fopen(FILE_NAME, "wb"); CO5 K5


if (!file) { perror("File error"); exit(1); }
fwrite(employees, sizeof(Employee), 5, file);
fclose(file);
}

// Function to read a record based on record number


void read_record(intrecord_num) {
Employee emp;
FILE *file = fopen(FILE_NAME, "rb");
if (!file) { perror("File error"); exit(1); }

fseek(file, (record_num - 1) * sizeof(Employee), SEEK_SET);


if (fread(&emp, sizeof(Employee), 1, file))
printf("ID: %d, Name: %s, Salary: %.2f\n", emp.id, emp.name,
emp.salary);
else
printf("Invalid record number!\n");

fclose(file);
}

int main() {
write_records();
intrecord_num;
printf("Enter record number (1-5): ");
scanf("%d", &record_num);
read_record(record_num);
return 0;
}

OUTPUT:

Enter recordnumber (1-5): 3

ID:3,Name:Charlie,Salary:70000.00

Write a C program to merge two files into a third file. The names
of the files must be entered using command line arguments.
#include <stdio.h>
void main() {
char c;
FILE *fptr1, *fptr2, *fptr3;

// Input and store content in FIRST.TXT


printf("Enter the text to be stored in the file - 1.\n");
printf("Use Ctrl+Z (Windows) or Ctrl+D (Linux/macOS) at the end
of the text and press ENTER:\n\n");
fptr1 = fopen("FIRST.TXT", "w");
while ((c = getc(stdin)) != EOF)
fputc(c, fptr1);
fclose(fptr1);

// Input and store content in SECOND.TXT


printf("\nEnter the text to be stored in the file - 2.\n");
3. printf("Use Ctrl+Z (Windows) or Ctrl+D (Linux/macOS) at the end CO5 K4
of the text and press ENTER:\n\n");
fptr2 = fopen("SECOND.TXT", "w");
while ((c = getc(stdin)) != EOF)
fputc(c, fptr2);
fclose(fptr2);

// Open files for merging


fptr1 = fopen("FIRST.TXT", "r");
fptr2 = fopen("SECOND.TXT", "r");
fptr3 = fopen("MERGE.TXT", "w");

// Copy FIRST.TXT to MERGE.TXT


while ((c = fgetc(fptr1)) != EOF)
fputc(c, fptr3);
fclose(fptr1);

// Copy SECOND.TXT to MERGE.TXT


while ((c = fgetc(fptr2)) != EOF)
fputc(c, fptr3);
fclose(fptr2);
fclose(fptr3);

// Display the content of MERGE.TXT


printf("\nThe content of the merged file is:\n\n");
fptr3 = fopen("MERGE.TXT", "r");
while ((c = fgetc(fptr3)) != EOF)
putchar(c);
fclose(fptr3);
}

OUTPUT

FIRST.TXT
Hello, thisis file one.
^Z (Windows) or Ctrl+D (Linux/macOS)
SECOND.TXT
This is file two.
^Z (Windows) or Ctrl+D (Linux/macOS)
MERGE.TXT
The content of the merged file is:

Hello, thisis file one.


This is file two.

Write a function that accepts a file path and writes multiple


records into the file. Use dynamic memory allocation to handle
the record data and write the data to the file in binary format.

The “malloc” or “memory allocation” method in C is used to


dynamically allocate a single large block of memory with the
specified size. It returns a pointer of type void which can be cast into
a pointer of any form. It doesn‟t Initialize memory at execution time
so that it has initialized each block with the default garbage value
initially.

4. Syntax of malloc() in C CO5 K4


ptr = (cast-type*) malloc(byte-size)

#include <stdio.h>
#include <stdlib.h>

typedefstruct {
int id;
char name[50];
float salary;
} Employee;
// Function to write multiple records to a file
void write_records(const char *file_path) {
intnum_records;
printf("Enter the number of employees: ");
scanf("%d", &num_records);

// Allocate memory for records


Employee *employees = (Employee *)malloc(num_records *
sizeof(Employee));
if (!employees) {
perror("Memory allocation failed");
exit(1);
}

// Input employee details


for (inti = 0; i<num_records; i++) {
printf("Enter details for Employee %d:\n", i + 1);
printf("ID: ");
scanf("%d", &employees[i].id);
printf("Name: ");
scanf("%s", employees[i].name);
printf("Salary: ");
scanf("%f", &employees[i].salary);
}

// Open file in binary write mode


FILE *file = fopen(file_path, "wb");
if (!file) {
perror("File opening failed");
free(employees);
exit(1);
}

// Write data to the file


fwrite(employees, sizeof(Employee), num_records, file);
fclose(file);

// Free allocated memory


free(employees);

printf("\nRecords successfully written to %s\n", file_path);


}

int main() {
write_records("employees.dat");
return 0;
}

OUTPUT
User Input:
Enter the number of employees:2
Enter details for Employee 1:
ID:101
Name:Alice
Salary:55000
Enter details for Employee 2:
ID:102
Name:Bob
Salary:60000
Output:
Records successfully written to employees.dat
Develop a C program that performs sequential access file
processing. The program should read integers from a file,
calculate their sum, and display the result.

#include<stdio.h>
void main()
{
FILE* fp;
int n[50], i = 0;
float sum = 0;

if ((fp = fopen("num.dat", "r")) != NULL)


{
puts("Reading numbers from num.dat");

// Read numbers until fscanf fails (indicating end of file or


error)
while (fscanf(fp, "%d", &n[i]) == 1)
5. CO5 K4
{
printf("%d %d\n", i, n[i]);
sum += n[i];
i++;
}
fclose(fp);
// Calculate the average using the correct count of numbers read
if (i> 0)
printf("The SUM is %f for %d numbers\n", sum,i);
else
puts("No numbers to process.");
}
else
{
puts("File could not be opened.");
}
}
OUTPUT

num.dat
10 20 30 40 50

Reading numbers from num.dat


0 10
1 20
2 30
3 40
4 50
The SUM is 150.000000 for 5 numbers:

Create a C program that reads a large text file, processes its


content dynamically (e.g., storing each line into dynamically
allocated memory), and then writes the processed data to a new
file. The program should handle memory allocation efficiently
and use error checking throughout the file operations.

#include <stdio.h>
#include <stdlib.h>

#define INITIAL_SIZE 128

int main() {
const char *input_file_name = "input.txt"; // Input file name
const char *output_file_name = "output.txt"; // Output file name

FILE *input = fopen(input_file_name, "r");


6. if (input == NULL) { CO5 K5
perror("Error opening input file");
return EXIT_FAILURE;
}

FILE *output = fopen(output_file_name, "w");


if (output == NULL) {
perror("Error opening output file");
fclose(input);
return EXIT_FAILURE;
}

char *line = (char *)malloc(INITIAL_SIZE);


if (line == NULL) {
perror("Memory allocation failed");
fclose(input);
fclose(output);
return EXIT_FAILURE;
}

size_t size = INITIAL_SIZE;


size_tlen = 0;
intch;

while ((ch = fgetc(input)) != EOF) {


if (len + 1 >= size) {
size *= 2;
line = realloc(line, size);
if (line == NULL) {
perror("Memory reallocation failed");
fclose(input);
fclose(output);
return EXIT_FAILURE;
}
}

line[len++] = ch;

if (ch == '\n') {
line[len] = '\0'; // Null-terminate the line
fputs(line, output); // Write line to output
len = 0; // Reset line length for next line
}
}

if (len> 0) {
line[len] = '\0';
fputs(line, output); // Write the last line if not followed by newline
}

free(line);
fclose(input);
fclose(output);

printf("File processed successfully.\n");


return 0;
}

OUTPUT

input.txt:
Hello, World!
This is a test file.
1234567890
output.txt:
Hello, World!
This is a test file.
1234567890

Console Output:
File processed successfully

Write a brief note on file functions that are used to (a) read data
from a file (b) write data to a file with suitable examples.
Reading Data from a file
The fscanf() is used to read formatted data from the stream i.e text
file.The
Syntax:

intfscanf(FILE *stream, const char


Example: *format,…);
#include<stdio.h>
void main()
{
FILE *fp;
char name[80];
int roll_no;
fp = fopen("stud.txt", "r");
if(fp==NULL)
{
printf("\n The file could not be opened");
exit(1);
}
printf("\n Enter the name and roll number of the student : ");
fscanf(stdin, "%s
%d", name, &roll_no); // read from keyboard
printf(“\n NAME : %s \t ROLL NUMBER =
7 %d", name, roll_no); CO5 K4
fscanf(fp, "%s %d", name, &roll_no); // read from file-
stud.txt
printf(“\n NAME : %s \t ROLL NUMBER =
%d", name, roll_no);
fclose(fp);
}
Output:
Enter the name and roll number of the student : raj 101
NAME : raj ROLL NUMBER = 101
NAME : raj ROLL NUMBER = 101

(b) Writing the Data to file using fprintf( ):


The fpritnt() is used to write formatted output to stream.

Syntax:
intfprintf ( FILE * stream, const char * format,
... );
The parameter format in the fprintf() is a C string that contains the text
that has to be written on to the stream.

Example:
#include <stdio.h>
void main()
{
FILE *fptr;
char name[20];
int age;
float salary;
fptr = fopen ("emp.txt", "w"); /* open for writing*/
if (fptr == NULL)
{
printf("File does not exists \n");
return;
}
printf("Enter the name \n");
scanf("%s", name);
fprintf(fptr, "Name = %s\n", name);
printf("Enter the age \n");
scanf("%d", &age);
fprintf(fptr, "Age = %d\n", age);
printf("Enter the salary \n");
scanf("%f", &salary);
fprintf(fptr, "Salary = %.2f\n", salary);
fclose(fptr);
}
Output:
Enter the name
raj
Enter the age
30
Enter the salary
50000
Design a file handling system in C that allows the user to add,
delete, and update records in a binary file. The program should
use random access to locate specific records, and dynamic
memory allocation should be used for managing record data.
Implement error handling and file pointer management to
ensure data consistency.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct student {
intrno;
8 CO5 K5
char name[50];
};

void addRecord(FILE *fp);


void displayRecords(FILE *fp);
void modifyRecord(FILE *fp);
void deleteRecord(FILE *fp);

int main() {
FILE *fp;
intch;

fp = fopen("stu.dat", "r+b");
if (fp == NULL) {
fp = fopen("stu.dat", "w+b");
if (fp == NULL) {
perror("File opening failed");
exit(1);
}
}

while (1) {
printf("1. Add New Record\n2. Display\n3. Modify\n4. Delete\n5.
Exit\n");
printf("Enter your choice: ");
scanf("%d", &ch);

switch (ch) {
case 1:
addRecord(fp);
break;
case 2:
displayRecords(fp);
break;
case 3:
modifyRecord(fp);
break;
case 4:
deleteRecord(fp);
break;
case 5:
printf("Exiting...\n");
fclose(fp);
exit(0);
default:
printf("Invalid choice\n");
}
}

return 0;
}

void addRecord(FILE *fp) {


struct student s;
fseek(fp, 0, SEEK_END); // Move the file pointer to the end
printf("Enter roll number and name: ");
scanf("%d %s", &s.rno, s.name);
fwrite(&s, sizeof(s), 1, fp);
printf("Record added successfully.\n");
}

void displayRecords(FILE *fp) {


struct student s;
rewind(fp); // Move to the beginning of the file
printf("The records are:\n");

while (fread(&s, sizeof(s), 1, fp) == 1) {


printf("Roll No: %d, Name: %s\n", s.rno, s.name);
}
}

void modifyRecord(FILE *fp) {


struct student s;
introllNo, found = 0;
printf("Enter the roll number to modify: ");
scanf("%d", &rollNo);

rewind(fp);
while (fread(&s, sizeof(s), 1, fp) == 1) {
if (s.rno == rollNo) {
found = 1;
fseek(fp, -sizeof(s), SEEK_CUR); // Move back to the current
record's position
printf("Enter new roll number and name: ");
scanf("%d %s", &s.rno, s.name);
fwrite(&s, sizeof(s), 1, fp);
printf("Record updated successfully.\n");
break;
}
}

if (!found) {
printf("Record not found!\n");
}
}

void deleteRecord(FILE *fp) {


struct student s;
FILE *tempFile;
introllNo, found = 0;

tempFile = fopen("temp.dat", "w+b");


if (tempFile == NULL) {
perror("Error opening temporary file");
exit(1);
}

printf("Enter the roll number to delete: ");


scanf("%d", &rollNo);

rewind(fp);
while (fread(&s, sizeof(s), 1, fp) == 1) {
if (s.rno != rollNo) {
fwrite(&s, sizeof(s), 1, tempFile);
} else {
found = 1;
}
}

if (found) {
printf("Record deleted successfully.\n");
fclose(fp);
fclose(tempFile);
remove("stu.dat");
rename("temp.dat", "stu.dat");
fp = fopen("stu.dat", "r+b");
} else {
printf("Record not found.\n");
}
}

OUTPUT
1. Add New Record
2. Display
3. Modify
4. Delete
5. Exit
Enter your choice: 1
Enter roll number and name: 101 John
Record added successfully.

1. Add New Record


2. Display
3. Modify
4. Delete
5. Exit
Enter your choice: 2
The records are:
Roll No: 101, Name: John

1. Add New Record


2. Display
3. Modify
4. Delete
5. Exit
Enter your choice: 3
Enter the roll number to modify: 101
Enter new roll number and name: 102 Jack
Record updated successfully.

1. Add New Record


2. Display
3. Modify
4. Delete
5. Exit
Enter your choice: 2
The records are:
Roll No: 102, Name: Jack

1. Add New Record


2. Display
3. Modify
4. Delete
5. Exit
Enter your choice: 4
Enter the roll number to delete: 102
Record deleted successfully.

1. Add New Record


2. Display
3. Modify
4. Delete
5. Exit
Enter your choice: 2
The records are:
File is Empty

1. Add New Record


2. Display
3. Modify
4. Delete
5. Exit
Enter your choice: 5
Exiting...

CO‟s Bloom‟s
Q.No Questions
Level
Part C
Create a C program to read account details from a sequential
access file and count the number of account holders whose
balance is below the required minimum balance. Your program
should open the file, read account details, check the balance, and
display the total count of such account holders.

#include <stdio.h>
1. void insert(); CO5 K6
void count();
int main(void)
{
int choice = 0;
while (choice != 3)
{
printf("\n1 insert records\n");
printf("2 Count min balance holders\n");
printf("3 Exit\n");
printf("Enter choice:");
scanf("%d", &choice);
switch(choice)
{
case 1: insert(); break;
case 2: count(); break;
}
}
}
void insert()
{
unsigned intaccount,i;
char name[30];
double balance;
FILE* cfPtr;
if ((cfPtr = fopen("clients.dat", "w")) == NULL) {
puts("File could not be opened");
}
else {
intrecords,i=0;
printf("Enter the No. of records ");
scanf("%d", &records);
while (i<records)
{
printf("Enter the account, name, and balance.");
scanf("%d%29s%lf", &account, name, &balance);
fprintf(cfPtr, "%d %s %.2f\n", account, name, balance);
i++;
}
fclose(cfPtr);
}
}
void count()
{
unsigned int account;
char name[30];
double balance;
float minBal = 5000.00;
int count = 0;
FILE *cfPtr;
if ((cfPtr = fopen("clients.dat", "r")) == NULL)
printf("File could not be opened");
else
{
printf("%-10s%-13s%s\n", "Account", "Name", "Balance");
fscanf(cfPtr, "%d%29s%lf", &account, name, &balance);
while (!feof(cfPtr))
{
if (balance <minBal)
{
printf("%-10d%-13s%7.2f\n", account, name, balance);
count++;
}
fscanf(cfPtr, "%d%29s%lf", &account, name, &balance);
}
fclose(cfPtr);
printf("The number of account holders whose balance is less than the
minimum balance:
%d", count);
}
}
OUTPUT:
1 insert records
2 Count min balance holders
3 Exit
Enter choice:1
Enter the No. of records 2
Enter the account, name, and balance.1001 A 10000
Enter the account, name, and balance.1002 B 300
1 insert records
2 Count min balance holders
3 Exit
Enter choice:2
Account Name
Balance
1002
B
300.00
The number of account holders whose balance is less than the
minimum balance: 1
1 insert records
2 Count min balance holders
3 Exit
Enter choice: 3
Design and implement a C program to update the telephone
details of an individual or a company in a telephone directory
using a random access file. Your program should allow searching
for a specific record, modifying the telephone number, and
saving the updated details back into the file.
#include<stdio.h>
structteledir
2. CO5 K6
{
int no;
char name[3];
};
void main()
{
structteledir t1,t2,t3;
inti,n,p,newp;
FILE *fp,*fp1;
clrscr();
fp=fopen("td.txt","w");
printf("Enter the no of records\n");
scanf("%d",&n);
printf("Enter the record\n");
for (i=0;i<n;i++)
{
scanf("%d%s",&t1.no,t1.name);
fwrite(&t1,sizeof(structteledir),1,fp);
}
fclose(fp);
fp=fopen("td.txt","r");
while(fread(&t2,sizeof(structteledir),1,fp)!=NULL)
{
printf("\t%d%s\n",t2.no,t2.name);
}
printf("Enter number to be modified & a new number\n");
scanf("%d%d",&p,&newp);
fclose(fp);
fp=fopen("td.txt","r+");
fp1=fopen("td1.txt","w");
while(fread(&t2,sizeof(structteledir),1,fp)!=NULL)
{
if(t2.no==p)
{
fseek(fp,-sizeof(structteledir),SEEK_CUR);
t3.no=newp;
strcpy(t3.name,t2.name);
fwrite(&t3,sizeof(structteledir),1,fp1);
}
else
{
fwrite(&t2,sizeof(structteledir),1,fp1);
}
}
fclose(fp);
fclose(fp1);
fp=fopen("td1.txt","r");
while(fread(&t3,sizeof(structteledir),1,fp)!=NULL)
{
printf("\t%d\t%s\n",t3.no,t3.name);
}
fclose(fp);
getch();
}
OUTPUT:
Enter the no of records
3
Enter the record
111 abc
222 xyz
333 nmo
111abc
222xyz
333nmo
Enter number to be modified & a new number
222 9898
111 abc
9898 xyz
333 nmo

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy