0% found this document useful (0 votes)
10 views40 pages

PPS_MID-II_(1)[1]

The document discusses various concepts related to functions and pointers in C programming, including definitions, advantages, limitations, and examples of different types of functions. It also covers recursion, parameter passing mechanisms, storage classes, and pointer operations, providing code snippets for practical understanding. Additionally, it highlights the differences between recursion and iteration, as well as the uses and pitfalls of pointers.

Uploaded by

srundhanreddy7
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)
10 views40 pages

PPS_MID-II_(1)[1]

The document discusses various concepts related to functions and pointers in C programming, including definitions, advantages, limitations, and examples of different types of functions. It also covers recursion, parameter passing mechanisms, storage classes, and pointer operations, providing code snippets for practical understanding. Additionally, it highlights the differences between recursion and iteration, as well as the uses and pitfalls of pointers.

Uploaded by

srundhanreddy7
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/ 40

PPS MID-2 IMPORTANT QUESTIONS 24-25 SEM-1

UNIT-3

FUNCTIONS

1.Define a Function. Write the advantages and limitations of using functions in C

Programming language. Explain different classification of user defined functions based on

parameter passing and return type with examples.

A function is a block of code that performs a specific task.


Instead of writing the same code multiple times, we can write it once in a function and call it
whenever needed.

Advantages of functions
1. Code Reusability: Write code once and reuse it.
2. Modularity: Break a large program into smaller, manageable parts.
3. Simplified Code: Makes code easier to understand and maintain.
4. Easier Debugging: Fix issues in one place without affecting other parts of the code

There are 4 different types of functions based on number of parameters passed and return type
1. Function with no return value and with no arguments
void printMessage() {
printf("Hello, this is a simple message.\n");
}
2. Function with no return value and with arguments
void printSum(int a, int b) {
int sum = a + b;
printf("The sum is: %d\n", sum);
}
3. Functions with return values and no arguments allow you to create a function that doesn’t
require any input data but still returns a result.
int getNumber() {
int number = 42; // or any logic to determine the value
return number;
}
4. Function with return value and with arguments
int multiply(int x, int y) { //function header (int x, int y are formal parameters)
return x * y;//function body
}
2.Construct a ‘C’ program to calculate the area of the square using Function without argument and
with return value.
int getArea() {

float side, area;

printf(“Enter the side length of the square:”);


scanf (“%f”, &side);

area = side * side;


return area;
}
3.Define the Recursive functions. List the limitations of recursive functions. Write a C program to
calculate the Fibonacci sequence using recursive and non recursive Functions.

A recursive function is a function that calls itself within its code.


Disadvantages of Recursion
1. Memory Usage:
1. Every recursive call requires memory to be allocated on the stack to store function call details
(parameters, return address, local variables).
2. This stack memory can add up quickly for deep recursive calls, potentially leading to a stack
overflow if the recursion depth is too large.
2. Performance Overhead:
1. Recursive calls involve extra overhead for maintaining call stack information. Each recursive
function call takes time and memory, leading to inefficiencies compared to iterative solutions.
2. For some problems, an iterative approach can be more efficient in terms of speed and memory
usage.
3. Risk of Stack Overflow:
1. Deep recursive calls can lead to stack overflow errors, as the stack has limited memory.
2. Without careful control of the recursion depth, especially in the absence of a proper base case or
in cases of excessive depth, programs may crash due to stack overflow.
4. Difficult to Debug:
1. Recursive code can be challenging to debug and trace, especially for beginners. Since each
function call has its own execution context, it may be difficult to follow the logic and pinpoint errors.
2. Understanding the flow of execution requires following multiple levels of function calls, which can
be tricky.
5. May Not Be Tail-Optimized:
1. While tail recursion (when the recursive call is the last operation in the function) can sometimes
be optimized to save stack space, C compilers do not always optimize tail recursion. Therefore,
recursive solutions in C can be less efficient than they might be in other languages that optimize tail
recursion.
6. Complexity in Understanding Base Cases:
1. Properly defining base cases is essential for recursive functions to terminate. If a base case is not
correctly defined, the function can go into an infinite recursMio.snun, itchaausing a stack overflow.

#include <stdio.h>

// Recursive function to calculate Fibonacci numbers


int fibonacci_recursive(int n) {
if (n <= 1)
return n;
return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2);
}

// Non-recursive (iterative) function to calculate Fibonacci numbers


int fibonacci_iterative(int n) {
if (n <= 1)
return n;

int prev1 = 0, prev2 = 1, current;


for (int i = 2; i <= n; i++) {
current = prev1 + prev2;
prev1 = prev2;
prev2 = current;
}
return current;
}

int main() {
int n;

printf("Enter the number of terms for the Fibonacci sequence: ");


scanf("%d", &n);

if (n < 0) {
printf("Please enter a non-negative integer.\n");
return 1;
}

printf("Fibonacci sequence using recursion:\n");


for (int i = 0; i < n; i++) {
printf("%d ", fibonacci_recursive(i));
}
printf("\n");

printf("Fibonacci sequence using iteration:\n");


for (int i = 0; i < n; i++) {
printf("%d ", fibonacci_iterative(i));
}
printf("\n");

return 0;
}
4.Differentiate between recursion and iteration and Write a C program to calculate GCD of

two numbers using recursive and non recursive Functions.

#include <stdio.h>

// Recursive function to calculate GCD


int gcd_recursive(int a, int b) {
if (b == 0)
return a;
return gcd_recursive(b, a % b);
}

// Non-recursive (iterative) function to calculate GCD


int gcd_iterative(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}

int main() {
int a, b;

printf("Enter two numbers to calculate GCD: ");


scanf("%d %d", &a, &b);

if (a < 0 || b < 0) {
printf("Please enter non-negative integers.\n");
return 1;
}

printf("GCD using recursion: %d\n", gcd_recursive(a, b));


printf("GCD using iteration: %d\n", gcd_iterative(a, b));

return 0;
}
5.Differentiate between call by value and call by reference function parameter passing

mechanism with the help of a program.

Pass by Value means passing a copy of the argument's value to the function. The function works
on this copy, so changes made to the parameter inside the function do not affect the original
variable in the caller function.
Pass by Reference means passing the actual memory address (reference) of the argument to the
function. The function can then modify the original variable’s value since it has direct access to its
memory location. In C, we achieve pass by reference by using pointers.

#include <stdio.h>

void passing_byRef(int *x) {


*x = 20; // This changes the original variable that x points to
printf("Inside function, *x = %d\n", *x);
}

void passing_byValue(int y) {
y = 30; // This doesn’t change the original variable
printf("Inside function, y = %d\n", y);
}

int main() {
int a = 10;
printf("Before function call, a = %d\n", a); // prints 10

// Pass by reference
passing_byRef (&a);
printf("After function call, a = %d\n", a); // prints 20, changes from 10 to 20

// Pass by value
passing_byValue (a);
printf("After function call, a = %d\n", a); // prints 20, did not change to 30

return 0;
}
6.List and explain the types of storage classes in C.

extern int a; // It will get access to the variable defined in another file.
static int static_global_count = 0; //limits scope to the current file
void example() {
auto int num = 10; // 'auto' is optional
static int static_local_count = 0; // retains value across function calls
printf("Value of num: %d\n", num);
register int i;
for (i = 0; i < 5; i++) {
printf("%d ", i);
}
}
UNIT-4

POINTERS

1.Define the Pointer in C Programming. Explain how the pointer variable declared and initialized?
Write a C program to find the sum and mean of all elements in an array using pointer.

The pointer in C language is a variable which stores the address of another variable. This variable can
be of type int, char, array, function, or any other pointer. The size of the pointer depends on the
machine architecture.

Just like the variables, we also have to declare the pointers in C before we use them in any program
SYNTAX:data_type * name_of_pointer_variable;
We can declare the pointers in the C language with the use of asterisk (*, dereferencing symbol).
For example:
int *ip;
char *cp;

Pointers can be initialized with address of the already declared variables. Address of a variable can be
obtained by placing an ampersand (&) in front of a variable name;
SYNTAX: pointer_variable = & name_of_another_variable;
int a = 10;
int *ip;
ip = &ip;

Pointers can be assigned with the address returned by malloc function with appropriate typecasting.
int *ip;
ip = (int *) malloc (10 * sizeof(int)); // address of the memory allocated for 10 integer values

// Function to calculate sum and mean of array elements using pointers


void calculate_sum_and_mean(int *arr, int size, int *sum, float *mean) {
*sum = 0;
for (int i = 0; i < size; i++) {
*sum += *(arr + i);
}
*mean = (float)(*sum) / size;
}
int main() {
// Array sum and mean calculation
int n;
printf("\nEnter the size of the array: ");
scanf("%d", &n);

if (n <= 0) {
printf("Invalid array size.\n");
return 1;
}

int arr[n];
printf("Enter %d elements of the array: ", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

int sum;
float mean;
calculate_sum_and_mean(arr, n, &sum, &mean);

printf("Sum of array elements: %d\n", sum);


printf("Mean of array elements: %.2f\n", mean);

return 0;
}

2.Write a C program to implement function pointer to find sum and product of two numbers.

int add(int a,int b)


{
int c=a+b;
return c;
}

int multiply(int a,int b)


{
int c=a*b;
return c;
}

#include <stdio.h>
int add(int,int);
int main()
{
int a,b;
int (*ip)(int,int);
int *ptr;
int result;
printf("Enter the values of a and b : ");
scanf("%d %d",&a,&b);

ip=add;
result=(*ip)(a,b); //function call to sum up two numbers
printf("Value after addition is : %d",result);

ip=multiply;
result=(*ip)(a,b); //function call to get product of two numbers
printf("Value after multiplication is : %d",result);
return 0;
}
3.What is a pointer? How it can be used to access 1D array and 2D array using pointer.

The pointer in C language is a variable which stores the address of another variable. This variable can
be of type int, char, array, function, or any other pointer.

For an array, the base address is the location of the first element (index 0) of the array. The compiler
also defines the array name as a constant pointer to the first element.

If ‘p’ is a pointer to a one dimensional array ‘a’ then the array name “a” is a constant pointer pointing
to first element of that array &a[0] => a => (base address)

In case of 2D arrays,
• arr points to the first row (address of arr[0]).
• arr[0] points to the first element of the first row (arr[0][0]).
• arr + 1: Points to the second row (arr[1]).
• *(arr + 1): Dereferences the pointer to the second row, equivalent to arr[1].
• *(*(arr + 1) + 2): Accesses the element in the second row, third column (arr[1][2]).

4.What are the advantages and disadvantages of pointers? Explain the possible arithmetic and
value arithmetic operations on pointers.

There are various uses of the pointers in C language. Some of them are listed below:
1. One can easily access any location of memory in the computer using the pointers
2. We can allocate the memory dynamically in C language when we use the calloc() and
malloc() functions. The pointers are primarily used in such cases.
3. Pointers are used to create complex data structures, like the linked list, tree, graph, etc.
4. It reduces the code and thus improves the overall performance. We can use it to retrieve the
strings, trees, and many more. We can also use it with structures, arrays, and functions
5. Pass by reference is implemented by using pointers in C language.

The disadvantages of the pointers are listed below:


1. Pointers can lead to some errors like segmentation faults, accessing of unwanted memory
locations, and many more.
2. A pointer may cause corruption of memory if we provide it with an incorrect value.
3. Pointers in a program can lead to leakage of memory.
4. As compared to all the other variables, pointers are somewhat slower.
5. Some programmers might find it very tricky to deal with pointers in a program. It is their
responsibility to use these pointers and manipulate them carefully.

Possible operations with pointers:


1. Increment/Decrement of a Pointer (p++, p--)
2. Addition of integer to a pointer (p+1)
3. Subtraction of integer to a pointer (p-1)
4. Subtracting two pointers of the same type (p2 – p1)
5. Comparison of pointers (<, <=, >, >=, ==, !=)
Invalid arithmetic operations with pointers:
1. Product of pointers (p1 * p2, p1 * 2)
2. Division of pointers (p1 / p2, p1 / 2)
3. Subtraction of pointers of different types (int_p1 – char_p2)
4. Addition of pointers (p1 + p2)

5.Write a short note on:(i)void pointer (ii)pointer to pointer(iii) null pointer (iv) dangling

pointer (v) constant pointer.

The Void pointers in C are the pointers of type void. It means that they do not have any associated
data type. They are also called generic pointers as they can point to any type and can be typecasted.
Syntax: void * pointer_name;
Note: Void pointers cannot be dereferenced. It can however be done using typecasting the void
pointer. Pointer arithmetic is not possible on pointers of void due to lack of concrete value and thus
size.
int main()
{
int x = 4;
float y = 5.5;
// A void pointer
void* ptr;

// void pointer is now int


ptr = &x;
printf("Integer variable is = %d", *((int*)ptr));

// void pointer is now float


ptr = &y;
printf("\nFloat variable is = %f", *((float*)ptr));

return 0;
}

A pointer variable can store the address of any type including the primary data types, arrays, struct
types, etc. Likewise, a pointer can store the address of another pointer too, in which case it is called
"pointer to pointer" (also called "double pointer").

NULL Pointer is a pointer that is pointing to nothing (i.e. not pointing to any valid object or memory
location). In case, if we don’t have an address to be assigned to a pointer, then we can simply use
NULL. NULL is used to represent that there is no valid memory address.

A pointer pointing to a memory location that has been deleted (or freed) is called a dangling pointer.
Such a situation can lead to unexpected behavior in the program and also serve as a source of bugs
in C programs.

int main()
{
int* ptr = (int*)malloc(sizeof(int));
// After below free call, ptr becomes a dangling
pointer
free(ptr);
printf("Memory freed\n");
// removing Dangling Pointer
ptr = NULL;
return 0;
}

A constant pointer in C cannot change the address of the variable to which it is pointing, i.e., the
address will remain constant. Therefore, we can say that if a constant pointer is pointing to some
variable, then it cannot point to any other variable.

SYNTAX:<type of pointer> *const <name of pointer>

Declaration of a constant pointer is given below:


int *const ptr;

#include <stdio.h>
int main()
{
int a=1;
int b=2;
int *const ptr;
ptr=&a; // We will get error here.
ptr=&b; // We will get error here.
printf("Value of ptr is :%d",*ptr);
return 0;
}
STRUCTURES

1.Compare and Explain the following with suitable examples

(i) Nested Structures

A nested structure in C is a structure within structure. One structure can be declared inside another
structure in the same way structure members are declared inside a structure.

Syntax of an embedded nested structure:


struct name_1
{
member1;
member2;
membern;
struct name_2
{
member_1;
member_2;

member_n;
} var1;
} var2;

Syntax of separate nested structure


struct DependentStructure{
data member 1;
data member 2;
};
struct ParentStructure{
data member 1;
data member 2;
struct DependentStructure X;
};

(ii) Array of structures

An array of structures in C can be defined as the collection of multiple structures variables where
each variable contains information about different entities.
The array of structures in C are used to store information about multiple entities of different data
types.
The array of structures is also known as the collection of structures

#include<stdio.h>
#include <string.h>
struct student{
int rollno;
char name[10];
};
int main(){
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++){
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++){
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
return 0;
}

Comparison:

Feature Nested Structure Array of Structures

Encapsulates related structures as Manages multiple instances of the same


Purpose
members. structure.

Use . operator to access nested Access using array indexing and .


Access
structure fields. operator.

Ideal for hierarchical or composite


Complexity Suitable for homogeneous data.
data.

Example Use
Person details with an address. List of students or employees.
Cases

2. Define the structure employee with attributes employee id, name, department and basic

salary. Develop a C program to display the employee details in the increasing order of their

salaries.

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

// Define structure for employee


struct Employee {
int id;
char name[50];
char department[30];
float basic_salary;
};

// Function to sort employees by salary in increasing order


void sort_employees_by_salary(struct Employee employees[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (employees[j].basic_salary > employees[j + 1].basic_salary) {
struct Employee temp = employees[j];
employees[j] = employees[j + 1];
employees[j + 1] = temp;
}
}
}
}

int main() {
int n;

printf("Enter the number of employees: ");


scanf("%d", &n);

if (n <= 0) {
printf("Invalid number of employees.\n");
return 1;
}

struct Employee employees[n];

// Input employee details


for (int i = 0; i < n; i++) {
printf("\nEnter details for employee %d:\n", i + 1);
printf("ID: ");
scanf("%d", &employees[i].id);
printf("Name: ");
scanf(" %[^"]s", employees[i].name); // Read string with spaces
printf("Department: ");
scanf(" %[^"]s", employees[i].department);
printf("Basic Salary: ");
scanf("%f", &employees[i].basic_salary);
}

// Sort employees by salary


sort_employees_by_salary(employees, n);

// Display employee details


printf("\nEmployee details sorted by increasing salary:\n");
for (int i = 0; i < n; i++) {
printf("\nEmployee %d:\n", i + 1);
printf("ID: %d\n", employees[i].id);
printf("Name: %s\n", employees[i].name);
printf("Department: %s\n", employees[i].department);
printf("Basic Salary: %.2f\n", employees[i].basic_salary);
}

return 0;
}

3. Define Structure. Differentiate between Union and Structure. Explain how to declare,

initialize and access the structure elements with example.

Structure in C is a user-defined data type that enables us to store the collection of different data
types. Structures are a way to group several related variables into one place.

Example: student is a tag name. Rollno, name, and marks are the member variables.
struct student
{
int rollno;
char name[20];
int marks[6];
};

struct student s;

s.rollno = 12;
strcpy(s.name, “Ram”);
s.marks = 988;

printf("Roll Number: %d\n", s.rollno);


printf("Name: %s\n", s.name);
printf("Marks: %.2f\n", s.marks);

The Union is a user-defined data type in C language that can contain elements of the different data
types just like structure.

But unlike structures, all the members in the C union are stored in the same memory location. Due to
this, only one member can store data at the given instance.

union un {
int member1;
char member2;
float member3;
};

// driver code
int main()
{
// defining a union variable
union un var1;
// initializing the union member
var1.member1 = 15;
printf("The value stored in member1 = %d", var1.member1);
return 0;
}

4.What is a union? For what kind of applications unions are useful? Explain the unions with

an example.

The Union is a user-defined data type in C language that can contain elements of the different data
types just like structure.

Unlike structures, all the members in the C union are stored in the same memory location. Due to
this, only one member can store data at the given instance.

For below cases unions are used

Memory Optimization:

• Useful when working with embedded systems or memory-constrained environments.

• Example: Storing multiple types of data (like int, float, or char) in a limited space.

Variant Data Handling:

• Efficiently manage different data formats for a variable, such as when implementing
protocols or parsers.

Data Interpretation:
• Used while interpreting the same memory location in different ways.

Hardware Registers:

• Represent hardware registers where multiple fields share the same memory location.

union un {
int member1;
char member2;
float member3;
};

// driver code
int main()
{
// defining a union variable
union un var1;
// initializing the union member
var1.member1 = 15;
printf("The value stored in member1 = %d", var1.member1);
return 0;
}
UNIT-5

FILES

1.Define the Text and Binary files in C. List the importance of text and binary files. Explain

different modes used to work with text and binary files

1. Text files

Text files are the normal .txt files that you can easily create using Notepad or any simple text editors.

When you open those files, you'll see all the contents within the file as plain text. You can easily edit
or delete the contents.

They take minimum effort to maintain, are easily readable, and provide least security and takes
bigger storage space.

2. Binary files

Binary files are mostly the .bin files in your computer.

Instead of storing data in plain text, they store it in the binary form (0's and 1's).

They can hold higher amount of data, are not readable easily and provides a better security than text
files.

The fopen() function is used to create a new file or to open an existing file. This function is available
in stdio.h file

Syntax:

fp= fopen(“filename”, “mode”);

filename is the name of the file to be opened and mode specifies the purpose of opening the file.
Mode can be of following types,

Example:

fp= fopen(“sample.txt”, “w”);

fp= fopen(“sample.txt”, “r”);


2.Write a program to print file contents on the screen.

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

// Function to print file contents


void print_file_contents(const char *filename) {
FILE *file = fopen(filename, "r");
if (file == NULL) {
perror("Error opening file");
return;
}

char ch;
while ((ch = fgetc(file)) != EOF) {
putchar(ch);
}

fclose(file);
}

int main() {
char filename[100];

printf("Enter the name of the file to display its contents: ");


scanf("%s", filename);

print_file_contents(filename);

return 0;
}
3.Write a C program to merge two files into single file.

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

// Function to print file contents


void print_file_contents(const char *input_filename, FILE *ofp) {
char buffer[256];
FILE *file = fopen(input_filename, "r");
if (file == NULL) {
perror("Error opening input file");
return;
}

while (fgets (buffer, sizeof(buffer), file) ) {


fprintf (ofp, "%s", buffer);
}

fclose(file);
}

int main() {
char input_file1[100], input_file2[100], output_file[100];

printf("Enter the name of the input file 1 to read its contents: ");
scanf("%s", input_file1);
printf("Enter the name of the input file 2 to read its contents: ");
scanf("%s", input_file2);
printf("Enter the name of the output file to merge the input file contents: ");
scanf("%s", output_file);

FILE *ofp = fopen(output_file, "w");


if (ofp == NULL) {
perror("Error opening output file");
return;
}
print_file_contents(input_file1, ofp);
print_file_contents(input_file2, ofp);

fclose (ofp);

return 0;
}
4.Write a C Program to copy the contents of file into a second file.

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

// Function to print file contents


void print_file_contents(const char *input_filename, FILE *ofp) {
char buffer[256];
FILE * ifp = fopen(input_filename, "r");
if (ifp == NULL) {
perror("Error opening input file");
return;
}

while (fgets (buffer, sizeof(buffer), ifp) ) {


fprintf (ofp, "%s", buffer);
}

fclose(file);
}

int main() {
char input_file[100], output_file[100];

printf("Enter the name of the input file to read its contents: ");
scanf("%s", input_file);
printf("Enter the name of the output file to copy the input file contents: ");
scanf("%s", output_file);

FILE *ofp = fopen(output_file, "w");


if (ofp == NULL) {
perror("Error opening output file");
return;
}
print_file_contents(input_file, ofp);

fclose (ofp);

return 0;
}
5.Write a c program to append the content in to file and display it.

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

// Function to print file contents


void print_file_contents(const char *input_filename, FILE *ofp) {
char buffer[256];
FILE *ifp = fopen(input_filename, "r");
if (ifp == NULL) {
perror("Error opening input file");
return;
}

while (fgets (buffer, sizeof(buffer), ifp) ) {


fprintf (ofp, "%s", buffer);
}

fclose(file);
}

int main() {
char file1[100], file2[100];

printf("Enter the name of file 1: ");


scanf("%s", file1);
printf("Enter the name of file 2: ");
scanf("%s", file2);

FILE *ofp = fopen(file2, "a");


if (ofp == NULL) {
perror("Error opening file 2 for appending contents");
return;
}
print_file_contents(file1, ofp);

fclose (ofp);

// Reopen the file2 in read-only mode. Pointer will be set to the top.
ofp = fopen(file2, "r");
if (ofp == NULL) {
perror("Error opening file 2 for reading");
return;
}

while (fgets (buffer, sizeof(buffer), ofp) ) {


printf ("%s", buffer);
}
fclose (fp2);

return 0;
}
6.WAP to count no. of characters, lines and words in a file.

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

// Function to print file contents


void print_file_contents(const char *filename) {
int char_count = 0;
int word_count = 0;
int line_count = 0;

FILE *file = fopen(filename, "r");


if (file == NULL) {
perror("Error opening file");
return;
}

char ch;
while ((ch = fgetc(file)) != EOF) {
if (ch == ‘ ‘) word_count++;
if (ch == ‘\n’) line_count++;
char_count++;
}

Printf (“Character count = %d, Word Count = %d, Line count = %d\n”,
char_count, word_count, line_count);
fclose(file);
}

int main() {
char filename[100];

printf("Enter the name of the file: ");


scanf("%s", filename);

print_file_contents(filename);

return 0;
}
7.Write a program to print the records in reverse order.

#include <stdio.h>
struct threeNum
{
int n1, n2, n3;
};

int main()
{
int n;
struct threeNum num;
int total_bytes, records_count;

FILE *fptr;
if ((fptr = fopen("C:\\program.bin","rb")) == NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}

fseek(fptr, 0, 2);
total_bytes = ftell(fptr);
records_count = total_bytes / sizeof(struct threeNum);

for (int i = 0; i < records_count; i++)


{
if (fseek(fptr, - i * sizeof(struct threeNum), 2) == 0) {
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d", num.n1, num.n2, num.n3);
}
else
break;
}
fclose(fptr);
return 0;
}

8.Explain about Random access to files.

File content need not be read in a sequential order. Using the library function fseek, we can place the
pointer position in the file at the specified byte.

Syntax:
int fseek ( file_pointer, displacement, pointer position);
int fseek ( FILE *fp, long num_bytes, int origin ) ;

• file_pointer ---- It is the pointer which points to the file.


• displacement ---- It is positive or negative.
This is the number of bytes which are skipped backward (if negative) or forward( if positive)
from the current position.
This is attached with L because this is a long integer.
• Pointer position:
This sets the pointer position in the file.
1. 0 Beginning of file.
2. 1 Current position
3. 2 End of file
Example:
1) fseek( p,10L,0)
0 means pointer position is on beginning of the file, from this statement pointer position is skipped
10 bytes from the beginning of the file.
2) fseek( p,5L,1)
1 means current position of the pointer position. From this statement pointer position is skipped 5
bytes forward from the current position.
3)fseek(p,-5L,1) From this statement pointer position is skipped 5 bytes backward from the current
position.
9.Define Preprocessor directive. List the uses, advantages and disadvantages of C pre-processor.
Discuss any three types of preprocessor commands.

Preprocessing directives are lines in the program that start with `#'.
The C preprocessor is a tool that processes the source code before the actual compilation starts. It
performs various tasks, including:
1. File Inclusion:
o Includes header files into the program using #include.
o Example: #include<stdio.h>.
2. Macro Definition:
o Defines macros for constants or reusable code snippets using #define.
o Example: #define PI 3.14.
3. Conditional Compilation:
o Compiles specific parts of the program based on conditions using directives like #if,
#ifdef, #ifndef, etc.
o Example: #ifdef DEBUG.
4. Code Optimization:
o Simplifies repetitive tasks by expanding macros before compilation.

Advantages of the C Preprocessor


1. Improved Code Readability:
o By using macros and constants, code becomes easier to read and maintain.
2. Modularity:
o The inclusion of header files encourages modular programming.
3. Conditional Compilation:
o Enables platform-specific or feature-specific code to be included or excluded.
4. Reusability:
o Header files and macros can be reused across multiple programs, reducing
duplication.
5. Efficiency:
o Reduces typing by automating repetitive code patterns through macros.

Disadvantages of the C Preprocessor


1. Debugging Difficulty:
o Errors in preprocessor directives are not easy to trace since they occur before
compilation.
2. Code Bloat:
o Overuse of macros can lead to unnecessarily large and less efficient code.
3. Limited Error Checking:
o The preprocessor does not perform type checking for macros, which can lead to
runtime errors.
4. Reduced Code Clarity:
o Extensive use of macros may make the code harder to understand, especially for
complex expressions.
5. No Namespace:
o Macro names are global and may cause conflicts if reused in other parts of the
program.
#define template_name value:
Substitutes the value, wherever template_name occurs in the source file

#include <File> :
Inserts a particular header from another file in a list of directories specified by include path, then in a
standard list of system directories.

#ifdef macro_name:
Returns true if a macro with macro_name is defined then the block of code will be processed
otherwise not.
10.Explain about File I/O functions and Error Handling in files.

File I/O functions in C allow programs to read from and write to files stored on a disk. These
operations are performed using standard file handling functions from the stdio.h library.

Common File I/O Functions


1. File Opening (fopen):
o Opens a file in a specified mode (e.g., read, write, append).
FILE *fopen(const char *filename, const char *mode);
o Modes:
Mode Description
r Opens for reading.
w Opens for writing (overwrites).
a Opens for appending.
r+ Opens for read and write.
w+ Opens for read/write (overwrites).
a+ Opens for read/append.
2. File Closing (fclose):
o Closes an open file.
int fclose(FILE *stream);
3. File Reading:
o fgetc: Reads a single character.
int fgetc(FILE *stream);
o fgets: Reads a line of text.
char *fgets(char *str, int n, FILE *stream);
o fread: Reads binary data.
size_t fread(void *ptr, size_t size, size_t count, FILE *stream);
4. File Writing:
o fputc: Writes a single character.
int fputc(int char, FILE *stream);
o fputs: Writes a string.
int fputs(const char *str, FILE *stream);
o fwrite: Writes binary data.
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);
5. File Positioning:
o ftell: Returns the current file position.
long ftell(FILE *stream);
o fseek: Moves the file pointer.
int fseek(FILE *stream, long offset, int whence);
o rewind: Resets file pointer to the beginning.
void rewind(FILE *stream);
6. File End Check (feof):
o Checks if the end of a file has been reached.
int feof(FILE *stream);
Error Handling in Files
1. Checking for Errors:
o fopen: Returns NULL if the file cannot be opened.
o ferror: Checks for file-related errors.
int ferror(FILE *stream);
2. Clearing Errors:
o clearerr: Clears the error and EOF flags.
void clearerr(FILE *stream);
3. Error Messages:
o perror: Prints a descriptive error message.
void perror(const char *str);
4. Exiting on Error:
o exit: Terminates the program if a critical error occurs.

Advantages of Proper Error Handling:


• Prevents crashes or undefined behavior.
• Makes debugging easier with descriptive error messages.
• Ensures proper resource cleanup (e.g., closing files).
Let me know if you’d like more examples or clarifications!

Example Program: Reading and Writing with Error Handling


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

int main() {
FILE *file;

// Open file for writing


file = fopen("example.txt", "w");
if (file == NULL) {
perror("Error opening file for writing");
exit(1);
}

fprintf(file, "Hello, world!\n");


fclose(file);

// Open file for reading


file = fopen("example.txt", "r");
if (file == NULL) {
perror("Error opening file for reading");
exit(1);
}
char line[100];
if (fgets(line, sizeof(line), file) == NULL) {
if (feof(file)) {
printf("End of file reached\n");
} else if (ferror(file)) {
perror("Error reading file");
}
} else {
printf("Read from file: %s", line);
}
fclose(file);
return 0;
}
11.Explain Enumeration data type and Macros in preprocessor with examples.

Enumeration Data Type in C


An enumeration (enum) is a user-defined data type in C that consists of a set of named integer
constants. It is primarily used to assign symbolic names to integral values, improving code readability
and maintainability.

Syntax:
enum EnumName {
constant1,
constant2,
constant3,
...
};
• By default, the constants are assigned integer values starting from 0.
• You can also manually assign specific values.
Example:
#include <stdio.h>

enum Days { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY };

int main() {
enum Days today;
today = WEDNESDAY;

if (today == WEDNESDAY) {
printf("It's Wednesday!\n");
}

return 0;
}
Output:
It's Wednesday!
Manually Assigned Values:
enum Colors { RED = 1, GREEN = 2, BLUE = 4, YELLOW = 8 };

Advantages:
1. Improves Readability:
o Makes code easier to understand (e.g., WEDNESDAY vs. 2).
2. Safer Code:
o Prevents unintended assignments to unrelated constants.
3. Maintainability:
o Changing values in the enum reflects throughout the program.
Macros in Preprocessor
A macro is a preprocessor directive in C that defines a name for a constant, expression, or function-
like construct. Macros are replaced by their values or code during the preprocessing stage.
Syntax:
1. Object-like Macro:
#define NAME value
2. Function-like Macro:
#define NAME(parameters) code

Examples:
1. Object-like Macro:
#include <stdio.h>

#define PI 3.14159
#define AREA_OF_CIRCLE(radius) (PI * (radius) * (radius))

int main() {
float radius = 5.0;
printf("Area of the circle: %.2f\n", AREA_OF_CIRCLE(radius));
return 0;
}
Output:
Area of the circle: 78.54

2. Function-like Macro:
#include <stdio.h>
#define SQUARE(x) ((x) * (x))

int main() {
int num = 4;
printf("Square of %d is %d\n", num, SQUARE(num));
return 0;
}
Output:
Square of 4 is 16

Advantages of Macros:
1. Efficiency:
o Avoids the overhead of function calls.
2. Convenience:
o Useful for constants or repetitive code.
3. Portability:
o Changes in the macro definition propagate across the program.

Disadvantages of Macros:
1. No Type Checking:
o May lead to runtime errors due to improper usage.
2. Debugging Difficulty:
o Errors in macros are harder to trace as they are replaced during preprocessing.

Difference Between Enumeration and Macros


Aspect Enumeration Macros
Definition User-defined type with symbolic names. Preprocessor directive for substitution.
Type Safety Ensures type safety. No type safety; raw substitution.
Debugging Easier to debug. Harder to debug.
Scope Limited to the enum. Global across the program.
Usage Used for named integral constants. Used for constants or reusable code.
12.Write a c program to create a user defined header file to find sum, product and greatest of two
numbers.

File name: myHeader.h

int product(int p, int q)


{
return p * q;
}
int sum(int p, int q)
{
return p + q;
}

int greatest(int p, int q)


{
return p>q ? p:q;
}

File name: main.c


#include<stdio.h>
#include “myHeader.h”

int main()
{
int m = 8;
int n = 5;
printf (“Product of %d and %d = %d\n”, product (m,n));
printf (“Sum of %d and %d = %d\n”, sum (m,n));
printf (“Greatest of %d and %d = %d\n”, greatest (m,n));
}
13.Explain about command line arguments in c and write a c program to find sum of n numbers using
command line argument.

Command-line arguments are parameters passed to the main() function when the program is
executed. These arguments allow users to pass input values or options directly to the program from
the command line

int main(int argc, char *argv[])

• argc (argument count): The number of arguments passed to the program.


• argv (argument vector): An array of strings (character pointers) representing the arguments.
1. argv[0]: The name of the program or its invocation path.
2. argv[1] to argv[argc-1]: Arguments passed by the user.
3. Since all arguments in argv are strings, they must be converted to the desired data
type using functions like atoi, atof, etc.

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if (argc < 2)
{
printf("Usage: %s num1 num2 ...\n", argv[0]);
return 1;
}
int sum = 0; // Loop through command-line arguments and compute the sum
for (int i = 1; i < argc; i++) {
sum += atoi(argv[i]); // Convert string to integer
}
printf("The sum of the given numbers is: %d\n", sum);
return 0;
}

You might also like