FOP assignment_3
FOP assignment_3
#include <stdio.h>
int main() {
int var = 789;
int *ptr; // Single pointer
int **d_ptr; // Double pointer
return 0;
}
2. Difference between call by value and call by reference. Explain with
an example.
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>
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.
int main() {
int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr; // ptr points to the first element of arr
return 0;
}
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
return 0;
}
Summary
int main() {
// Declare a function pointer
void (*funcPtr)(int);
// Assign the address of the function to the pointer
funcPtr = &printNumber;
return 0;
}
int main() {
// Array of function pointers
void (*operations[])(int, int) = {add, subtract, multiply};
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.
1. malloc()
2. calloc()
3. realloc()
4. free()
1. malloc()
• 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
6. Explain User define datatype structure and union with syntax and
example.
Example:
#include <stdio.h>
#include <string.h>
struct Person {
char name[50];
int age;
float height;
};
int main() {
struct Person person1;
// 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;
return 0;
}
• 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
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;
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.
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>
int main() {
// Declare and initialize a variable of type Person
struct Person person1;
return 0;
}
Key Points
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()
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;
}
return 0;
}
if (file_ptr == NULL) {
printf("Error opening file!\n");
return 1;
}
return 0;
}
int main() {
FILE *file_ptr;
int numbers[] = {1, 2, 3, 4, 5};
if (file_ptr == NULL) {
printf("Error opening file!\n");
return 1;
}
return 0;
}
if (file_ptr == NULL) {
printf("Error opening file!\n");
return 1;
}
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().
1. fopen()
Example:
FILE *file_ptr;
if (file_ptr == NULL) {
2. fclose()
Example:
fclose(file_ptr);
3. fprintf()
Example:
4. fscanf()
Example:
int 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:
6. fread()
Example:
int numbers[5];
7. fseek()
Example:
8. rewind()
Example:
rewind(file_ptr);
9. getc()
Example:
char ch;
ch = getc(file_ptr);
10. putc()
Example:
putc('A', file_ptr);
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;
#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;
}
In C, storage classes define the scope, visibility, and lifetime of variables and
functions. There are four primary storage classes:
1. auto
Example:
void function() {
printf("%d\n", x);
}
2. extern
Example:
// File1.c
#include <stdio.h>
void function() {
printf("%d\n", x);
// File2.c
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() {
printf("%d\n", x);
4. register
Example:
void function() {
printf("%d\n", x);
Summary:
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() {
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() {
return 0;
Operation: Each bit of the output is 1 if the corresponding bits of the operands are
different.
Example:
#include <stdio.h>
int main() {
return 0;
int main() {
int result = ~a; // 11110011 in binary (2's complement), which is -13 in decimal
return 0;
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() {
return 0;
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() {
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.
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?