0% found this document useful (0 votes)
13 views

FOP assignment_3

The document explains various concepts in C programming, including pointers, call by value vs. call by reference, pointers with arrays, function pointers, dynamic memory allocation, user-defined data types (structures and unions), nested structures, and file types. It provides definitions, syntax, and examples for each concept, illustrating how they are implemented in C. Key differences between structures and unions, as well as the use of nested structures, are also highlighted.

Uploaded by

Piyaa Rathod
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

FOP assignment_3

The document explains various concepts in C programming, including pointers, call by value vs. call by reference, pointers with arrays, function pointers, dynamic memory allocation, user-defined data types (structures and unions), nested structures, and file types. It provides definitions, syntax, and examples for each concept, illustrating how they are implemented in C. Key differences between structures and unions, as well as the use of nested structures, are also highlighted.

Uploaded by

Piyaa Rathod
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

1. What is pointer? What is pointer to pointer? How to implement it?

A pointer in C is a variable that stores the memory address of another variable.


Pointers are used for various purposes, such as dynamic memory allocation, arrays,
and function arguments.
Pointer to Pointer (Double Pointer)
A pointer to a pointer (or double pointer) is a pointer that stores the address of
another pointer. This is useful when you need to manipulate the address of a pointer
or create complex data structures like multi-dimensional arrays.

#include <stdio.h>

int main() {
int var = 789;
int *ptr; // Single pointer
int **d_ptr; // Double pointer

ptr = &var; // ptr stores the address of var


d_ptr = &ptr; // d_ptr stores the address of ptr

// Printing the values


printf("Value of var = %d\n", var);
printf("Value of var using single pointer = %d\n", *ptr);
printf("Value of var using double pointer = %d\n", **d_ptr);

return 0;
}
2. Difference between call by value and call by reference. Explain with
an example.

Call by Value vs. Call by Reference


Call by Value
• Definition: The function receives a copy of the argument’s value.
• Effect: Changes made to the parameter inside the function do not affect the original
argument.
• Use Case: When you want to ensure the original data remains unchanged.
Example:
#include <stdio.h>

void swap(int x, int y) {


int temp = x;
x = y;
y = temp;
printf("Inside function: x = %d, y = %d\n", x, y);
}

int main() {
int a = 10, b = 20;
swap(a, b);
printf("In main: a = %d, b = %d\n", a, b);
return 0;
}

Output:
Inside function: x = 20, y = 10
In main: a = 10, b = 20
Call by Reference
• Definition: The function receives a reference (address) to the argument.
• Effect: Changes made to the parameter inside the function affect the original
argument.
• Use Case: When you need to modify the original data.
Example:
#include <stdio.h>

void swap(int *x, int *y) {


int temp = *x;
*x = *y;
*y = temp;
printf("Inside function: x = %d, y = %d\n", *x, *y);
}

int main() {
int a = 10, b = 20;
swap(&a, &b);
printf("In main: a = %d, b = %d\n", a, b);
return 0;
}
Output:
Inside function: x = 20, y = 10
In main: a = 20, b = 10

Summary

• Call by Value: Copies the value of the argument. Changes inside the function do
not affect the original variable.
• Call by Reference: Passes the address of the argument. Changes inside the
function affect the original variable.

3. Explain how pointer works with array.

Basics of Pointers and Arrays


• Array Name as a Pointer: The name of an array acts as a pointer to its first element.
For example, if you have an array int arr[5], arr is equivalent to &arr[0].
• Pointer Arithmetic: You can use pointers to traverse an array. For example, *(arr +
i) is equivalent to arr[i].
Example
#include <stdio.h>

int main() {
int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr; // ptr points to the first element of arr

// Accessing array elements using pointer


for (int i = 0; i < 5; i++) {
printf("Element %d: %d\n", i, *(ptr + i));
}

return 0;
}

Advanced Example: Pointer to an Array


You can also have a pointer to an entire array. This is useful for multi-dimensional
arrays.
#include <stdio.h>

int main() {
int arr[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
int (*ptr)[4] = arr; // ptr is a pointer to an array of 4 integers

// Accessing elements using pointer to an array


for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
printf("Element [%d][%d]: %d\n", i, j, ptr[i][j]);
}
}

return 0;
}

Summary

• Array Name: Acts as a pointer to the first element.


• Pointer Arithmetic: Allows traversal of the array.
• Pointer to an Array: Useful for multi-dimensional arrays.

4. Explain pointer to the function.

A pointer to a function in C is a variable that stores the address of a function. This


allows you to call the function indirectly and is useful for implementing callback
functions, passing functions as arguments, and creating arrays of functions.
How to Declare and Use a Function Pointer
#include <stdio.h>

// A simple function that takes an integer and prints it


void printNumber(int num) {
printf("Number: %d\n", num);
}

int main() {
// Declare a function pointer
void (*funcPtr)(int);
// Assign the address of the function to the pointer
funcPtr = &printNumber;

// Call the function using the pointer


funcPtr(5);

return 0;
}

Advanced Example: Array of Function Pointers


Function pointers can also be used to create arrays of functions, which is useful for
implementing a menu system or a set of operations.
#include <stdio.h>

// Functions for different operations


void add(int a, int b) {
printf("Addition: %d\n", a + b);
}

void subtract(int a, int b) {


printf("Subtraction: %d\n", a - b);
}

void multiply(int a, int b) {


printf("Multiplication: %d\n", a * b);
}

int main() {
// Array of function pointers
void (*operations[])(int, int) = {add, subtract, multiply};

int choice, a = 10, b = 5;

printf("Enter choice (0 for add, 1 for subtract, 2 for multiply): ");


scanf("%d", &choice);

if (choice >= 0 && choice < 3) {


// Call the chosen function
operationschoice;
} else {
printf("Invalid choice\n");
}

return 0;
}

Summary
• Function Pointer: Stores the address of a function.
• Usage: Allows indirect function calls, passing functions as arguments, and creating
arrays of functions.

5. What is dynamic memory allocation? Explain functions available for


implementation of DMA.

Dynamic Memory Allocation (DMA)


Dynamic Memory Allocation (DMA) in C allows you to allocate memory during runtime,
which is particularly useful when the amount of memory required cannot be determined
before execution. This flexibility is essential for creating data structures like linked lists,
trees, and dynamic arrays.

Functions for Dynamic Memory Allocation


C provides several standard library functions for dynamic memory allocation, all of
which are declared in the <stdlib.h> header file:

1. malloc()
2. calloc()
3. realloc()
4. free()

1. malloc()

• Purpose: Allocates a single block of memory of a specified size.


• Syntax: ptr = (castType*) malloc(size);
• Example:
• int *ptr;
• ptr = (int*) malloc(10 * sizeof(int)); // Allocates memory for 10
integers
• if (ptr == NULL) {
• printf("Memory allocation failed\n");
• }
2. calloc()

• Purpose: Allocates multiple blocks of memory, each of the same size, and
initializes all bytes to zero.
• Syntax: ptr = (castType*) calloc(num, size);
• Example:
• int *ptr;
• ptr = (int*) calloc(10, sizeof(int)); // Allocates memory for 10
integers and initializes them to 0
• if (ptr == NULL) {
• printf("Memory allocation failed\n");
• }
3. realloc()

• Purpose: Reallocates memory blocks to a new size. It can expand or shrink the
existing memory block.
• Syntax: ptr = (castType*) realloc(ptr, newSize);
• Example:
• int *ptr;
• ptr = (int*) malloc(10 * sizeof(int)); // Initial allocation
• ptr = (int*) realloc(ptr, 20 * sizeof(int)); // Reallocates memory to
hold 20 integers
• if (ptr == NULL) {
• printf("Memory reallocation failed\n");
• }
4. free()

• Purpose: Frees the dynamically allocated memory, making it available for future
allocations.
• Syntax: free(ptr);
• Example:
• int *ptr;
• ptr = (int*) malloc(10 * sizeof(int)); // Allocates memory
• if (ptr != NULL) {
• free(ptr); // Frees the allocated memory
• }

Summary

• malloc(): Allocates a single block of memory.


• calloc(): Allocates multiple blocks and initializes them to zero.
• realloc(): Changes the size of an allocated memory block.
• free(): Frees the allocated memory.

6. Explain User define datatype structure and union with syntax and
example.

User-Defined Data Types: Structure and Union


Structure
A structure in C is a user-defined data type that allows you to combine data items of
different kinds. Structures are useful for grouping related variables together, such as the
properties of a person or a book.
Syntax:
struct StructureName {
dataType member1;
dataType member2;
// more members
};

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

struct Person {
char name[50];
int age;
float height;
};

int main() {
struct Person person1;

// Assigning values to members


strcpy(person1.name, "Alice");
person1.age = 30;
person1.height = 5.5;

// Accessing members
printf("Name: %s\n", person1.name);
printf("Age: %d\n", person1.age);
printf("Height: %.1f\n", person1.height);
return 0;
}

Union
A union in C is similar to a structure, but it allows storing different data types in the
same memory location. This means that at any given time, only one of the union’s
members can hold a value.
Syntax:
union UnionName {
dataType member1;
dataType member2;
// more members
};

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

union Data {
int i;
float f;
char str[20];
};

int main() {
union Data data;

// Assigning and accessing integer value


data.i = 10;
printf("Data.i: %d\n", data.i);

// Assigning and accessing float value


data.f = 3.14;
printf("Data.f: %f\n", data.f);

// Assigning and accessing string value


strcpy(data.str, "Hello");
printf("Data.str: %s\n", data.str);

return 0;
}

7. Mention the difference between union and structure.


Difference Between Structure and Union
Structures and unions are both user-defined data types in C that allow you to store
multiple data types together. However, they have some key differences:
Memory Allocation

• Structure: Each member has its own memory location. The total memory
required is the sum of the sizes of all members.
• Union: All members share the same memory location. The total memory required
is equal to the size of the largest member.

Storage

• Structure: Can store different values in each member simultaneously.


• Union: Can store a value in only one member at a time. Assigning a value to one
member will overwrite the previous value.

Syntax

• Structure:
• struct StructureName {
• dataType member1;
• dataType member2;
• // more members
• };
• Union:
• union UnionName {
• dataType member1;
• dataType member2;
• // more members
• };

Example
Structure:
#include <stdio.h>
#include <string.h>

struct Person {
char name[50];
int age;
float height;
};

int main() {
struct Person person1;
strcpy(person1.name, "Alice");
person1.age = 30;
person1.height = 5.5;

printf("Name: %s\n", person1.name);


printf("Age: %d\n", person1.age);
printf("Height: %.1f\n", person1.height);

return 0;
}

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

union Data {
int i;
float f;
char str[20];
};

int main() {
union Data data;
data.i = 10;
printf("Data.i: %d\n", data.i);

data.f = 3.14;
printf("Data.f: %f\n", data.f);

strcpy(data.str, "Hello");
printf("Data.str: %s\n", data.str);

return 0;
}

Key Differences
1. Memory Usage:
o Structure: Uses more memory as each member has its own space.
o Union: Uses less memory as all members share the same space.
2. Access:
o Structure: All members can be accessed and modified independently.
o Union: Only one member can be accessed at a time; modifying one
member affects all.
3. Use Case:
o Structure: Suitable for storing related but different data items.
o Union: Suitable for storing different data items in the same memory
location, useful for memory-efficient storage.

8. What is nested structure? Explain syntax and example.

Nested Structure in C
A nested structure in C is a structure within another structure. This allows you to create
complex data types that group related data together in a hierarchical manner.

Syntax
Here’s the syntax for defining a nested structure:
struct OuterStructure {
dataType1 member1;
dataType2 member2;
struct InnerStructure {
dataType3 member3;
dataType4 member4;
} innerMember;
};

Example
Let’s consider an example where we have a Person structure that contains
an Address structure:
#include <stdio.h>
#include <string.h>

// Define the inner structure


struct Address {
char street[50];
char city[50];
int zip;
};

// Define the outer structure


struct Person {
char name[50];
int age;
struct Address address; // Nested structure
};

int main() {
// Declare and initialize a variable of type Person
struct Person person1;

// Assign values to the members


strcpy(person1.name, "John Doe");
person1.age = 30;
strcpy(person1.address.street, "123 Main St");
strcpy(person1.address.city, "Springfield");
person1.address.zip = 12345;

// Access and print the values


printf("Name: %s\n", person1.name);
printf("Age: %d\n", person1.age);
printf("Address: %s, %s, %d\n", person1.address.street,
person1.address.city, person1.address.zip);

return 0;
}

Key Points

• Nested structures allow you to logically group related data.


• Accessing Members: Use the dot operator to access members of both the outer
and inner structures (e.g., person1.address.street).

9. Explain different type of file and How to implement in C?


Types of Files in C
In C, files are used to store data permanently on a storage device. There are two main
types of files:

1. Text Files
2. Binary Files

1. Text Files

• Definition: Text files store data in the form of ASCII characters. Each line of text
is terminated with a newline character (\n).
• Usage: Suitable for storing readable data like plain text, source code, etc.
• Extension: Typically have extensions like .txt.

2. Binary Files

• Definition: Binary files store data in binary format (0s and 1s). They are not
human-readable and are used to store data like images, audio, video, and
compiled programs.
• Usage: Suitable for storing non-text data.
• Extension: Typically have extensions like .bin.

File Handling in C
C provides several functions for file handling, which are declared in
the <stdio.h> header file. Here are the main functions used for file operations:

1. fopen()
2. fclose()
3. fprintf()
4. fscanf()
5. fwrite()
6. fread()
7. fseek()
8. rewind()

Example: Working with Text Files


Creating and Writing to a Text File:
#include <stdio.h>

int main() {
FILE *file_ptr;
file_ptr = fopen("example.txt", "w"); // Open file for writing

if (file_ptr == NULL) {
printf("Error opening file!\n");
return 1;
}

fprintf(file_ptr, "Hello, World!\n"); // Write to file


fclose(file_ptr); // Close the file

return 0;
}

Reading from a Text File:


#include <stdio.h>
int main() {
FILE *file_ptr;
char buffer[100];

file_ptr = fopen("example.txt", "r"); // Open file for reading

if (file_ptr == NULL) {
printf("Error opening file!\n");
return 1;
}

while (fgets(buffer, 100, file_ptr) != NULL) {


printf("%s", buffer); // Print each line
}

fclose(file_ptr); // Close the file

return 0;
}

Example: Working with Binary Files


Writing to a Binary File:
#include <stdio.h>

int main() {
FILE *file_ptr;
int numbers[] = {1, 2, 3, 4, 5};

file_ptr = fopen("example.bin", "wb"); // Open file for writing in binary


mode

if (file_ptr == NULL) {
printf("Error opening file!\n");
return 1;
}

fwrite(numbers, sizeof(int), 5, file_ptr); // Write array to file


fclose(file_ptr); // Close the file

return 0;
}

Reading from a Binary File:


#include <stdio.h>
int main() {
FILE *file_ptr;
int numbers[5];

file_ptr = fopen("example.bin", "rb"); // Open file for reading in binary


mode

if (file_ptr == NULL) {
printf("Error opening file!\n");
return 1;
}

fread(numbers, sizeof(int), 5, file_ptr); // Read array from file

for (int i = 0; i < 5; i++) {


printf("%d ", numbers[i]); // Print each number
}

fclose(file_ptr); // Close the file

return 0;
}

Summary

• Text Files: Store data as ASCII characters, suitable for readable data.
• Binary Files: Store data in binary format, suitable for non-text data.
• File Handling
Functions: fopen(), fclose(), fprintf(), fscanf(), fwrite(), fread(), fseek(), r
ewind().

10. Explain different file management functions.

In C, file management functions are essential for performing various operations on


files, such as creating, opening, reading, writing, and closing files.

1. fopen()

• Purpose: Opens a file and returns a file pointer.


• Syntax: FILE *fopen(const char *filename, const char *mode);
• Modes:
o "r": Open for reading.
o "w": Open for writing (creates a new file or truncates an existing file).
o "a": Open for appending (creates a new file if it doesn’t exist).
o "rb", "wb", "ab": Same as above but in binary mode.
o "r+", "w+", "a+": Open for reading and writing.
o "rb+", "wb+", "ab+": Same as above but in binary mode.

Example:

FILE *file_ptr;

file_ptr = fopen("example.txt", "r");

if (file_ptr == NULL) {

printf("Error opening file!\n");

2. fclose()

• Purpose: Closes an opened file.


• Syntax: int fclose(FILE *stream);

Example:

fclose(file_ptr);

3. fprintf()

• Purpose: Writes formatted output to a file.


• Syntax: int fprintf(FILE *stream, const char *format, ...);

Example:

fprintf(file_ptr, "Hello, World!\n");

4. fscanf()

• Purpose: Reads formatted input from a file.


• Syntax: int fscanf(FILE *stream, const char *format, ...);

Example:

int num;

fscanf(file_ptr, "%d", &num);

5. fwrite()
• Purpose: Writes data to a binary file.
• Syntax: size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);

Example:

int numbers[] = {1, 2, 3, 4, 5};

fwrite(numbers, sizeof(int), 5, file_ptr);

6. fread()

• Purpose: Reads data from a binary file.


• Syntax: size_t fread(void *ptr, size_t size, size_t count, FILE *stream);

Example:

int numbers[5];

fread(numbers, sizeof(int), 5, file_ptr);

7. fseek()

• Purpose: Moves the file pointer to a specific location.


• Syntax: int fseek(FILE *stream, long int offset, int whence);
• Parameters:
o offset: Number of bytes to move the pointer.
o whence: Position from where offset is added
(SEEK_SET, SEEK_CUR, SEEK_END).

Example:

fseek(file_ptr, 0, SEEK_SET); // Move to the beginning of the file

8. rewind()

• Purpose: Moves the file pointer to the beginning of the file.


• Syntax: void rewind(FILE *stream);

Example:

rewind(file_ptr);

9. getc()

• Purpose: Reads a character from a file.


• Syntax: int getc(FILE *stream);

Example:

char ch;

ch = getc(file_ptr);

10. putc()

• Purpose: Writes a character to a file.


• Syntax: int putc(int char, FILE *stream);

Example:

putc('A', file_ptr);

11. Write syntax and use of sizeof() operator.

The sizeof() operator in C is used to determine the size, in bytes, of a data type or a
variable. It is a compile-time unary operator, meaning it is evaluated during the
compilation of the program.

Syntax
sizeof(dataType);
sizeof(variable);

Usage Examples
1. Using sizeof with Data Types

#include <stdio.h>

int main() {
printf("Size of char: %lu bytes\n", sizeof(char));
printf("Size of int: %lu bytes\n", sizeof(int));
printf("Size of float: %lu bytes\n", sizeof(float));
printf("Size of double: %lu bytes\n", sizeof(double));
return 0;
}
2. Using sizeof with Variables

#include <stdio.h>
int main() {
int a;
float b;
double c;
char d;

printf("Size of a: %lu bytes\n", sizeof(a));


printf("Size of b: %lu bytes\n", sizeof(b));
printf("Size of c: %lu bytes\n", sizeof(c));
printf("Size of d: %lu bytes\n", sizeof(d));
return 0;
}
3. Using sizeof with Arrays:

#include <stdio.h>

int main() {
int arr[10];
printf("Size of array: %lu bytes\n", sizeof(arr));
printf("Number of elements in array: %lu\n", sizeof(arr) / sizeof(arr[0]));
return 0;
}

12. Explain different storage classes available in C.

In C, storage classes define the scope, visibility, and lifetime of variables and
functions. There are four primary storage classes:
1. auto

Scope: Local to the block in which it is defined.


Lifetime: Exists only during the execution of the block.
Default: This is the default storage class for local variables.
Initialization: Not initialized by default; contains garbage value.

Example:

void function() {

auto int x = 10; // 'auto' keyword is optional

printf("%d\n", x);
}

2. extern

Scope: Global, can be accessed across multiple files.


Lifetime: Exists for the entire duration of the program.
Usage: Used to declare a global variable or function in another file.

Example:

// File1.c

#include <stdio.h>

extern int x; // Declaration of external variable

void function() {

printf("%d\n", x);

// File2.c

int x = 10; // Definition of external variable

3. static

Scope: Local to the block in which it is defined, but retains its value between
function calls.
Lifetime: Exists for the entire duration of the program.
Usage: Used to maintain state information between function calls.

Example:

void function() {

static int x = 0; // Static variable


x++;

printf("%d\n", x);

4. register

Scope: Local to the block in which it is defined.


Lifetime: Exists only during the execution of the block.
Usage: Suggests that the variable be stored in a CPU register for faster access.
Note: The compiler may ignore this request.

Example:

void function() {

register int x = 10; // Register variable

printf("%d\n", x);

Summary:

• auto: Default for local variables, limited to block scope.


• extern: Global scope, used for variables/functions across multiple files.
• static: Local scope but retains value between function calls.
• register: Suggests storage in CPU register for faster access.

13. Explain Bitwise operator with an example.

Bitwise Operators in C
Bitwise operators in C are used to perform operations at the bit level. These
operators work on the binary representation of data. Here are the main bitwise
operators:
1. Bitwise AND (&)
2. Bitwise OR (|)
3. Bitwise XOR (^)
4. Bitwise NOT (~)
5. Left Shift (<<)
6. Right Shift (>>)
Examples and Explanation
1. Bitwise AND (&)

Operation: Each bit of the output is 1 if the corresponding bits of both operands are
1.
Example:

#include <stdio.h>

int main() {

int a = 12; // 00001100 in binary

int b = 25; // 00011001 in binary

int result = a & b; // 00001000 in binary, which is 8 in decimal

printf("a & b = %d\n", result);

return 0;

2. Bitwise OR (|)

Operation: Each bit of the output is 1 if at least one of the corresponding bits of
either operand is 1.
Example:

#include <stdio.h>
int main() {

int a = 12; // 00001100 in binary

int b = 25; // 00011001 in binary

int result = a | b; // 00011101 in binary, which is 29 in decimal

printf("a | b = %d\n", result);

return 0;

3. Bitwise XOR (^)

Operation: Each bit of the output is 1 if the corresponding bits of the operands are
different.
Example:

#include <stdio.h>

int main() {

int a = 12; // 00001100 in binary

int b = 25; // 00011001 in binary

int result = a ^ b; // 00010101 in binary, which is 21 in decimal

printf("a ^ b = %d\n", result);

return 0;

4. Bitwise NOT (~)

Operation: Inverts all the bits of the operand.


Example:
#include <stdio.h>

int main() {

int a = 12; // 00001100 in binary

int result = ~a; // 11110011 in binary (2's complement), which is -13 in decimal

printf("~a = %d\n", result);

return 0;

5. Left Shift (<<)

Operation: Shifts the bits of the first operand to the left by the number of positions
specified by the second operand.
Example:

#include <stdio.h>

int main() {

int a = 12; // 00001100 in binary

int result = a << 2; // 00110000 in binary, which is 48 in decimal

printf("a << 2 = %d\n", result);

return 0;

6. Right Shift (>>)

Operation: Shifts the bits of the first operand to the right by the number of positions
specified by the second operand.
Example:

#include <stdio.h>

int main() {

int a = 12; // 00001100 in binary

int result = a >> 2; // 00000011 in binary, which is 3 in decimal

printf("a >> 2 = %d\n", result);

return 0;

Summary
• Bitwise AND (&): Both bits must be 1.
• Bitwise OR (|): At least one bit must be 1.
• Bitwise XOR (^): Bits must be different.
• Bitwise NOT (~): Inverts all bits.
• Left Shift (<<): Shifts bits to the left.
• Right Shift (>>): Shifts bits to the right.

14. What is Preprocessor? Explain with an example.

Preprocessor in C
A preprocessor in C is a program that processes the source code before it is compiled. It
performs various text substitution tasks, such as including header files, defining macros,
and conditional compilation. The preprocessor directives begin with a # symbol.
Types of Preprocessor Directives
1. Macros
2. File Inclusion
3. Conditional Compilation
4. Other Directives
1. Macros
Macros are fragments of code that are given a name. Whenever the name is encountered
in the program, it is replaced by the actual code fragment.
Syntax:
#define MACRO_NAME value
Example:
#include <stdio.h>

#define PI 3.1415

int main() {
float radius = 5.0;
float area = PI * radius * radius;
printf("Area of the circle: %.2f\n", area);
return 0;
}
2. File Inclusion
The #include directive is used to include the contents of a file into the source code.
Syntax:
#include <header_file>
#include "user_defined_file.h"
Example:
#include <stdio.h>
#include "my_header.h"

int main() {
// Code that uses functions or variables from my_header.h
return 0;
}
3. Conditional Compilation
Conditional compilation allows you to compile certain parts of the code based on specific
conditions.
Syntax:
#ifdef MACRO
// Code to include if MACRO is defined
#endif
Example:
#include <stdio.h>

#define DEBUG

int main() {
#ifdef DEBUG
printf("Debug mode is enabled\n");
#endif
printf("Program is running\n");
return 0;
}
Explanation
• Macros: Simplify code by replacing repetitive patterns.
• File Inclusion: Modularize code by including external files.
• Conditional Compilation: Compile code conditionally based on defined macros.

15. List out different error in C. Mention in one or two statement how to
solve each error?

Types of Errors in C and How to Solve Them


1. Syntax Errors
o Description: Occur when the rules of the C language syntax are violated.
o Solution: Carefully check the code for missing semicolons, mismatched
parentheses, or incorrect keywords. The compiler usually points out the location
of these errors.
2. Runtime Errors
o Description: Occur during the execution of the program, such as division by zero
or accessing invalid array indices.
o Solution: Use proper error handling, such as checking for zero before division
and ensuring array indices are within bounds.
3. Logical Errors
o Description: The program compiles and runs but produces incorrect results due
to flawed logic.
o Solution: Debug the program by checking the logic and flow of the code. Use
print statements or a debugger to trace variable values and program execution.
4. Semantic Errors
o Description: Occur when statements are syntactically correct but do not make
sense in the context of the program.
o Solution: Ensure that the operations and functions used are appropriate for the
data types and context.
5. Linker Errors
o Description: Occur when the linker cannot resolve references to external
symbols, such as functions or variables.
o Solution: Ensure all necessary object files and libraries are included, and that
function prototypes and definitions match.
Summary
• Syntax Errors: Fix typos and syntax issues as indicated by the compiler.
• Runtime Errors: Implement proper error handling and boundary checks.
• Logical Errors: Debug and verify the program logic.
• Semantic Errors: Ensure meaningful and contextually correct statements.
• Linker Errors: Include all required files and ensure correct function prototypes.

You might also like