C LAN. UNIT 4&5

 

 C LAN. UNIT 4&5

 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

  1. Efficient memory usage

  2. Used in dynamic memory allocation

  3. Helps in call by reference

  4. 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 

  1. Array stores multiple values of the same data type.
    Pointer stores the address of a variable.

  2. Array name represents the base address of the first element.
    Pointer is a separate variable that holds an address.

  3. Array size must be specified at the time of declaration.
    Pointer does not require size at declaration.

  4. Memory for an array is allocated at compile time.
    Memory for a pointer is allocated at runtime.

  5. Array name is a constant and cannot be changed.
    Pointer value can be changed.

  6. Array elements are stored in continuous memory locations.
    Pointer can point to any memory location.

  7. Array elements are accessed using index notation like a[i].
    Pointer accesses value using dereferencing operator (*p).

  8. Array cannot directly point to another array.
    Pointer can point to another pointer or an array.

  9. Array name cannot be incremented or decremented.
    Pointer supports arithmetic operations.

  10. 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 :

Enter Roll Number: 101 Enter Name: Pravina Enter Marks: 78.50 --- Student Details --- Roll Number : 101 Name : Pravina
Marks : 78.50

Explanation:
  1. The struct student is declared to store student information.

  2. It contains three members: roll number, name, and marks.

  3. Structure variable s is created inside the main() function.

  4. scanf() is used to accept input values from the user.

  5. printf() is used to display student details.

  6. Structure allows grouping of different data types.

  7. 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

#include <stdio.h> #include <conio.h> union student { int rollno; char name[20]; float marks; }; void main() { union student s; clrscr(); printf("Enter Roll Number: "); scanf("%d", &s.rollno); printf("Roll Number : %d\n", s.rollno); printf("\nEnter Name: "); scanf("%s", s.name); printf("Name : %s\n", s.name); printf("\nEnter Marks: "); scanf("%f", &s.marks); printf("Marks : %.2f\n", s.marks); getch(); }

Program Explanation

  1. union student is declared to store roll number, name, and marks.

  2. All members of the union share the same memory location.

  3. Union variable s is declared inside void main().

  4. scanf("%d", &s.rollno) stores roll number in union memory.

  5. scanf("%s", s.name) stores name and overwrites roll number.

  6. scanf("%f", &s.marks) stores marks and overwrites name.

  7. printf() displays only the currently stored value.


Output (Sample Output)

Enter Roll Number: 101 Roll Number : 101 Enter Name: Pravina Name : Pravina Enter Marks: 78.50 Marks : 78.50

⚠️ 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:

  1. Pointer variables are used to store addresses of variables.

  2. swap() function takes two pointer arguments.

  3. *a and *b access the actual values using dereferencing.

  4. Temporary variable temp is used for swapping.

  5. Values are swapped inside the function.

  6. Changes reflect in main() due to call by reference.

  7. 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:

  1. Declare a file pointer.

  2. Open a file using fopen().

  3. Perform file operations (read/write).

  4. 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.

  1. "r" (Read mode)

    • Opens an existing file for reading.

    • File must exist.

    • Data cannot be modified.

  2. "w" (Write mode)

    • Opens a file for writing.

    • Creates a new file if it does not exist.

    • Deletes old data if file already exists.

  3. "a" (Append mode)

    • Opens a file for appending data.

    • New data is added at the end of file.

    • Old data is not deleted.

  4. "r+" (Read and Write mode)

    • Opens an existing file for both reading and writing.

    • File must exist.

  5. "w+" (Write and Read mode)

    • Opens a file for reading and writing.

    • Creates a new file or overwrites existing file.

  6. "a+" (Append and Read mode)

    • Opens a file for reading and appending.

    Data is added at the end of the file.

    Common File Handling Functions:

  • fopen() – opens a file
  • fclose() – closes a file
  • fprintf() – writes formatted data
  • fscanf() – reads formatted data
  • fgetc() / fputc() – read/write a character

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():

  • Returns non-zero value if end of file is reached.

  • Returns zero if end of file is not reached.

Example:

while (!feof(fp)) {
    ch = fgetc(fp);
    printf("%c", ch);
}

Explanation Points

  1. EOF stands for End Of File.

  2. EOF is a macro defined in stdio.h.

  3. It is used as a condition to stop reading a file.

  4. feof() is a function that checks end of file status.

  5. feof() returns non-zero when file ends.

  6. EOF is compared with returned value of file functions.

  7. 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

  1. AND (&)

    • Performs logical AND on each pair of bits.

    • Result bit is 1 only if both bits are 1.

    • Example: 5 & 30101 & 0011 = 0001 → Result = 1

  2. OR (|)

    • Performs logical OR on each pair of bits.

    • Result bit is 1 if any one of the bits is 1.

    • Example: 5 | 30101 | 0011 = 0111 → Result = 7

  3. XOR (^)

    • Performs logical XOR on each pair of bits.

    • Result bit is 1 if bits are different.

    • Example: 5 ^ 30101 ^ 0011 = 0110 → Result = 6

  4. Complement (~)

    • Inverts all bits of a number.

    • Example: ~50101 → 1010 (for 4-bit representation)

  5. Left Shift (<<)

    • Shifts bits to the left by specified positions.

    • Fills rightmost bits with 0.

    • Example: 5 << 10101 << 1 = 1010 → Result = 10

  6. Right Shift (>>)

    • Shifts bits to the right by specified positions.

    • Fills leftmost bits with 0 (for unsigned numbers).

    • Example: 5 >> 10101 >> 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

  1. Bitwise operators work on binary representation of numbers.

  2. AND (&) gives 1 only if both bits are 1.

  3. OR (|) gives 1 if any bit is 1.

  4. XOR (^) gives 1 if bits are different.

  5. Complement (~) flips all bits.

  6. Left shift (<<) multiplies number by 2^n.

  7. Right shift (>>) divides number by 2^n (for positive integers).

Output of Bitwise Operators :

a = 5, b = 3 a & b = 1 a | b = 7 a ^ b = 6 ~a = -6 a << 1 = 10 a >> 1 = 2

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

  1. #include

    • Used to include header files in a program.

    • Example: #include <stdio.h> or #include "myfile.h"

  2. #define

    • Used to define constants or macros.

    • Example:

      #define PI 3.14
      #define SQUARE(x) ((x)*(x))
      
  3. #undef

    • Used to undefine a macro.

    • Example: #undef PI

  4. #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
      
  5. #if / #elif / #else / #endif

    • Used for conditional compilation based on expressions.

    • Example:

      #define VALUE 10
      #if VALUE > 5
          printf("Value is greater than 5");
      #else
          printf("Value is 5 or less");
      #endif
      
  6. #error

    • Generates a compilation error intentionally.

    • Example: #error "This file cannot be compiled"

  7. #pragma

    • Provides special instructions to the compiler.

    • Example: #pragma once (ensures header file is included only once)


Explanation Points

  1. Preprocessor directives are handled before compilation.

  2. They start with # and have no semicolon.

  3. #include adds header files for standard functions.

  4. #define is used to create constants or macros.

  5. Conditional directives like #ifdef and #if control compilation.

  6. #error stops compilation intentionally if needed.

  7. 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

Popular Posts