pcl pyq(unit3)
pcl pyq(unit3)
HANDLING)
POINTERS
Declaring a Pointer:
data_type *pointer_name;
Here, data_type specifies the data type of the variable whose address the pointer will hold.
Example:
int *ptr;
This declaration creates a pointer named ptr that can hold the address of an integer variable.
Initializing a Pointer:
int x = 10;
int *ptr = &x;
This allocates memory for an integer and assigns its address to ptr.
Accessing the Value Pointed to by a Pointer:
To access the value stored at the memory location pointed to by a pointer, you use the *
operator again, but in a different context.
#include <stdio.h>
int main() {
int value = 10; // Original variable
return 0;
}
Key Points:
• Addition/Subtraction of Integers:
Adding an integer to a pointer moves it forward in memory by a specific number of
o
elements.
o Subtracting an integer moves it backward.
o The amount of movement depends on the size of the data type the pointer points to.
(e.g., adding 1 to an integer pointer moves it 4 bytes if an integer is 4 bytes)
• Comparison of Pointers:
o You can compare pointers using relational operators (==, <, >) only if they point to
elements within the same array or memory block allocated with malloc.
o Comparing pointers from different memory areas is meaningless.
Example:
Declaration:
data_type (*ptr)[size];
Here:
#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50};
int (*ptr)[5]; // Pointer to an array of 5 integers
return 0;
}
Example:
#include <stdio.h>
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
return 0;
}
Example:
#include <stdio.h>
int main() {
int matrix[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11,
12}};
return 0;
}
6Q. Explain (a)Void/Generic pointer (b)
Ans.(a) A void pointer, declared as void *, is a special type of pointer that can point to any
data type. It doesn't have a specific type associated with it, making it highly flexible but
requiring careful handling.
Declaration:
void *ptr;
Assigning Values:
You can assign the address of any variable to a void pointer, regardless of its data type.
However, to access the value stored at the address, you need to cast the void pointer to the
appropriate data type.
Example:
#include <stdio.h>
int main() {
int num = 10;
char ch = 'A';
float f = 3.14;
void *ptr;
return 0;
}
• Purpose: Used to access the value stored at a memory location pointed to by a pointer.
• Syntax: *pointer_name
Example:
int x = 10;
int *ptr = &x; // ptr stores the address of x
int x = 10;
int *ptr = &x; // ptr stores the address of x
Ans. In C, a structure (often shortened to struct) is a user-defined data type that groups
together variables of different data types under a single name. This allows you to create
complex data objects that represent real-world entities or concepts.
Benefits of Structures:
• Data Organization: Structures help organize related data into a single unit, improving
code readability and maintainability.
• Data Packing: You can group variables of different sizes efficiently in memory since C
doesn't have automatic memory padding like some other languages.
Declaring a Structure:
The struct keyword is used to define a structure. You specify a structure name and a list of
member variables enclosed within curly braces {}.
Example:
struct Person {
char name[50]; // Character array to store name
int age; // Integer to store age
float salary; // Float to store salary
};
allocation, a union allocates memory for the largest member and all other members share
this memory space.
Declaration:
union UnionName {
data_type1 member1;
data_type2 member2;
// ...
};
Example:
union Data {
int i;
float f;
char str[20];
};
How it Works:
#include <stdio.h>
int main() {
union Data data;
data.i = 10;
printf("Integer value: %d\n", data.i);
data.f = 220.5;
printf("Float value: %f\n", data.f);
return 0;
}
1. Pass by Value:
In this method, a copy of the entire structure is passed to the function. Any modifications
1
made to the structure within the function will not affect the original structure in the calling
function.2
#include <stdio.h>
struct Student {
char name[50];
int age;
float marks;
};
int main() {
struct Student student1 = {"Alice", 20, 95.5};
printStudentDetails(student1);
return 0;
}
2. Pass by Reference:
In this method, the address of the structure is passed to the function. This allows the
function to modify the original structure directly.
#include <stdio.h>
struct Student {
char name[50];
int age;
float marks;
};
int main() {
struct Student student1 = {"Alice", 20, 95.5};
printStudentDetails(&student1);
return 0;
}
Benefits:
data_type *ptr_name;
Here:
• data_type: The data type of the structure the pointer points to.
• ptr_name: The name of the pointer variable.
Example:
struct Student {
char name[50];
int age;
};
int main() {
struct Student student1 = {"Alice", 20};
struct Student *ptr; // Pointer to a Student structure
return 0;
}
Example:
struct Address {
char street[50];
char city[30];
char state[20];
int pincode;
};
struct Student {
char name[50];
int roll_no;
struct Address address; // Nested structure};
In this example:
• struct Address defines a structure to hold address information.
• struct Student defines a structure to hold student information, including an Address
structure as a member.
Accessing Members of Nested Structures:
To access members of a nested structure, you use the dot (.) operator multiple times:
Declaration:
Here:
struct Student {
char name[50];
int roll_no;
float marks;
};
int main() {
struct Student students[3]; // Array of 3 Student structures
// Assign values to the first student
strcpy(students[0].name, "Alice");
students[0].roll_no = 10;
students[0].marks = 95.5;
return 0;
}
Example:
struct Student {
char name[50];
int roll_no;
int marks[5]; // Array of 5 marks
};
int main() {
struct Student student1;
strcpy(student1.name, "Alice");
student1.roll_no = 10;
student1.marks[0] = 85;
student1.marks[1] = 92;
// ... and so on
return 0;
}
8Q. Differentiation
➢ Structure Vs Union
➢ Array Vs Structure
Ans.
(a)
Memory Each member has its All members share the same memory
Allocation own memory allocation. location.
Size Size is the sum of the Size is equal to the size of its largest
sizes of its members. member.
Use Cases Organizing related data Storing different data types in the same
into a single unit. memory location, but only one at a
time.
(b)
Flexibility Less flexible, can only store More flexible, can store elements
elements of the same type of different types
Feature Array Structure
FILE HANDLING
1. Data Persistence:
o Files allow us to save data even after the program terminates. This is crucial for
1
applications that need to store information for future use, such as user preferences,
game progress, or financial records.
2. Data Sharing:
o Files can be easily shared and transferred between different systems, enabling
collaboration and data exchange.
3. Efficient Data Handling:
o By storing large amounts of data in files, we can avoid the need to re-enter it each
time the program runs. This saves time and effort, especially for repetitive tasks.
2
File Handling in C
1. Opening a File:
• fopen() function is used to open a file. It takes two arguments: the filename and the mode
of opening.
FILE *fp = fopen("myfile.txt", "r"); // Open for reading
3. Writing to a File:
• fputc(), fprintf(), and fputs() functions are used to write data to a file.
4. Closing a File:
• "r": Opens a file for reading. If the file doesn't exist, the function returns NULL. This
mode is for existing files you want to read from.
• "rb": Opens a file for reading in binary mode. Similar to "r", but treats the file as a
stream of bytes (important for non-text files).
Write Modes:
• "w": Creates a new file for writing. If the file exists, its content is overwritten. Use
this to create a new file or completely rewrite an existing one.
• "wb": Creates a new file for writing in binary mode. Similar to "w", but for binary
data.
Append Modes:
• "a": Opens a file for appending. If the file doesn't exist, it creates a new one. Data is
written to the end of the file. Use this to add content to an existing file without
overwriting it.
• "ab": Opens a file for appending in binary mode. Similar to "a", but for binary data.
Read-Write Modes:
• "r+": Opens an existing file for both reading and writing. If the file doesn't exist, the
function returns NULL. Use this for existing files where you might need to read and
modify content.
• "rb+": Opens an existing file for both reading and writing in binary mode. Similar to
"r+", but for binary data.
• "w+": Creates a new file for both reading and writing. If the file exists, its content is
overwritten. Use this to create a new file or completely rewrite an existing one,
allowing both read and write access.
• "wb+": Creates a new file for both reading and writing in binary mode. Similar to
"w+", but for binary data.
• "a+": Opens an existing file for both reading and appending. If the file doesn't exist,
it creates a new one. Data is written to the end of the file, allowing both reading and
appending.
• "ab+": Opens an existing file for both reading and appending in binary mode. Similar
to "a+", but for binary data.
4Q. Explain the concept of Reading and Writing using Character I/O Functions with
example.
Ans. 1. Reading Characters:
• getchar() function:
o Reads a single character from the standard input (usually keyboard). 1
char ch = getchar();
printf("You entered: %c\n", ch);
• getc() function:
o Similar to getchar(), but takes a file pointer as an argument.
o Reads a character from the specified file stream. 2
2. Writing Characters:
• putchar() function:
o Writes a single character to the standard output (usually console). 3
char ch = 'A';
putchar(ch); // Prints 'A' to the console
• putc() function:
o Similar to putchar(), but takes a file pointer as an argument.
o Writes a character to the specified file stream.
o Takes the character as an int (ASCII value).
5Q. Explain the concept of Reading and Writing using String I/O Functions
Ans. 1. Reading Strings:
• gets() function:
o Reads a string from the standard input (usually the keyboard).
o Stores the string in a character array.
o Note: This function is deprecated due to security vulnerabilities. It's recommended to
use safer alternatives like fgets().
char str[100];
printf("Enter a string: ");
gets(str);
printf("You entered: %s\n", str);
• fgets() function:
o Reads a line of text from a file or standard input.
o Takes a character array, maximum number of characters to read, and a file pointer as
arguments.
o Returns the string read or NULL on error or end-of-file.
char str[100];
printf("Enter a string: ");
fgets(str, 100, stdin);
printf("You entered: %s\n", str);
2. Writing Strings:
• puts() function:
o Writes a string to the standard output (usually the console), followed by a newline
character.
o Takes a string as an argument.
char str[] = "Hello, world!";
puts(str);
• fputs() function:
o Writes a string to a file.
o Takes a string and a file pointer as arguments.
FILE *fp = fopen("output.txt", "w");
if (fp != NULL) {
char str[] = "This is a line of text.";
fputs(str, fp);
fclose(fp);
} else {
printf("Error opening file!\n");
}
6Q. Explain the concept of Reading and Writing using integer I/O Functions.
Ans.
1. Reading Integers:
• scanf() function:
o Reads formatted input from the standard input (usually the keyboard).
o Takes a format specifier and a pointer to the variable where the input will be stored.
o For integers, use the %d format specifier.
int num;
printf("Enter an integer: ");
scanf("%d", &num);
printf("You entered: %d\n", num);
• fscanf() function:
o Reads formatted input from a file.
o Similar to scanf(), but takes a file pointer as an additional argument.
2. Writing Integers:
• printf() function:
o Prints formatted output to the standard output (usually the console).
o Takes a format specifier and the value to be printed.
o For integers, use the %d format specifier.
• fprintf() function:
o Writes formatted output to a file.
o Similar to printf(), but takes a file pointer as an additional argument.
FILE *fp = fopen("output.txt", "w");
if (fp != NULL) {
int num = 123;
fprintf(fp, "The number is: %d\n", num);
fclose(fp);
} else {
printf("Error opening file!\n");
}
7Q. Explain the concept of Reading and Writing using formatted I/O Functions.
Ans. 1. Reading Formatted Input:
• scanf() function:
o Reads formatted input from the standard input (usually the keyboard).
o Takes a format string and pointers to variables where the input will be stored.
o The format string specifies the expected input format using format specifiers.
int age;
float salary;
char name[50];
• printf() function:
o Prints formatted output to the standard output (usually the console).
o Takes a format string and values to be printed.
o The format string specifies how the values should be formatted.
• %d: Integer
• %f: Floating-point number
• %c: Character
• %s: String
• %x: Hexadecimal integer
• %o: Octal integer
8Q. Explain the concept of Reading and Writing using Unformatted I/O Functions.
Ans. 1. Reading Characters:
• getchar() function:
o Reads a single character from the standard input (usually the keyboard).
o Returns the character as an int (ASCII value) or EOF on end-of-file.
char ch = getchar();
printf("You entered: %c\n", ch);
• getc() function:
o Similar to getchar(), but takes a file pointer as an argument.
o Reads a single character from the specified file stream.
o Returns the character read or EOF on end-of-file or error.
2. Writing Characters:
• putchar() function:
o Writes a single character to the standard output (usually the console).
o Takes the character as an int (ASCII value).
char ch = 'A';
putchar(ch); // Prints 'A' to the console
• putc() function:
o Similar to putchar(), but takes a file pointer as an argument.
o Writes a single character to the specified file stream.
o Takes the character as an int (ASCII value).
1. feof():
2. ferror():
3. clearerr():
4. fseek():
5. ftell():
1. fseek():
2. ftell():
• Returns the current position of the file pointer, measured in bytes from the beginning of
the file.
• This can be useful for saving the current position and returning to it later, or for
determining the size of a file.
Example:
3. rewind():
rewind(fp);
Ans.(a) Header Files: Header files in C are files with the .h extension that contain function
declarations, macro definitions, and variable declarations. They are used to share code and
definitions between different source files in a C program.
(b) File Pointer: A file pointer in C is a variable that points to a file. It is used to perform file
operations like reading, writing, and seeking.
(c) EOF (End-of-File)
In C programming, EOF is a special constant that represents the end-of-file condition. It's
often used in file input operations to determine when the end of a file has been reached.
12Q. Differentiation
➢ Stream oriented Vs System oriented data files
➢ Text file Vs Binary file
➢ fputc() vs fgetc()
➢ fputs() vs fgets()
➢ fprintf() vs fscanf()
➢ argc Vs argv[]
Ans.(a)
Efficiency Less efficient for large data More efficient for large data
File Extension .txt, .c, .h, etc. .bin, .exe, .jpg, etc.
Efficiency Less efficient for large data More efficient for large data
(c)
Parameters (const char *str, FILE (char *str, int size, FILE *stream)
*stream)
(e)
Arguments File pointer, format string, and File pointer, format string, and
values to be printed pointers to variables to store input
Example int main(int argc, char argv[0] stores the program name, argv[1]
*argv[]) stores the first argument, and so on.