C Programming
C Programming
# 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.
# 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.
# 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.
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.
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.
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
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");
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;
return 0;
}
Output
Enter marks: 80
Grade A
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
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
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.
Output
12345
Output
12345
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.
Output
1234
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
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.
Used to display a string on the screen. Used to read a string from the keyboard.
Automatically appends a newline (\n) after Reads characters until Enter key is pressed.
displaying the string.
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;
}
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
Example:
int add(int a, int b)
{
return a + b;
}
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
# 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);
}
Example:
int x = 100; // Global variable
void display()
{
extern int x;
printf("%d", x);
}
Example:
void counter()
{
static int count = 0;
count++;
printf("%d ", count);
}
Output:
123
Example:
void display()
{
register int i;
for(i = 1; i <= 5; i++)
printf("%d ", i);
}
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.
int main()
{
display();
display();
display();
return 0;
}
Output
123
int main()
{
display();
display();
display();
return 0;
}
Output
123
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
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 = #
Example:
printf("%d", *ptr);
Output:
10
Program Example
#include <stdio.h>
int main()
{
int num = 25;
int *ptr;
ptr = #
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.
Output:
10
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]);
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
Expanded by the preprocessor before compilation. Executed during program run time.
Increases program size because code is expanded Reduces program size because only one copy of
wherever used. the function exists.
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.
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().
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.
"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.
"wb" Opens a binary file for writing only. Creates a new file or overwrites an existing file.
"wb+" Opens a binary file for reading and writing. Existing contents are erased.
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");
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);