0% found this document useful (0 votes)
2 views31 pages

C Programming

Uploaded by

dummylakhamje
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views31 pages

C Programming

Uploaded by

dummylakhamje
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

# Program Execution and Error Types

1.​ Syntax Errors


○​ Explanation: These occur when you violate the grammatical rules (syntax) of the C
language. The compiler detects these errors during the compilation phase and will not
produce an object file until they are fixed.
○​ Example: Forgetting a semicolon (;) at the end of a statement or missing a closing curly
bracket }.

2.​ Semantic Errors


○​ Explanation: These are displayed as warnings during compilation. They happen when a
statement is syntactically correct but has no meaning to the compiler. The program will still
compile, but it may cause issues later.
○​ Example: Declaring a variable but never using it in the code; the compiler may warn that
the "code has no effect".

3.​ Linker Errors


○​ Explanation: These occur after successful compilation when the linker cannot find the
object code for a function you have called (often from the standard library). The executable
file (.exe) will not be created until these are resolved.
○​ Example: Calling a standard function like printf() but failing to include the correct
header file or having a missing library definition.

4.​ Logical Errors


○​ Explanation: The program compiles and runs successfully, but it produces incorrect results.
These are the hardest to find because the computer does exactly what you told it to do, but
your logic was flawed.
○​ Example: Calculating the average of three numbers using an integer variable instead of a
float (e.g., 25/3 results in 8 instead of 8.33), which causes the fractional part to be lost.

5.​ Runtime Errors


○​ Explanation: These are detected only when the program is running. They cause the program
to stop abruptly or "crash" because it encountered an operation it could not perform.
○​ Example: A "Divide by zero" error, which happens if a division operation has a
denominator that evaluates to zero during execution.

# Preprocessor Directives
●​ Definition and Timing:
○​ Preprocessor directives are special statements in a C program that start with the # character.
○​ They are handled by a system program called the preprocessor, which processes the source
code before the actual compilation begins.​

●​ The #include Directive:


○​ This directive is used to reference "header files" (such as stdio.h) that contain essential
information for the compiler.
○​ These files allow the program to use standard library functions like printf() for output
and scanf() for input.
○​ The preprocessor automatically handles the inclusion of this required information during the
preparation phase.​

●​ The #define Directive:


○​ This is used to create Symbolic Constants, which assign a name to a specific numeric value,
character, or string constant.
○​ Syntax: #define name text (where 'name' is typically written in uppercase).
○​ Before compilation, the preprocessor replaces every occurrence of the symbolic name in the
program with its defined text or value.​

●​ Advantages of Using Directives:


○​ Ease of Modification: If a constant value (like a tax rate) needs to be changed, it only needs
to be updated once in the #define a statement rather than at every location it appears in the
code.
○​ Readability: It allows programmers to use meaningful names instead of "magic numbers,"
making the program logic easier to understand.
○​ Time Efficiency: Directives save development time by providing centralized control over
constants and facilitating the use of standard libraries.

# Categories of Constants
1. Integer Constants
●​ These constants represent whole numbers and are classified according to their number base.
●​ Decimal Integer Constants: These consist of digits 0 through 9, where the first digit cannot be 0.
●​ Octal Integer Constants: These consist of digits 0 through 7 and must always begin with the digit 0.
●​ Hexadecimal Integer Constants: these begin with the prefix 0x or 0X, followed by a combination
of digits 0–9 and letters A–F.
●​ To exceed standard limits, unsigned integers are suffixed with 'U' and long integers are suffixed with
'L'.

2. Character Constants
●​ A character constant is a single character enclosed within single quotes, such as 'A', 'x', or '3'.
●​ Each character constant has an associated integer value determined by the character set in use, such
as ASCII.
●​ Escape Sequences: Non-printable characters are represented by preceding them with a backslash (),
such as '\n' for a newline or '\t' for a horizontal tab.
●​ A null character, represented as '\0', has a value of zero.

# Categories of Operators
Definition of Operator
●​ An operator is a symbol that performs a specific operation or evaluation on one or more operands.
●​ An operand is a subexpression or data item upon which an operator acts.

Categories of Operators in C
1. Arithmetic Operators
●​ These are used to perform mathematical calculations.
●​ They are binary operators, meaning they require two operands.
●​ Common operators include:
○​ Addition (+) and Subtraction (-).
○​ Multiplication (*) and Division (/).
○​ Modular Division (%): This yields the remainder after an integer division and can only be
used with integer operands.

2. Relational Operators
●​ These operators are used to compare two variables or constants to establish a relationship between
them.
●​ The result of a relational expression is always either true or false.
●​ Common operators include:
○​ Equality (==) and Inequality (!=).
○​ Less than (<) and Less than or equal to (<=).
○​ Greater than (>) and Greater than or equal to (>=).

3. Logical Operators
●​ These are used to combine multiple simple conditions to form complex conditions or to negate a
condition.
●​ Common operators include:
○​ Logical AND (&&): Result is true only if both conditions are true.
○​ Logical OR (||): Result is true if at least one of the conditions is true.
○​ Logical NOT (!): A unary operator that reverses the truth value of a condition.

4. Assignment Operators
●​ Used to assign values, variables, or the results of expressions on the right-hand side to a variable on
the left-hand side.
●​ The basic operator is =.
●​ C also provides shorthand assignment operators like +=, -=, *=, /=, and %= to simplify coding.

5. Other Specialized Operators


●​ Increment (++) and Decrement (--): Unary operators that increase or decrease a variable's value by
one.
●​ Conditional Operator (?:): A ternary operator (takes three operands) used as a shortcut for if-else
decisions.
●​ Sizeof Operator: A unary operator used to compute the memory size (in bytes) of any data type or
object.
●​ Type Cast Operator: Used to force an expression to be of a specific data type.

# Conditional and Ternary Operators in C


Short Note on the Ternary Operator
●​ The conditional operator (?:) is uniquely referred to as the ternary operator in C because it is the
only operator that takes three operands.
●​ It is closely related to the if/else structure and is often used as a shorthand for decision-making.
●​ The expression is formed by a condition followed by two expressions separated by a colon:
(condition) ? (expression1) : (expression2);.
●​ Illustration: In the expression x = (y < 20) ? 9 : 10;, if the variable y is less than 20, the
value 9 is assigned to x; otherwise, the value 10 is assigned.
Conditional Operator
●​ The conditional operator evaluates the first operand (a condition); if the result is true, the second
operand is evaluated as the result of the entire expression.
●​ If the initial condition evaluates to false, the third operand is evaluated as the final result.

Program to find the greater number between two numbers:


#include <stdio.h>
main()
{
int a, b, max;
printf("Enter two integers: ");
scanf("%d %d", &a, &b);

/* Using conditional operator to find the greater number */


max = (a > b) ? a : b;

printf("The greater number is %d\n", max);


}

# Precedence of Operators
Definition and Importance
●​ Precedence determines the hierarchy used by C to solve mixed expressions containing different types
of operators.
●​ It defines the "highest level" and "lowest level" of priority, ensuring that higher precedence operators
are evaluated first,.
●​ When an expression contains several operators of the same level, the order of evaluation is
determined by their associativity (e.g., left to right or right to left),.

Hierarchy of Evaluation
●​ Highest Precedence: Parentheses () are at the highest level. In cases of nested parentheses, the
innermost are evaluated first.
●​ Unary Operators: This category includes Logical NOT !, increment ++, decrement --, the
sizeof operator, and type casts. They are evaluated from right to left.
●​ Arithmetic Operators: Multiplication *, division /, and modulus % take priority over addition +
and subtraction -.
●​ Relational and Equality Operators: Operators that compare values (like <, >, ==, !=) have lower
precedence than arithmetic operators.
●​ Logical Operators: Logical AND && is evaluated before Logical OR ||. Both follow left-to-right
associativity.
●​ Conditional and Assignment Operators: The ternary operator ?: and various assignment
operators (like =, +=, *=) are near the bottom of the hierarchy and evaluate from right to left.
●​ Lowest Precedence: The comma operator (,) has the lowest priority of all operators in C,.

#Typecasting in C
Definition and Purpose
●​ Typecasting is the process of forcing an expression to be of a specific data type.
●​ While C performs automatic type conversions (promoting operands to the type of the largest
operand), a programmer can use a "cast" to explicitly control the type of a calculation.
●​ It is primarily used to ensure that fractional parts are not lost during operations like division
involving integers.

Syntax and Operator Features


●​ The syntax for declaring a cast is (type) expression, where "type" is a standard C data type
such as int, float, or double.
●​ The cast is classified as a unary operator.
●​ It follows a right-to-left associativity.
●​ It has the same level of precedence as other unary operators, such as the sizeof operator and the
increment/decrement operators.

Practical Illustration
●​ Expression Example: If a variable a is an integer, writing (float) a / 5 forces the division to
evaluate as a float, preserving decimal values.
●​ Code Example: Using printf("%f", (float)num / 3); ensures the output displays the
fractional result rather than a rounded-off integer.

# The Size of Operator


Definition and Purpose
●​ The sizeof operator is a compile-time unary operator used to compute the size of any object or
data type.
●​ It calculates the number of bytes required to store an object of the type of its operand.
●​ The result of this operator is an unsigned integer value equal to the size of the specified object or
type in bytes.

Syntax and Application


●​ The operator can be used in two forms: sizeof object or sizeof(type name).
●​ It can be applied to basic data types (such as int, char, double), variables, or derived data
structures like arrays and structures.
●​ In the hierarchy of operators, sizeof has high precedence and follows right-to-left associativity.

Illustrative Examples
●​ Basic Data Types: According to the standard memory requirements in C:
○​ sizeof(char) evaluates to 1 byte.
○​ sizeof(int) evaluates to 2 bytes.
○​ sizeof(float) evaluates to 4 bytes.
○​ sizeof(double) evaluates to 8 bytes.
●​ Practical Use: If a programmer needs to know the exact memory footprint of a specific variable or a
complex structure during compilation, they use this operator to ensure portability across different
systems.

# Use of switch Statement in C


●​ The switch statement is a decision-making control statement used when one variable or expression
can have multiple possible values.
●​ It provides an alternative to multiple if-else statements.
●​ The expression is evaluated once, and its value is compared with different case values.
●​ When a matching case is found, the corresponding block of statements is executed.
●​ The break statement is used to exit the switch block after executing a case.

Syntax
switch(expression)
{
case value:
statements;
break;

default:
statements;
}

Example
#include <stdio.h>
int main()
{
int choice = 2;
switch(choice)
{
case 1:
printf("Square of number");
break;

case 2:
printf("Square root of number");
break;

case 3:
printf("Cube of number");
break;

default:
printf("Invalid choice");
}
return 0;
}

Output
Square root of number
# Difference Between Nested if and Multiple if
Nested if Multiple if

An if statement is placed inside another if or Several independent if statements are used.


else block.

The inner condition is checked only if the outer Each condition is checked separately.
condition is true.

Used when conditions are dependent on each Used when conditions are independent.
other.

Execution depends on previous condition results. More than one if block can execute.

Example of Nested if
int a = 10, b = 20;

if(a < b)
{
if(b > 15)
{
printf("Both conditions are true");
}
}

Output:
Both conditions are true

Example of Multiple if
int a = 10;

if(a > 5)
printf("Greater than 5\n");

if(a < 20)


printf("Less than 20");

Output:
Greater than 5
Less than 20

# Else-if Statement
●​ The else-if statement is used to make a multi-way decision based on several conditions.
●​ Conditions are checked from top to bottom.
●​ As soon as one condition becomes true, its corresponding statement block is executed.
●​ The remaining conditions are skipped.
●​ If none of the conditions is true, the else block is executed.
Syntax
if(condition1)
{
statements1;
}
else if(condition2)
{
statements2;
}
else
{
statements;
}

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

printf("Enter marks: ");


scanf("%d", &marks);

if(marks <= 50)


printf("Grade D");
else if(marks <= 60)
printf("Grade C");
else if(marks <= 75)
printf("Grade B");
else
printf("Grade A");

return 0;
}

Output
Enter marks: 80
Grade A

# While and For Loop


While Loop
●​ The while loop executes a statement or block of statements repeatedly as long as the given
condition is true.
●​ It is an entry-controlled loop because the condition is checked before executing the loop body.

Syntax
while(condition)
{
statements;
}

Code Segment
#include <stdio.h>
int main()
{
int i = 1;
while(i <= 5)
{
printf("%d ", i);
i++;
}
return 0;
}

Output
12345

(ii) For Loop


●​ The for loop is used when the number of iterations is known in advance.
●​ It contains initialization, condition checking, and increment/decrement in a single statement.

Syntax
for(initialization; condition; increment/decrement)
{
statements;
}

Code Segment
#include <stdio.h>
int main()
{
int i;
for(i = 1; i <= 5; i++)
{
printf("%d ", i);
}
return 0;
}

Output
12345

# Difference Between For Loop and Do-While Loop


For Loop Do-While Loop

Condition is checked before executing the loop Condition is checked after executing the loop
body. body.
May execute zero times if the condition is false Executes at least once even if the condition is
initially. false.

Used when the number of iterations is known. Used when the loop must execute at least once.

Initialization, condition, and increment/decrement Initialization, condition, and increment/decrement


are written in one statement. are written separately.

Example of For Loop


#include <stdio.h>
int main()
{
int i;
for(i = 1; i <= 5; i++)
{
printf("%d ", i);
}
return 0;
}

Output
12345

Example of Do-While Loop


#include <stdio.h>
int main()
{
int i = 1;
do
{
printf("%d ", i);
i++;
} while(i <= 5);
return 0;
}

Output
12345

# Difference Between Break Statement and Continue Statement


Break Statement Continue Statement

Terminates the loop immediately. Skips the remaining statements of the current
iteration.

Control transfers to the first statement after the Control returns to the beginning of the loop for the
loop. next iteration.
Used when it is necessary to exit a loop before its Used when some iterations need to be skipped.
normal completion.

Can be used in loops and switch statements. Can be used only in loops.

Example of Break Statement


#include <stdio.h>
int main()
{
int i;
for(i = 1; i <= 10; i++)
{
if(i == 5)
break;
printf("%d ", i);
}
return 0;
}

Output
1234

Example of Continue Statement


#include <stdio.h>
int main()
{
int i;
for(i = 1; i <= 10; i++)
{
if(i == 5)
continue;
printf("%d ", i);
}
return 0;
}

Output
1 2 3 4 6 7 8 9 10

# Goto Statement
●​ The goto statement is used to transfer program control from one part of the program to another.
●​ It causes an unconditional jump to a labeled statement.
●​ The label is an identifier followed by a colon (:).
●​ It is generally avoided because it can make programs difficult to understand and debug.

Syntax
goto label;
/* statements */
label:
statement;

Illustration
#include <stdio.h>
int main()
{
int i = 1;
while(1)
{
printf("%d ", i);
i++;
if(i > 10)
goto end;
}
end:
printf("Over");
return 0;
}

Output
1 2 3 4 5 6 7 8 9 10 Over

Use
●​ To transfer control to another part of the program.
●​ To exit from loops under specific conditions.
●​ To implement jumps when required, though structured control statements are usually preferred.

#Array Fundamentals
Definition of Array

●​ An array is a collection of similar data elements stored in contiguous memory locations.


●​ All elements of an array are of the same data type.
●​ The elements are accessed using an index (subscript).
●​ A single array name is used to refer to all elements.

Declaration of Array
●​ Array must be declared before it is used.
●​ Declaration specifies the data type, array name, and size of the array.

Syntax:
data_type array_name[size];

Example:
int marks[5];
This declares an integer array marks capable of storing 5 elements.

Initialization of Array
●​ Initialization assigns values to array elements.
●​ Values are enclosed within curly braces {} and separated by commas.

Syntax:
data_type array_name[size] = {value1, value2, ...};

Example:
int marks[5] = {10, 20, 30, 40, 50};

C Code Segment
#include <stdio.h>
int main()
{
int marks[5] = {10, 20, 30, 40, 50};
int i;
for(i = 0; i < 5; i++)
{
printf("%d ", marks[i]);
}
return 0;
}

Output
10 20 30 40 50

# strcat() Function
●​ strcat() is a string library function used to concatenate (join) two strings.
●​ It appends the contents of one string to the end of another string.
●​ It is declared in the header file string.h.
●​ The destination string must have enough space to hold the combined result.

Syntax
strcat(destination_string, source_string);

Example
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "Hello ";
char str2[] = "World";
strcat(str1, str2);
printf("%s", str1);
return 0;
}

Output
Hello World

Use of strcat()
●​ Combines two strings into a single string.
●​ Used in message creation, text processing, and string manipulation programs.
●​ Saves effort compared to manually copying characters from one string to another.

# Difference Between puts() and gets()


puts() gets()

Used to display a string on the screen. Used to read a string from the keyboard.

Output function. Input function.

Automatically appends a newline (\n) after Reads characters until Enter key is pressed.
displaying the string.

Syntax: puts(string); Syntax: gets(string);

Returns a non-negative value on success. Returns the string on success.

Example of puts()
#include <stdio.h>
int main()
{
char str[] = "Hello World";
puts(str);
return 0;
}

Output
Hello World

Example of gets()
#include <stdio.h>
int main()
{
char str[50];
printf("Enter a string: ");
gets(str);
printf("You entered: ");
puts(str);
return 0;
}

Sample Output
Enter a string: Programming
You entered: Programming

# Function in C
Definition
●​ A function is a self-contained block of statements that performs a specific task.
●​ Functions help in dividing a large program into smaller and manageable modules.
●​ A function can be called whenever required in the program.
●​ Functions improve code reusability and readability.

Function Declaration
●​ A function declaration informs the compiler about the function's name, return type, and parameters
before it is used.
●​ It is also known as a function prototype.

Syntax:
return_type function_name(parameter_list);

Example:
int add(int, int);

Function Definition
int add(int a, int b)
{
return a + b;
}

# Function Prototypes & Return Statement


Function Prototypes
●​ A function prototype is a declaration of a function that informs the compiler about:
○​ Function name
○​ Return type
○​ Number and type of arguments
●​ It is written before the function is called.
●​ It helps the compiler perform type checking of function arguments.

Syntax:
return_type function_name(parameter_list);

Example:
int add(int, int);
float area(float);

Return Statement
●​ The return statement is used to return a value from a function to the calling function.
●​ It terminates the execution of the function.
●​ A function can return only one value at a time.
●​ In void functions, return can be used without a value.

Syntax:
return expression;

Example:
int add(int a, int b)
{
return a + b;
}

# Categories of Functions in C
Functions are broadly classified into:

1. Library Functions
●​ Predefined functions provided by the C library.
●​ Available through header files.
●​ Used to perform common operations.

Examples:
●​ printf()
●​ scanf()
●​ strlen()
●​ sqrt()

2. User-Defined Functions

●​ Functions created by the programmer to perform specific tasks.


●​ Help in modular programming and code reusability.

Example:
int add(int a, int b)
{
return a + b;
}

# Call by Value & Call by Reference


Call by Value
●​ In call by value, a copy of the actual argument is passed to the function.
●​ Changes made to the parameter inside the function do not affect the original variable.
●​ Separate memory locations are used for actual and formal parameters.

Example:
#include <stdio.h>
void swap(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}

int main()
{
int x = 10, y = 20;
swap(x, y);
printf("x = %d, y = %d", x, y);
return 0;
}

Output
x = 10, y = 20

Call by Reference
●​ In call by reference, the address of the actual argument is passed to the function.
●​ Changes made inside the function affect the original variables.
●​ Same memory location is accessed through pointers.

Example:
#include <stdio.h>
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}

int main()
{
int x = 10, y = 20;
swap(&x, &y);
printf("x = %d, y = %d", x, y);
return 0;
}

Output
x = 20, y = 10

Difference Between Call by Value and Call by Reference


Call by Value Call by Reference

Copy of data is passed. Address of data is passed.

Original values remain unchanged. Original values can be modified.

Separate memory locations are used. Same memory location is accessed.

Safer but less flexible. More efficient for modifying data.

Does not use pointers. Uses pointers.

# Recursion
●​ Recursion is a process in which a function calls itself repeatedly to solve a problem.
●​ A recursive function must have a base condition to stop further function calls.
●​ It is useful for problems that can be broken down into smaller subproblems.
Factorial Using Recursion
●​ Factorial of a number n is calculated as:
○​ n! = n × (n-1)!
○​ 0! = 1 (Base Condition)

Example:
#include <stdio.h>
int factorial(int n)
{
if(n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}

int main()
{
int num = 5;
printf("Factorial = %d", factorial(num));
return 0;
}

Output
Factorial = 120

# Storage Classes in C
1. Automatic Storage Class (auto)
●​ Default storage class for local variables.
●​ Variables are created when a function is called and destroyed when it ends.
●​ Stored in memory.

Example:
void display()
{
auto int x = 10;
printf("%d", x);
}

2. External Storage Class (extern)


●​ Used to declare a global variable that is defined elsewhere.
●​ Makes a global variable accessible across multiple functions or files.
●​ Memory is allocated only once.

Example:
int x = 100; // Global variable
void display()
{
extern int x;
printf("%d", x);
}

3. Static Storage Class (static)


●​ A static variable retains its value between function calls.
●​ Initialized only once.
●​ Lifetime exists throughout the program execution.

Example:
void counter()
{
static int count = 0;
count++;
printf("%d ", count);
}

Output:
123

4. Register Storage Class (register)


●​ Requests the compiler to store the variable in a CPU register instead of memory.
●​ Used for frequently accessed variables.
●​ Faster access than ordinary variables.

Example:
void display()
{
register int i;
for(i = 1; i <= 5; i++)
printf("%d ", i);
}

# Difference Between Global Variables and Static Variables


Global Variable Static Variable

Declared outside all functions. Declared using the static keyword.

Accessible from any function in the program. If declared inside a function, its scope is limited to
that function.

Lifetime is throughout the program execution. Lifetime is also throughout the program
execution.

Value can be modified and accessed globally. Retains its value between function calls.

Default value is 0. Default value is 0.

Example of Global Variable


#include <stdio.h>
int count = 0; // Global Variable
void display()
{
count++;
printf("%d ", count);
}

int main()
{
display();
display();
display();
return 0;
}

Output
123

Example of Static Variable


#include <stdio.h>
void display()
{
static int count = 0; // Static Variable
count++;
printf("%d ", count);
}

int main()
{
display();
display();
display();
return 0;
}

Output
123

# Declaration and Usage of Structures


Structure in C
Definition
●​ A structure is a user-defined data type that allows grouping of variables of different data types under
a single name.
●​ It is used to represent a record containing related information.
●​ Each variable inside a structure is called a member.

Declaration of a Structure
Syntax:
struct structure_name
{
data_type member1;
data_type member2;
...
};

Example:
struct Student
{
int rollNo;
char name[20];
float marks;
};

Using a Structure

●​ First declare the structure.


●​ Create a structure variable.
●​ Access members using the dot (.) operator.

Example Program
#include <stdio.h>
struct Student
{
int rollNo;
char name[20];
float marks;
};

int main()
{
struct Student s1;
[Link] = 101;
strcpy([Link], "Rahul");
[Link] = 85.5;
printf("Roll No: %d\n", [Link]);
printf("Name: %s\n", [Link]);
printf("Marks: %.1f\n", [Link]);
return 0;
}

Output
Roll No: 101
Name: Rahul
Marks: 85.5
# Structures vs. Unions
Structure Union

Allocates separate memory for each member. Share the same memory among all members.

All members can contain values simultaneously. Only one member can contain a value at a time.

Size is equal to the sum of sizes of all members Size is equal to the size of its largest member.

Changing one member does not affect others. Changing one member affects the values of other
members.

Used when all data members are required. Used when memory optimization is important.

Example of Structure
#include <stdio.h>
struct Student
{
int rollNo;
float marks;
};

int main()
{
struct Student s;
[Link] = 101;
[Link] = 85.5;
printf("Roll No = %d\n", [Link]);
printf("Marks = %.1f\n", [Link]);
return 0;
}

Output
Roll No = 101
Marks = 85.5

Example of Union
#include <stdio.h>
union Data
{
int rollNo;
float marks;
};

int main()
{
union Data d;
[Link] = 101;
printf("Roll No = %d\n", [Link]);
[Link] = 85.5;
printf("Marks = %.1f\n", [Link]);
return 0;
}

Output
Roll No = 101
Marks = 85.5

# Union in C
Definition
●​ A union is a user-defined data type that allows different data types to be stored in the same memory
location.
●​ All members of a union share the same memory.
●​ At any given time, only one member can contain a valid value.
●​ It is mainly used to save memory.

Declaration of a Union
Syntax:
union union_name
{
data_type member1;
data_type member2;
...
};

Example:
union Data
{
int i;
float f;
char ch;
};

Use of a Union
●​ A union variable is declared similarly to a structure variable.
●​ Members are accessed using the dot (.) operator.
●​ Since all members share the same memory, assigning a value to one member overwrites the previous
value.

Program
#include <stdio.h>
union Data
{
int i;
float f;
char ch;
};
int main()
{
union Data d;
d.i = 100;
printf("Integer = %d\n", d.i);
d.f = 25.5;
printf("Float = %.1f\n", d.f);
[Link] = 'A';
printf("Character = %c\n", [Link]);
return 0;
}

Output
Integer = 100
Float = 25.5
Character = A

# Pointer Variable in C
Definition
●​ A pointer is a variable that stores the memory address of another variable.
●​ It helps in accessing and manipulating data indirectly.

1. Declaration of a Pointer
Syntax:
data_type *pointer_name;

Example:
int *ptr;
Here, ptr is a pointer that can store the address of an integer variable.

2. Initialization of a Pointer
A pointer is initialized by assigning it the address of a variable using the & operator.

Example:
int num = 10;
int *ptr = &num;

●​ num contains the value 10.


●​ &num gives the address of num.
●​ ptr stores that address.

3. Accessing Value Using a Pointer


The value stored at the address can be accessed using the * (dereference) operator.

Example:
printf("%d", *ptr);

Output:
10
Program Example
#include <stdio.h>
int main()
{
int num = 25;
int *ptr;
ptr = &num;
printf("Value of num = %d\n", num);
printf("Address of num = %p\n", ptr);
printf("Value using pointer = %d\n", *ptr);
return 0;
}

Output
Value of num = 25
Address of num = 6422296 (address may vary)
Value using pointer = 25

#Uses of Pointers
●​ Dynamic Memory Allocation
○​ Pointers are used to allocate memory at runtime using functions like malloc() and
calloc().
●​ Passing Arguments to Functions
○​ Allows functions to modify original variables by passing their addresses.
●​ Efficient Array and String Handling
○​ Arrays and strings can be accessed and processed efficiently using pointers.
●​ Creating Data Structures
○​ Used in linked lists, stacks, queues, trees, and graphs.
●​ Accessing Hardware Resources
○​ Helpful in system programming and embedded systems for direct memory access.

Characteristics of Pointers
1. Memory Efficiency
●​ Pointers avoid duplication of data by working with memory addresses.
●​ Large arrays or structures can be passed to functions without copying entire data.

Example:
void display(int *p)
{
printf("%d", *p);
}
Only the address is passed, saving memory.

2. Direct Address Manipulation


●​ Pointers store memory addresses and allow direct access to memory locations.
●​ The address operator (&) obtains the address, and the dereference operator (*) accesses the value.
Example:
int x = 10;
int *ptr = &x;
printf("%d", *ptr);

Output:
10

# Dynamic Memory Allocation


malloc() Function
Definition
●​ malloc() stands for Memory Allocation.
●​ It is used to allocate memory dynamically at run time.
●​ Memory is allocated from the heap area.
●​ It returns a pointer to the first byte of the allocated memory block.
●​ If memory allocation fails, it returns NULL.

Syntax
ptr = (data_type *)malloc(size_in_bytes);

Example:
int *ptr;
ptr = (int *)malloc(5 * sizeof(int));
●​ Allocates memory for 5 integer elements.
●​ sizeof(int) gives the size of one integer in bytes.

Program Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr, i;
ptr = (int *)malloc(5 * sizeof(int));
printf("Enter 5 numbers:\n");
for(i = 0; i < 5; i++)
scanf("%d", &ptr[i]);

printf("Entered numbers are:\n");


for(i = 0; i < 5; i++)
printf("%d ", ptr[i]);

free(ptr);
return 0;
}

Output
Enter 5 numbers:
10 20 30 40 50
Entered numbers are:
10 20 30 40 50

Uses of malloc()
●​ Allocates memory during program execution.
●​ Memory size can be decided at run time.
●​ Prevents wastage of memory.
●​ Useful for dynamic arrays, linked lists, stacks, queues, and other dynamic data structures.

# array of pointers
Array of Pointers
Definition
●​ An array of pointers is an array whose elements are pointers.
●​ Each element of the array stores the address of a variable.
●​ It allows efficient handling of strings, arrays, and dynamic memory.

Declaration
Syntax:
data_type *array_name[size];

Example:
int *ptr[5];
●​ ptr is an array of 5 integer pointers.
●​ Each element can store the address of an integer variable.

Example Program
#include <stdio.h>
int main()
{
int a = 10, b = 20, c = 30;
int *ptr[3];
ptr[0] = &a;
ptr[1] = &b;
ptr[2] = &c;
printf("%d\n", *ptr[0]);
printf("%d\n", *ptr[1]);
printf("%d\n", *ptr[2]);
return 0;
}

Output
10
20
30
# Difference Between Macro and Function
Macro Function

Defined using #define directive. Defined using function syntax.

Expanded by the preprocessor before compilation. Executed during program run time.

No function call overhead. Requires function call overhead.

Execution is faster. Execution is comparatively slower.

Increases program size because code is expanded Reduces program size because only one copy of
wherever used. the function exists.

No type checking of arguments. Type checking is performed.

Difficult to debug. Easier to debug and maintain.

Example of Macro
#include <stdio.h>
#define SQUARE(x) ((x) * (x))
int main()
{
printf("%d", SQUARE(5));
return 0;
}

Output
25

Example of Function
#include <stdio.h>
int square(int x)
{
return x * x;
}
int main()
{
printf("%d", square(5));
return 0;
}

Output
25
# Sequential vs. Random Access
Sequential Access File Random Access File

Records are accessed one after another in Records can be accessed directly in any order.
sequence.

To reach a specific record, all previous records Any record can be accessed directly using its
must be read. position.

Slower for searching a particular record. Faster for searching and updating records.

Simpler to implement. More complex to implement.

Suitable for processing all records sequentially. Suitable for large files requiring frequent access to
specific records.

Uses functions such as fgetc(), fgets(), and Uses functions such as fseek(), ftell(), and
fprintf(). rewind().

Sequential Access Example


FILE *fp;
fp = fopen("[Link]", "r");
/* Records are read one by one */

Random Access Example


FILE *fp;
fp = fopen("[Link]", "r");
fseek(fp, 100, SEEK_SET); // Move directly to a specific position

File Access Modes in C

File access modes specify how a file is opened and what operations can be performed on it.

Mode Description

"r" Opens an existing file for reading only. If the file does not exist, the opening fails.

"w" Open a file for writing. If the file exists, its contents are erased. Else, a new file is created.

"a" Open a file for appending. New data is added at the end of the file.

"r+" Opens an existing file for both reading and writing.

"w+" Open a file for reading and writing. Existing contents are erased.

"a+" Opens a file for reading and appending. Data is always written at the end.

"rb" Opens a binary file for reading only.

"wb" Opens a binary file for writing only. Creates a new file or overwrites an existing file.

"ab" Opens a binary file for appending.


"rb+" Opens a binary file for both reading and writing.

"wb+" Opens a binary file for reading and writing. Existing contents are erased.

"ab+" Opens a binary file for reading and appending.

Syntax
FILE *fp;
fp = fopen("filename", "mode");

Examples
Read Mode
fp = fopen("[Link]", "r");

Write Mode
fp = fopen("[Link]", "w");

Append Mode
fp = fopen("[Link]", "a");

Binary Read Mode


fp = fopen("[Link]", "rb");

# File Handling Functions


1. fopen()
Use
●​ fopen() is used to open a file.
●​ It creates a connection between the program and the file.
●​ Returns a file pointer if successful; otherwise returns NULL.

Syntax
FILE *fp;
fp = fopen("filename", "mode");

Example
FILE *fp;
fp = fopen("[Link]", "r");

2. fclose()
Use
●​ fclose() is used to close an opened file.
●​ It releases the memory associated with the file.

Syntax
fclose(file_pointer);

Example
fclose(fp);
3. fseek()
Use
●​ fseek() is used to move the file pointer to a specific location in a file.
●​ Useful for random access of files.

Syntax
fseek(file_pointer, offset, position);

Example
fseek(fp, 10, SEEK_SET);
Moves the file pointer 10 bytes from the beginning.

4. ftell()
Use
●​ ftell() returns the current position of the file pointer.
●​ Useful for determining file size and current location.

Syntax
long int pos;
pos = ftell(file_pointer);

Example
long int pos;
pos = ftell(fp);
printf("%ld", pos);

5. fputc()
Use
●​ fputc() writes a single character to a file.
●​ Returns the character written if successful.

Syntax
fputc(character, file_pointer);

Example
FILE *fp;
fp = fopen("[Link]", "w");
fputc('A', fp);
fclose(fp);

You might also like