231CSC201T-Programming in C-CAT II QB With Answers
231CSC201T-Programming in C-CAT II QB With Answers
Regulations R 2023
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.
4.
CO3 K2
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>
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
};
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>
int main() {
char str[100];
CO‟s Bloom‟s
Q.No Questions
Level
PART A
Define a structure in C.
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;
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.
7. CO4 K1
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
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 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.
13. CO4 K2
Name different storage classes in C.
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>
int main() {
struct Point p1 = {10, 20};
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
Explanation:
Passing by Value:
Passing by Reference:
Difference in Behavior:
OUTPUT:
#include <stdio.h>
#include <string.h>
int main() {
struct Invoice invoice;
Output:
Item 1 Details:
Item Code: 101
Item Name: Widget
Price: 15.50
Item 2 Details:
Item Code: 102
Item Name: Gadget
Price: 25.75
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:
#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
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:
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>
int main() {
union Circle myCircle;
return 0;
}
Output:
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>
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);
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
#include:
#pragma:
int main() {
float radius = 5.0;
float area = AREA(radius);
printf("Area of the circle: %.2f\n", area);
return 0;
}
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>
#include <string.h>
int main() {
// Create instances of the structure and union
struct Book book1;
union BookUnion book2;
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
Structure:
Union:
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()?
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
Example: Semi-conductor
Example: Magnetic tape
devices
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);
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>
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");
fclose(file_ptr);
return EXIT_SUCCESS;
}
OUTPUT
If test.txt contains:
Hello, world!
This is a test file.
C programming is fun!
#include <stdio.h>
#include <stdlib.h>
typedefstruct {
int id;
char name[50];
float salary;
} Employee;
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:
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;
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:
#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);
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;
num.dat
10 20 30 40 50
#include <stdio.h>
#include <stdlib.h>
int main() {
const char *input_file_name = "input.txt"; // Input file name
const char *output_file_name = "output.txt"; // Output file name
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);
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:
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];
};
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;
}
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");
}
}
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.
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