UNIT:4
1. Explain pointers with example.
Introduction
In C programming, a pointer is a variable that stores the address of another variable. Instead of holding a value directly, it points to the memory location where the value is stored.
Definition of Pointer
A pointer is a variable that stores the memory address of another variable.
Declaration of Pointer
Pointer variables are declared using the * (asterisk) symbol.
Syntax:
datatype *pointer_name;
Example:
int *p;
Address-of Operator (&)
The & operator is used to get the address of a variable.
p = &a;
Dereferencing Operator (*)
The * operator is used to access the value stored at the address held by the pointer.
*p
Example Program
#include <stdio.h>
int main()
{
int a = 10;
int *p;
p = &a;
printf("Value of a = %d\n", a);
printf("Address of a = %u\n", &a);
printf("Value stored in p = %u\n", p);
printf("Value pointed by p = %d\n", *p);
return 0;
}
Output
Value of a = 10
Address of a = 65524
Value stored in p = 65524
Value pointed by p = 10
(Note: Memory address may change every time the program runs.)
Explanation of Output
Value of a shows the value stored in variable a
Address of a shows the memory address of a
Value stored in p is same as address of a
Value pointed by p gives the value at that address, i.e., 10
Advantages of Pointers
Efficient memory usage
Used in dynamic memory allocation
Helps in call by reference
Useful for arrays and strings
Conclusion
Pointers
are an important feature of C language that allow direct access to
memory. They help in writing efficient and powerful programs and are
widely used in advanced programming.
Q.2 Difference between array and pointer.
Difference between Array and Pointer
Array stores multiple values of the same data type.
Pointer stores the address of a variable.
Array name represents the base address of the first element.
Pointer is a separate variable that holds an address.
Array size must be specified at the time of declaration.
Pointer does not require size at declaration.
Memory for an array is allocated at compile time.
Memory for a pointer is allocated at runtime.
Array name is a constant and cannot be changed.
Pointer value can be changed.
Array elements are stored in continuous memory locations.
Pointer can point to any memory location.
Array elements are accessed using index notation like a[i].
Pointer accesses value using dereferencing operator (*p).
Array cannot directly point to another array.
Pointer can point to another pointer or an array.
Array name cannot be incremented or decremented.
Pointer supports arithmetic operations.
Array is mainly used to store data.
Pointer is mainly used to access and manipulate memory.
Q.3 Structure program for student details.
Answer:
A
structure in C is a user-defined data type that is used to store
different types of data items under a single name. It is very useful
when we want to represent a record like student details, employee
information, etc. Using structure improves program readability and data
management.
Definition of Structure:
A structure is defined using the struct keyword followed by structure name and its members.
Structure Program for Student Details:
#include <stdio.h>
#include <conio.h>
struct student {
int rollno;
char name[20];
float marks;
};
void main() {
struct student s;
clrscr();
printf("Enter Roll Number: ");
scanf("%d", &s.rollno);
printf("Enter Name: ");
scanf("%s", s.name);
printf("Enter Marks: ");
scanf("%f", &s.marks);
printf("\n--- Student Details ---\n");
printf("Roll Number : %d\n", s.rollno);
printf("Name : %s\n", s.name);
printf("Marks : %.2f\n", s.marks);
getch();
} Output :
The struct student is declared to store student information.
It contains three members: roll number, name, and marks.
Structure variable s is created inside the main() function.
scanf() is used to accept input values from the user.
printf() is used to display student details.
Structure allows grouping of different data types.
It helps in easy handling of large and complex data.
Conclusion:
Thus, structure in C is an efficient way to store and manage student details using a single variable.
Q.4 Explain Union.
Answer:
A union in C is a user-defined data type that allows us to store different types of data in the same memory location. All members of a union share the same memory space, but only one member can store a value at a time. Union is mainly used when memory optimization is required.
Definition:
Union is defined using the union keyword followed by union name and its members.
Syntax:
union union_name {
data_type member1;
data_type member2;
...
};
Student Union Program
Program Explanation
union student is declared to store roll number, name, and marks.
All members of the union share the same memory location.
Union variable s is declared inside void main().
scanf("%d", &s.rollno) stores roll number in union memory.
scanf("%s", s.name) stores name and overwrites roll number.
scanf("%f", &s.marks) stores marks and overwrites name.
printf() displays only the currently stored value.
Output (Sample Output)
⚠️ Important Note (Very Important for Exam):
In union, all members share the same memory location.
So, only the last entered value is correctly stored.
Previous values get overwritten.
One-line Difference :
Structure: All members have separate memory and all values are stored.
Union: All members share same memory, only one value at a time.
Q.5 Swap two numbers using pointers.
Answer:
Swapping two numbers using pointers means exchanging the values of two variables by using their memory addresses. Pointers allow a function to directly access and modify the actual values of variables.
Program: Swap Two Numbers Using Pointers
#include <stdio.h>
#include <conio.h>
void swap(int *a, int *b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}
void main() {
int x, y;
clrscr();
printf("Enter first number: ");
scanf("%d", &x);
printf("Enter second number: ");
scanf("%d", &y);
printf("\nBefore Swapping:");
printf("\nX = %d, Y = %d", x, y);
swap(&x, &y);
printf("\nAfter Swapping:");
printf("\nX = %d, Y = %d", x, y);
getch();
}
Explanation:
Pointer variables are used to store addresses of variables.
swap() function takes two pointer arguments.
*a and *b access the actual values using dereferencing.
Temporary variable temp is used for swapping.
Values are swapped inside the function.
Changes reflect in main() due to call by reference.
Pointers make swapping possible without returning values.
Output (Sample Output)
Enter first number: 10
Enter second number: 20
Before Swapping:
X = 10, Y = 20
After Swapping:
X = 20, Y = 10
UNIT 5:
Q.1 Explain File Handling and File Modes.
Answer:
File
handling in C is used to store data permanently in a file instead of
storing it temporarily in memory. Files help in storing large data and
allow data to be read and written even after the program is closed. C
provides various functions and file modes to perform file operations.
File Handling in C
File handling is the process of creating, opening, reading, writing, and closing a file using C programs.
In C, file handling is done using a FILE pointer.
Steps in File Handling:
Declare a file pointer.
Open a file using fopen().
Perform file operations (read/write).
Close the file using fclose().
File Pointer Declaration:
FILE *fp;
Opening a File:
fp = fopen("data.txt", "w");
File Modes in C
File modes specify the purpose for which a file is opened.
"r" (Read mode)
"w" (Write mode)
Opens a file for writing.
Creates a new file if it does not exist.
Deletes old data if file already exists.
"a" (Append mode)
"r+" (Read and Write mode)
"w+" (Write and Read mode)
"a+" (Append and Read mode)
Q.2 Program to Write and Read File.
File
handling in C is used to store data permanently in a file. Using file
handling, we can write data into a file and later read the same data
from the file.
Program: Write and Read File in C
#include <stdio.h>
#include <conio.h>
void main() {
FILE *fp;
char ch;
clrscr();
/* Writing data to file */
fp = fopen("data.txt", "w");
if (fp == NULL) {
printf("File cannot be opened");
getch();
return;
}
printf("Enter text (end with #): ");
while ((ch = getchar()) != '#') {
fputc(ch, fp);
}
fclose(fp);
/* Reading data from file */
fp = fopen("data.txt", "r");
printf("\n\nFile Contents:\n");
while ((ch = fgetc(fp)) != EOF) {
printf("%c", ch);
}
fclose(fp);
getch();
}
Explanation:
1. File pointer fp is declared using FILE *.
2. File is opened in write mode using fopen().
3. User input is written to file using fputc().
4. File is closed after writing using fclose().
5. File is reopened in read mode.
6. Data is read using fgetc().
7. File content is displayed on the screen.
Output (Sample Output):
Enter text (end with #): Hello GTU
File Contents:
Hello GTU
Q.3 Explain EOF and feof().
EOF and feof() are used in C file handling to detect the end of a file while reading data from a file.
EOF (End Of File)
EOF is a symbolic constant defined in stdio.h. It indicates that the end of a file has been reached or an error has occurred during file reading.
Use of EOF:
Returned by file reading functions like fgetc(), fscanf(), etc.
Helps in stopping the read operation when file ends.
Example:
while ((ch = fgetc(fp)) != EOF) {
printf("%c", ch);
}
feof() Function
feof() is a file handling function used to check whether the end of a file has been reached or not.
Syntax:
feof(FILE *fp);
Use of feof():
Example:
while (!feof(fp)) {
ch = fgetc(fp);
printf("%c", ch);
}
Explanation Points
EOF stands for End Of File.
EOF is a macro defined in stdio.h.
It is used as a condition to stop reading a file.
feof() is a function that checks end of file status.
feof() returns non-zero when file ends.
EOF is compared with returned value of file functions.
Both are used to control file reading operations.
Q.4 Explain Bitwise Operators
Bitwise operators in C are used to perform operations on individual bits
of integer data types. They are very useful in low-level programming,
such as device drivers, encryption, and optimization tasks.
Types of Bitwise Operators
AND (&)
Performs logical AND on each pair of bits.
Result bit is 1 only if both bits are 1.
Example: 5 & 3 → 0101 & 0011 = 0001 → Result = 1
OR (|)
Performs logical OR on each pair of bits.
Result bit is 1 if any one of the bits is 1.
Example: 5 | 3 → 0101 | 0011 = 0111 → Result = 7
XOR (^)
Performs logical XOR on each pair of bits.
Result bit is 1 if bits are different.
Example: 5 ^ 3 → 0101 ^ 0011 = 0110 → Result = 6
Complement (~)
Left Shift (<<)
Shifts bits to the left by specified positions.
Fills rightmost bits with 0.
Example: 5 << 1 → 0101 << 1 = 1010 → Result = 10
Right Shift (>>)
Shifts bits to the right by specified positions.
Fills leftmost bits with 0 (for unsigned numbers).
Example: 5 >> 1 → 0101 >> 1 = 0010 → Result = 2
Example Program
#include <stdio.h>
#include <conio.h>
void main() {
int a = 5, b = 3;
clrscr();
printf("a = %d, b = %d\n", a, b);
printf("a & b = %d\n", a & b);
printf("a | b = %d\n", a | b);
printf("a ^ b = %d\n", a ^ b);
printf("~a = %d\n", ~a);
printf("a << 1 = %d\n", a << 1);
printf("a >> 1 = %d\n", a >> 1);
getch();
}
Explanation
Bitwise operators work on binary representation of numbers.
AND (&) gives 1 only if both bits are 1.
OR (|) gives 1 if any bit is 1.
XOR (^) gives 1 if bits are different.
Complement (~) flips all bits.
Left shift (<<) multiplies number by 2^n.
Right shift (>>) divides number by 2^n (for positive integers).
Output of Bitwise Operators :
Q.5 Explain C Preprocessor Directives
C preprocessor directives are instructions given to the compiler
to process the program before actual compilation. They help in
including files, defining constants, macros, and conditional
compilation. Preprocessor directives start with # and are handled by the preprocessor, not by the compiler.
Types of Preprocessor Directives
#include
#define
#undef
#ifdef / #ifndef / #endif
Used for conditional compilation.
#ifdef compiles code if the macro is defined.
#ifndef compiles code if the macro is not defined.
Example:
#define FLAG
#ifdef FLAG
printf("FLAG is defined");
#endif
#if / #elif / #else / #endif
#error
#pragma
Explanation Points
Preprocessor directives are handled before compilation.
They start with # and have no semicolon.
#include adds header files for standard functions.
#define is used to create constants or macros.
Conditional directives like #ifdef and #if control compilation.
#error stops compilation intentionally if needed.
Preprocessor helps in code reuse, readability, and modular programming.
Conclusion
C
preprocessor directives are instructions to the compiler to process
code before compilation. They are used for including files, defining
constants, macros, and controlling conditional compilation.
Comments
Post a Comment